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::VisitOverflowBehaviorType(
6443 const OverflowBehaviorType *T) {
6444 return Visit(T: T->getUnderlyingType());
6445}
6446
6447bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6448 return false;
6449}
6450
6451bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6452 return false;
6453}
6454
6455bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6456 const ArrayParameterType *T) {
6457 return VisitConstantArrayType(T);
6458}
6459
6460bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6461 const DependentBitIntType *T) {
6462 return false;
6463}
6464
6465bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6466 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6467 S.Diag(Loc: SR.getBegin(), DiagID: S.getLangOpts().CPlusPlus11
6468 ? diag::warn_cxx98_compat_template_arg_local_type
6469 : diag::ext_template_arg_local_type)
6470 << S.Context.getCanonicalTagType(TD: Tag) << SR;
6471 return true;
6472 }
6473
6474 if (!Tag->hasNameForLinkage()) {
6475 S.Diag(Loc: SR.getBegin(),
6476 DiagID: S.getLangOpts().CPlusPlus11 ?
6477 diag::warn_cxx98_compat_template_arg_unnamed_type :
6478 diag::ext_template_arg_unnamed_type) << SR;
6479 S.Diag(Loc: Tag->getLocation(), DiagID: diag::note_template_unnamed_type_here);
6480 return true;
6481 }
6482
6483 return false;
6484}
6485
6486bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6487 NestedNameSpecifier NNS) {
6488 switch (NNS.getKind()) {
6489 case NestedNameSpecifier::Kind::Null:
6490 case NestedNameSpecifier::Kind::Namespace:
6491 case NestedNameSpecifier::Kind::Global:
6492 case NestedNameSpecifier::Kind::MicrosoftSuper:
6493 return false;
6494 case NestedNameSpecifier::Kind::Type:
6495 return Visit(T: QualType(NNS.getAsType(), 0));
6496 }
6497 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6498}
6499
6500bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6501 const HLSLAttributedResourceType *T) {
6502 if (T->hasContainedType() && Visit(T: T->getContainedType()))
6503 return true;
6504 return Visit(T: T->getWrappedType());
6505}
6506
6507bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6508 const HLSLInlineSpirvType *T) {
6509 for (auto &Operand : T->getOperands())
6510 if (Operand.isConstant() && Operand.isLiteral())
6511 if (Visit(T: Operand.getResultType()))
6512 return true;
6513 return false;
6514}
6515
6516bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6517 assert(ArgInfo && "invalid TypeSourceInfo");
6518 QualType Arg = ArgInfo->getType();
6519 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6520 QualType CanonArg = Context.getCanonicalType(T: Arg);
6521
6522 if (CanonArg->isVariablyModifiedType()) {
6523 return Diag(Loc: SR.getBegin(), DiagID: diag::err_variably_modified_template_arg) << Arg;
6524 } else if (Context.hasSameUnqualifiedType(T1: Arg, T2: Context.OverloadTy)) {
6525 return Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_overload_type) << SR;
6526 }
6527
6528 // C++03 [temp.arg.type]p2:
6529 // A local type, a type with no linkage, an unnamed type or a type
6530 // compounded from any of these types shall not be used as a
6531 // template-argument for a template type-parameter.
6532 //
6533 // C++11 allows these, and even in C++03 we allow them as an extension with
6534 // a warning.
6535 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6536 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6537 (void)Finder.Visit(T: CanonArg);
6538 }
6539
6540 return false;
6541}
6542
6543enum NullPointerValueKind {
6544 NPV_NotNullPointer,
6545 NPV_NullPointer,
6546 NPV_Error
6547};
6548
6549/// Determine whether the given template argument is a null pointer
6550/// value of the appropriate type.
6551static NullPointerValueKind
6552isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param,
6553 QualType ParamType, Expr *Arg,
6554 Decl *Entity = nullptr) {
6555 if (Arg->isValueDependent() || Arg->isTypeDependent())
6556 return NPV_NotNullPointer;
6557
6558 // dllimport'd entities aren't constant but are available inside of template
6559 // arguments.
6560 if (Entity && Entity->hasAttr<DLLImportAttr>())
6561 return NPV_NotNullPointer;
6562
6563 if (!S.isCompleteType(Loc: Arg->getExprLoc(), T: ParamType))
6564 llvm_unreachable(
6565 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6566
6567 if (!S.getLangOpts().CPlusPlus11)
6568 return NPV_NotNullPointer;
6569
6570 // Determine whether we have a constant expression.
6571 ExprResult ArgRV = S.DefaultFunctionArrayConversion(E: Arg);
6572 if (ArgRV.isInvalid())
6573 return NPV_Error;
6574 Arg = ArgRV.get();
6575
6576 Expr::EvalResult EvalResult;
6577 SmallVector<PartialDiagnosticAt, 8> Notes;
6578 EvalResult.Diag = &Notes;
6579 if (!Arg->EvaluateAsRValue(Result&: EvalResult, Ctx: S.Context) ||
6580 EvalResult.HasSideEffects) {
6581 SourceLocation DiagLoc = Arg->getExprLoc();
6582
6583 // If our only note is the usual "invalid subexpression" note, just point
6584 // the caret at its location rather than producing an essentially
6585 // redundant note.
6586 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6587 diag::note_invalid_subexpr_in_const_expr) {
6588 DiagLoc = Notes[0].first;
6589 Notes.clear();
6590 }
6591
6592 S.Diag(Loc: DiagLoc, DiagID: diag::err_template_arg_not_address_constant)
6593 << Arg->getType() << Arg->getSourceRange();
6594 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6595 S.Diag(Loc: Notes[I].first, PD: Notes[I].second);
6596
6597 S.NoteTemplateParameterLocation(Decl: *Param);
6598 return NPV_Error;
6599 }
6600
6601 // C++11 [temp.arg.nontype]p1:
6602 // - an address constant expression of type std::nullptr_t
6603 if (Arg->getType()->isNullPtrType())
6604 return NPV_NullPointer;
6605
6606 // - a constant expression that evaluates to a null pointer value (4.10); or
6607 // - a constant expression that evaluates to a null member pointer value
6608 // (4.11); or
6609 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6610 (EvalResult.Val.isMemberPointer() &&
6611 !EvalResult.Val.getMemberPointerDecl())) {
6612 // If our expression has an appropriate type, we've succeeded.
6613 bool ObjCLifetimeConversion;
6614 if (S.Context.hasSameUnqualifiedType(T1: Arg->getType(), T2: ParamType) ||
6615 S.IsQualificationConversion(FromType: Arg->getType(), ToType: ParamType, CStyle: false,
6616 ObjCLifetimeConversion))
6617 return NPV_NullPointer;
6618
6619 // The types didn't match, but we know we got a null pointer; complain,
6620 // then recover as if the types were correct.
6621 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_wrongtype_null_constant)
6622 << Arg->getType() << ParamType << Arg->getSourceRange();
6623 S.NoteTemplateParameterLocation(Decl: *Param);
6624 return NPV_NullPointer;
6625 }
6626
6627 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6628 // We found a pointer that isn't null, but doesn't refer to an object.
6629 // We could just return NPV_NotNullPointer, but we can print a better
6630 // message with the information we have here.
6631 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_invalid)
6632 << EvalResult.Val.getAsString(Ctx: S.Context, Ty: ParamType);
6633 S.NoteTemplateParameterLocation(Decl: *Param);
6634 return NPV_Error;
6635 }
6636
6637 // If we don't have a null pointer value, but we do have a NULL pointer
6638 // constant, suggest a cast to the appropriate type.
6639 if (Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_NeverValueDependent)) {
6640 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6641 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_untyped_null_constant)
6642 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code)
6643 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: Arg->getEndLoc()),
6644 Code: ")");
6645 S.NoteTemplateParameterLocation(Decl: *Param);
6646 return NPV_NullPointer;
6647 }
6648
6649 // FIXME: If we ever want to support general, address-constant expressions
6650 // as non-type template arguments, we should return the ExprResult here to
6651 // be interpreted by the caller.
6652 return NPV_NotNullPointer;
6653}
6654
6655/// Checks whether the given template argument is compatible with its
6656/// template parameter.
6657static bool
6658CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param,
6659 QualType ParamType, Expr *ArgIn,
6660 Expr *Arg, QualType ArgType) {
6661 bool ObjCLifetimeConversion;
6662 if (ParamType->isPointerType() &&
6663 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6664 S.IsQualificationConversion(FromType: ArgType, ToType: ParamType, CStyle: false,
6665 ObjCLifetimeConversion)) {
6666 // For pointer-to-object types, qualification conversions are
6667 // permitted.
6668 } else {
6669 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6670 if (!ParamRef->getPointeeType()->isFunctionType()) {
6671 // C++ [temp.arg.nontype]p5b3:
6672 // For a non-type template-parameter of type reference to
6673 // object, no conversions apply. The type referred to by the
6674 // reference may be more cv-qualified than the (otherwise
6675 // identical) type of the template- argument. The
6676 // template-parameter is bound directly to the
6677 // template-argument, which shall be an lvalue.
6678
6679 // FIXME: Other qualifiers?
6680 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6681 unsigned ArgQuals = ArgType.getCVRQualifiers();
6682
6683 if ((ParamQuals | ArgQuals) != ParamQuals) {
6684 S.Diag(Loc: Arg->getBeginLoc(),
6685 DiagID: diag::err_template_arg_ref_bind_ignores_quals)
6686 << ParamType << Arg->getType() << Arg->getSourceRange();
6687 S.NoteTemplateParameterLocation(Decl: *Param);
6688 return true;
6689 }
6690 }
6691 }
6692
6693 // At this point, the template argument refers to an object or
6694 // function with external linkage. We now need to check whether the
6695 // argument and parameter types are compatible.
6696 if (!S.Context.hasSameUnqualifiedType(T1: ArgType,
6697 T2: ParamType.getNonReferenceType())) {
6698 // We can't perform this conversion or binding.
6699 if (ParamType->isReferenceType())
6700 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_no_ref_bind)
6701 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6702 else
6703 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
6704 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6705 S.NoteTemplateParameterLocation(Decl: *Param);
6706 return true;
6707 }
6708 }
6709
6710 return false;
6711}
6712
6713/// Checks whether the given template argument is the address
6714/// of an object or function according to C++ [temp.arg.nontype]p1.
6715static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6716 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6717 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6718 bool Invalid = false;
6719 Expr *Arg = ArgIn;
6720 QualType ArgType = Arg->getType();
6721
6722 bool AddressTaken = false;
6723 SourceLocation AddrOpLoc;
6724 if (S.getLangOpts().MicrosoftExt) {
6725 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6726 // dereference and address-of operators.
6727 Arg = Arg->IgnoreParenCasts();
6728
6729 bool ExtWarnMSTemplateArg = false;
6730 UnaryOperatorKind FirstOpKind;
6731 SourceLocation FirstOpLoc;
6732 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6733 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6734 if (UnOpKind == UO_Deref)
6735 ExtWarnMSTemplateArg = true;
6736 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6737 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6738 if (!AddrOpLoc.isValid()) {
6739 FirstOpKind = UnOpKind;
6740 FirstOpLoc = UnOp->getOperatorLoc();
6741 }
6742 } else
6743 break;
6744 }
6745 if (FirstOpLoc.isValid()) {
6746 if (ExtWarnMSTemplateArg)
6747 S.Diag(Loc: ArgIn->getBeginLoc(), DiagID: diag::ext_ms_deref_template_argument)
6748 << ArgIn->getSourceRange();
6749
6750 if (FirstOpKind == UO_AddrOf)
6751 AddressTaken = true;
6752 else if (Arg->getType()->isPointerType()) {
6753 // We cannot let pointers get dereferenced here, that is obviously not a
6754 // constant expression.
6755 assert(FirstOpKind == UO_Deref);
6756 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6757 << Arg->getSourceRange();
6758 }
6759 }
6760 } else {
6761 // See through any implicit casts we added to fix the type.
6762 Arg = Arg->IgnoreImpCasts();
6763
6764 // C++ [temp.arg.nontype]p1:
6765 //
6766 // A template-argument for a non-type, non-template
6767 // template-parameter shall be one of: [...]
6768 //
6769 // -- the address of an object or function with external
6770 // linkage, including function templates and function
6771 // template-ids but excluding non-static class members,
6772 // expressed as & id-expression where the & is optional if
6773 // the name refers to a function or array, or if the
6774 // corresponding template-parameter is a reference; or
6775
6776 // In C++98/03 mode, give an extension warning on any extra parentheses.
6777 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6778 bool ExtraParens = false;
6779 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6780 if (!Invalid && !ExtraParens) {
6781 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
6782 << Arg->getSourceRange();
6783 ExtraParens = true;
6784 }
6785
6786 Arg = Parens->getSubExpr();
6787 }
6788
6789 while (SubstNonTypeTemplateParmExpr *subst =
6790 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6791 Arg = subst->getReplacement()->IgnoreImpCasts();
6792
6793 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6794 if (UnOp->getOpcode() == UO_AddrOf) {
6795 Arg = UnOp->getSubExpr();
6796 AddressTaken = true;
6797 AddrOpLoc = UnOp->getOperatorLoc();
6798 }
6799 }
6800
6801 while (SubstNonTypeTemplateParmExpr *subst =
6802 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6803 Arg = subst->getReplacement()->IgnoreImpCasts();
6804 }
6805
6806 ValueDecl *Entity = nullptr;
6807 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg))
6808 Entity = DRE->getDecl();
6809 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Val: Arg))
6810 Entity = CUE->getGuidDecl();
6811
6812 // If our parameter has pointer type, check for a null template value.
6813 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6814 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ArgIn,
6815 Entity)) {
6816 case NPV_NullPointer:
6817 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
6818 SugaredConverted = TemplateArgument(ParamType,
6819 /*isNullPtr=*/true);
6820 CanonicalConverted =
6821 TemplateArgument(S.Context.getCanonicalType(T: ParamType),
6822 /*isNullPtr=*/true);
6823 return false;
6824
6825 case NPV_Error:
6826 return true;
6827
6828 case NPV_NotNullPointer:
6829 break;
6830 }
6831 }
6832
6833 // Stop checking the precise nature of the argument if it is value dependent,
6834 // it should be checked when instantiated.
6835 if (Arg->isValueDependent()) {
6836 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6837 CanonicalConverted =
6838 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6839 return false;
6840 }
6841
6842 if (!Entity) {
6843 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6844 << Arg->getSourceRange();
6845 S.NoteTemplateParameterLocation(Decl: *Param);
6846 return true;
6847 }
6848
6849 // Cannot refer to non-static data members
6850 if (isa<FieldDecl>(Val: Entity) || isa<IndirectFieldDecl>(Val: Entity)) {
6851 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_field)
6852 << Entity << Arg->getSourceRange();
6853 S.NoteTemplateParameterLocation(Decl: *Param);
6854 return true;
6855 }
6856
6857 // Cannot refer to non-static member functions
6858 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Entity)) {
6859 if (!Method->isStatic()) {
6860 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_method)
6861 << Method << Arg->getSourceRange();
6862 S.NoteTemplateParameterLocation(Decl: *Param);
6863 return true;
6864 }
6865 }
6866
6867 FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Entity);
6868 VarDecl *Var = dyn_cast<VarDecl>(Val: Entity);
6869 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Val: Entity);
6870
6871 // A non-type template argument must refer to an object or function.
6872 if (!Func && !Var && !Guid) {
6873 // We found something, but we don't know specifically what it is.
6874 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_object_or_func)
6875 << Arg->getSourceRange();
6876 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_refers_here);
6877 return true;
6878 }
6879
6880 // Address / reference template args must have external linkage in C++98.
6881 if (Entity->getFormalLinkage() == Linkage::Internal) {
6882 S.Diag(Loc: Arg->getBeginLoc(),
6883 DiagID: S.getLangOpts().CPlusPlus11
6884 ? diag::warn_cxx98_compat_template_arg_object_internal
6885 : diag::ext_template_arg_object_internal)
6886 << !Func << Entity << Arg->getSourceRange();
6887 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6888 << !Func;
6889 } else if (!Entity->hasLinkage()) {
6890 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_object_no_linkage)
6891 << !Func << Entity << Arg->getSourceRange();
6892 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6893 << !Func;
6894 return true;
6895 }
6896
6897 if (Var) {
6898 // A value of reference type is not an object.
6899 if (Var->getType()->isReferenceType()) {
6900 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_reference_var)
6901 << Var->getType() << Arg->getSourceRange();
6902 S.NoteTemplateParameterLocation(Decl: *Param);
6903 return true;
6904 }
6905
6906 // A template argument must have static storage duration.
6907 if (Var->getTLSKind()) {
6908 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_thread_local)
6909 << Arg->getSourceRange();
6910 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_template_arg_refers_here);
6911 return true;
6912 }
6913 }
6914
6915 if (AddressTaken && ParamType->isReferenceType()) {
6916 // If we originally had an address-of operator, but the
6917 // parameter has reference type, complain and (if things look
6918 // like they will work) drop the address-of operator.
6919 if (!S.Context.hasSameUnqualifiedType(T1: Entity->getType(),
6920 T2: ParamType.getNonReferenceType())) {
6921 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6922 << ParamType;
6923 S.NoteTemplateParameterLocation(Decl: *Param);
6924 return true;
6925 }
6926
6927 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6928 << ParamType
6929 << FixItHint::CreateRemoval(RemoveRange: AddrOpLoc);
6930 S.NoteTemplateParameterLocation(Decl: *Param);
6931
6932 ArgType = Entity->getType();
6933 }
6934
6935 // If the template parameter has pointer type, either we must have taken the
6936 // address or the argument must decay to a pointer.
6937 if (!AddressTaken && ParamType->isPointerType()) {
6938 if (Func) {
6939 // Function-to-pointer decay.
6940 ArgType = S.Context.getPointerType(T: Func->getType());
6941 } else if (Entity->getType()->isArrayType()) {
6942 // Array-to-pointer decay.
6943 ArgType = S.Context.getArrayDecayedType(T: Entity->getType());
6944 } else {
6945 // If the template parameter has pointer type but the address of
6946 // this object was not taken, complain and (possibly) recover by
6947 // taking the address of the entity.
6948 ArgType = S.Context.getPointerType(T: Entity->getType());
6949 if (!S.Context.hasSameUnqualifiedType(T1: ArgType, T2: ParamType)) {
6950 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6951 << ParamType;
6952 S.NoteTemplateParameterLocation(Decl: *Param);
6953 return true;
6954 }
6955
6956 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6957 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code: "&");
6958
6959 S.NoteTemplateParameterLocation(Decl: *Param);
6960 }
6961 }
6962
6963 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6964 Arg, ArgType))
6965 return true;
6966
6967 // Create the template argument.
6968 SugaredConverted = TemplateArgument(Entity, ParamType);
6969 CanonicalConverted =
6970 TemplateArgument(cast<ValueDecl>(Val: Entity->getCanonicalDecl()),
6971 S.Context.getCanonicalType(T: ParamType));
6972 S.MarkAnyDeclReferenced(Loc: Arg->getBeginLoc(), D: Entity, MightBeOdrUse: false);
6973 return false;
6974}
6975
6976/// Checks whether the given template argument is a pointer to
6977/// member constant according to C++ [temp.arg.nontype]p1.
6978static bool CheckTemplateArgumentPointerToMember(
6979 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
6980 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6981 bool Invalid = false;
6982
6983 Expr *Arg = ResultArg;
6984 bool ObjCLifetimeConversion;
6985
6986 // C++ [temp.arg.nontype]p1:
6987 //
6988 // A template-argument for a non-type, non-template
6989 // template-parameter shall be one of: [...]
6990 //
6991 // -- a pointer to member expressed as described in 5.3.1.
6992 DeclRefExpr *DRE = nullptr;
6993
6994 // In C++98/03 mode, give an extension warning on any extra parentheses.
6995 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6996 bool ExtraParens = false;
6997 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6998 if (!Invalid && !ExtraParens) {
6999 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
7000 << Arg->getSourceRange();
7001 ExtraParens = true;
7002 }
7003
7004 Arg = Parens->getSubExpr();
7005 }
7006
7007 while (SubstNonTypeTemplateParmExpr *subst =
7008 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
7009 Arg = subst->getReplacement()->IgnoreImpCasts();
7010
7011 // A pointer-to-member constant written &Class::member.
7012 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
7013 if (UnOp->getOpcode() == UO_AddrOf) {
7014 DRE = dyn_cast<DeclRefExpr>(Val: UnOp->getSubExpr());
7015 if (DRE && !DRE->getQualifier())
7016 DRE = nullptr;
7017 }
7018 }
7019 // A constant of pointer-to-member type.
7020 else if ((DRE = dyn_cast<DeclRefExpr>(Val: Arg))) {
7021 ValueDecl *VD = DRE->getDecl();
7022 if (VD->getType()->isMemberPointerType()) {
7023 if (isa<NonTypeTemplateParmDecl>(Val: VD)) {
7024 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7025 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7026 CanonicalConverted =
7027 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7028 } else {
7029 SugaredConverted = TemplateArgument(VD, ParamType);
7030 CanonicalConverted =
7031 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7032 S.Context.getCanonicalType(T: ParamType));
7033 }
7034 return Invalid;
7035 }
7036 }
7037
7038 DRE = nullptr;
7039 }
7040
7041 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7042
7043 // Check for a null pointer value.
7044 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ResultArg,
7045 Entity)) {
7046 case NPV_Error:
7047 return true;
7048 case NPV_NullPointer:
7049 S.Diag(Loc: ResultArg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7050 SugaredConverted = TemplateArgument(ParamType,
7051 /*isNullPtr*/ true);
7052 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(T: ParamType),
7053 /*isNullPtr*/ true);
7054 return false;
7055 case NPV_NotNullPointer:
7056 break;
7057 }
7058
7059 if (S.IsQualificationConversion(FromType: ResultArg->getType(),
7060 ToType: ParamType.getNonReferenceType(), CStyle: false,
7061 ObjCLifetimeConversion)) {
7062 ResultArg = S.ImpCastExprToType(E: ResultArg, Type: ParamType, CK: CK_NoOp,
7063 VK: ResultArg->getValueKind())
7064 .get();
7065 } else if (!S.Context.hasSameUnqualifiedType(
7066 T1: ResultArg->getType(), T2: ParamType.getNonReferenceType())) {
7067 // We can't perform this conversion.
7068 S.Diag(Loc: ResultArg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
7069 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7070 S.NoteTemplateParameterLocation(Decl: *Param);
7071 return true;
7072 }
7073
7074 if (!DRE)
7075 return S.Diag(Loc: Arg->getBeginLoc(),
7076 DiagID: diag::err_template_arg_not_pointer_to_member_form)
7077 << Arg->getSourceRange();
7078
7079 if (isa<FieldDecl>(Val: DRE->getDecl()) ||
7080 isa<IndirectFieldDecl>(Val: DRE->getDecl()) ||
7081 isa<CXXMethodDecl>(Val: DRE->getDecl())) {
7082 assert((isa<FieldDecl>(DRE->getDecl()) ||
7083 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7084 cast<CXXMethodDecl>(DRE->getDecl())
7085 ->isImplicitObjectMemberFunction()) &&
7086 "Only non-static member pointers can make it here");
7087
7088 // Okay: this is the address of a non-static member, and therefore
7089 // a member pointer constant.
7090 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7091 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7092 CanonicalConverted =
7093 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7094 } else {
7095 ValueDecl *D = DRE->getDecl();
7096 SugaredConverted = TemplateArgument(D, ParamType);
7097 CanonicalConverted =
7098 TemplateArgument(cast<ValueDecl>(Val: D->getCanonicalDecl()),
7099 S.Context.getCanonicalType(T: ParamType));
7100 }
7101 return Invalid;
7102 }
7103
7104 // We found something else, but we don't know specifically what it is.
7105 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_pointer_to_member_form)
7106 << Arg->getSourceRange();
7107 S.Diag(Loc: DRE->getDecl()->getLocation(), DiagID: diag::note_template_arg_refers_here);
7108 return true;
7109}
7110
7111/// Check a template argument against its corresponding
7112/// non-type template parameter.
7113///
7114/// This routine implements the semantics of C++ [temp.arg.nontype].
7115/// If an error occurred, it returns ExprError(); otherwise, it
7116/// returns the converted template argument. \p ParamType is the
7117/// type of the non-type template parameter after it has been instantiated.
7118ExprResult Sema::CheckTemplateArgument(NamedDecl *Param, QualType ParamType,
7119 Expr *Arg,
7120 TemplateArgument &SugaredConverted,
7121 TemplateArgument &CanonicalConverted,
7122 bool StrictCheck,
7123 CheckTemplateArgumentKind CTAK) {
7124 SourceLocation StartLoc = Arg->getBeginLoc();
7125 auto *ArgPE = dyn_cast<PackExpansionExpr>(Val: Arg);
7126 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7127 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7128 DeductionArg = NewDeductionArg;
7129 if (ArgPE) {
7130 // Recreate a pack expansion if we unwrapped one.
7131 Arg = new (Context) PackExpansionExpr(
7132 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7133 } else {
7134 Arg = DeductionArg;
7135 }
7136 };
7137
7138 // If the parameter type somehow involves auto, deduce the type now.
7139 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7140 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7141 if (IsDeduced) {
7142 // When checking a deduced template argument, deduce from its type even if
7143 // the type is dependent, in order to check the types of non-type template
7144 // arguments line up properly in partial ordering.
7145 TypeSourceInfo *TSI =
7146 Context.getTrivialTypeSourceInfo(T: ParamType, Loc: Param->getLocation());
7147 if (isa<DeducedTemplateSpecializationType>(Val: DeducedT)) {
7148 InitializedEntity Entity =
7149 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7150 InitializationKind Kind = InitializationKind::CreateForInit(
7151 Loc: DeductionArg->getBeginLoc(), /*DirectInit*/false, Init: DeductionArg);
7152 Expr *Inits[1] = {DeductionArg};
7153 ParamType =
7154 DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind, Init: Inits);
7155 if (ParamType.isNull())
7156 return ExprError();
7157 } else {
7158 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7159 Param->getTemplateDepth() + 1);
7160 ParamType = QualType();
7161 TemplateDeductionResult Result =
7162 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeductionArg, Result&: ParamType, Info,
7163 /*DependentDeduction=*/true,
7164 // We do not check constraints right now because the
7165 // immediately-declared constraint of the auto type is
7166 // also an associated constraint, and will be checked
7167 // along with the other associated constraints after
7168 // checking the template argument list.
7169 /*IgnoreConstraints=*/true);
7170 if (Result != TemplateDeductionResult::Success) {
7171 ParamType = TSI->getType();
7172 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7173 if (Result == TemplateDeductionResult::AlreadyDiagnosed)
7174 return ExprError();
7175 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param))
7176 Diag(Loc: Arg->getExprLoc(),
7177 DiagID: diag::err_non_type_template_parm_type_deduction_failure)
7178 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7179 << Arg->getSourceRange();
7180 NoteTemplateParameterLocation(Decl: *Param);
7181 return ExprError();
7182 }
7183 ParamType = SubstAutoTypeDependent(TypeWithAuto: ParamType);
7184 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7185 }
7186 }
7187 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7188 // an error. The error message normally references the parameter
7189 // declaration, but here we'll pass the argument location because that's
7190 // where the parameter type is deduced.
7191 ParamType = CheckNonTypeTemplateParameterType(T: ParamType, Loc: Arg->getExprLoc());
7192 if (ParamType.isNull()) {
7193 NoteTemplateParameterLocation(Decl: *Param);
7194 return ExprError();
7195 }
7196 }
7197
7198 // We should have already dropped all cv-qualifiers by now.
7199 assert(!ParamType.hasQualifiers() &&
7200 "non-type template parameter type cannot be qualified");
7201
7202 // If either the parameter has a dependent type or the argument is
7203 // type-dependent, there's nothing we can check now.
7204 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7205 // Force the argument to the type of the parameter to maintain invariants.
7206 if (!IsDeduced) {
7207 ExprResult E = ImpCastExprToType(
7208 E: DeductionArg, Type: ParamType.getNonLValueExprType(Context), CK: CK_Dependent,
7209 VK: ParamType->isLValueReferenceType() ? VK_LValue
7210 : ParamType->isRValueReferenceType() ? VK_XValue
7211 : VK_PRValue);
7212 if (E.isInvalid())
7213 return ExprError();
7214 setDeductionArg(E.get());
7215 }
7216 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7217 CanonicalConverted = TemplateArgument(
7218 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7219 return Arg;
7220 }
7221
7222 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7223 if (CTAK == CTAK_Deduced && !StrictCheck &&
7224 (ParamType->isReferenceType()
7225 ? !Context.hasSameType(T1: ParamType.getNonReferenceType(),
7226 T2: DeductionArg->getType())
7227 : !Context.hasSameUnqualifiedType(T1: ParamType,
7228 T2: DeductionArg->getType()))) {
7229 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7230 // we should actually be checking the type of the template argument in P,
7231 // not the type of the template argument deduced from A, against the
7232 // template parameter type.
7233 Diag(Loc: StartLoc, DiagID: diag::err_deduced_non_type_template_arg_type_mismatch)
7234 << Arg->getType() << ParamType.getUnqualifiedType();
7235 NoteTemplateParameterLocation(Decl: *Param);
7236 return ExprError();
7237 }
7238
7239 // If the argument is a pack expansion, we don't know how many times it would
7240 // expand. If we continue checking the argument, this will make the template
7241 // definition ill-formed if it would be ill-formed for any number of
7242 // expansions during instantiation time. When partial ordering or matching
7243 // template template parameters, this is exactly what we want. Otherwise, the
7244 // normal template rules apply: we accept the template if it would be valid
7245 // for any number of expansions (i.e. none).
7246 if (ArgPE && !StrictCheck) {
7247 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7248 CanonicalConverted = TemplateArgument(
7249 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7250 return Arg;
7251 }
7252
7253 // Avoid making a copy when initializing a template parameter of class type
7254 // from a template parameter object of the same type. This is going beyond
7255 // the standard, but is required for soundness: in
7256 // template<A a> struct X { X *p; X<a> *q; };
7257 // ... we need p and q to have the same type.
7258 //
7259 // Similarly, don't inject a call to a copy constructor when initializing
7260 // from a template parameter of the same type.
7261 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7262 if (ParamType->isRecordType() && isa<DeclRefExpr>(Val: InnerArg) &&
7263 Context.hasSameUnqualifiedType(T1: ParamType, T2: InnerArg->getType())) {
7264 NamedDecl *ND = cast<DeclRefExpr>(Val: InnerArg)->getDecl();
7265 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: ND)) {
7266
7267 SugaredConverted = TemplateArgument(TPO, ParamType);
7268 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7269 ParamType.getCanonicalType());
7270 return Arg;
7271 }
7272 if (isa<NonTypeTemplateParmDecl>(Val: ND)) {
7273 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7274 CanonicalConverted =
7275 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7276 return Arg;
7277 }
7278 }
7279
7280 // The initialization of the parameter from the argument is
7281 // a constant-evaluated context.
7282 EnterExpressionEvaluationContext ConstantEvaluated(
7283 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7284
7285 bool IsConvertedConstantExpression = true;
7286 if (isa<InitListExpr>(Val: DeductionArg) || ParamType->isRecordType()) {
7287 InitializationKind Kind = InitializationKind::CreateForInit(
7288 Loc: StartLoc, /*DirectInit=*/false, Init: DeductionArg);
7289 Expr *Inits[1] = {DeductionArg};
7290 InitializedEntity Entity =
7291 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7292 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7293 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Inits);
7294 if (Result.isInvalid() || !Result.get())
7295 return ExprError();
7296 Result = ActOnConstantExpression(Res: Result.get());
7297 if (Result.isInvalid() || !Result.get())
7298 return ExprError();
7299 setDeductionArg(ActOnFinishFullExpr(Expr: Result.get(), CC: Arg->getBeginLoc(),
7300 /*DiscardedValue=*/false,
7301 /*IsConstexpr=*/true,
7302 /*IsTemplateArgument=*/true)
7303 .get());
7304 IsConvertedConstantExpression = false;
7305 }
7306
7307 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7308 // C++17 [temp.arg.nontype]p1:
7309 // A template-argument for a non-type template parameter shall be
7310 // a converted constant expression of the type of the template-parameter.
7311 APValue Value;
7312 ExprResult ArgResult;
7313 if (IsConvertedConstantExpression) {
7314 ArgResult = BuildConvertedConstantExpression(
7315 From: DeductionArg, T: ParamType,
7316 CCE: StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Dest: Param);
7317 assert(!ArgResult.isUnset());
7318 if (ArgResult.isInvalid()) {
7319 NoteTemplateParameterLocation(Decl: *Param);
7320 return ExprError();
7321 }
7322 } else {
7323 ArgResult = DeductionArg;
7324 }
7325
7326 // For a value-dependent argument, CheckConvertedConstantExpression is
7327 // permitted (and expected) to be unable to determine a value.
7328 if (ArgResult.get()->isValueDependent()) {
7329 setDeductionArg(ArgResult.get());
7330 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7331 CanonicalConverted =
7332 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7333 return Arg;
7334 }
7335
7336 APValue PreNarrowingValue;
7337 ArgResult = EvaluateConvertedConstantExpression(
7338 E: ArgResult.get(), T: ParamType, Value, CCE: CCEKind::TemplateArg, /*RequireInt=*/
7339 false, PreNarrowingValue);
7340 if (ArgResult.isInvalid())
7341 return ExprError();
7342 setDeductionArg(ArgResult.get());
7343
7344 if (Value.isLValue()) {
7345 APValue::LValueBase Base = Value.getLValueBase();
7346 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7347 // For a non-type template-parameter of pointer or reference type,
7348 // the value of the constant expression shall not refer to
7349 assert(ParamType->isPointerOrReferenceType() ||
7350 ParamType->isNullPtrType());
7351 // -- a temporary object
7352 // -- a string literal
7353 // -- the result of a typeid expression, or
7354 // -- a predefined __func__ variable
7355 if (Base &&
7356 (!VD ||
7357 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(Val: VD))) {
7358 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
7359 << Arg->getSourceRange();
7360 return ExprError();
7361 }
7362
7363 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7364 VD->getType()->isArrayType() &&
7365 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7366 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7367 if (ArgPE) {
7368 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7369 CanonicalConverted =
7370 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7371 } else {
7372 SugaredConverted = TemplateArgument(VD, ParamType);
7373 CanonicalConverted =
7374 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7375 ParamType.getCanonicalType());
7376 }
7377 return Arg;
7378 }
7379
7380 // -- a subobject [until C++20]
7381 if (!getLangOpts().CPlusPlus20) {
7382 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7383 Value.isLValueOnePastTheEnd()) {
7384 Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_subobject)
7385 << Value.getAsString(Ctx: Context, Ty: ParamType);
7386 return ExprError();
7387 }
7388 assert((VD || !ParamType->isReferenceType()) &&
7389 "null reference should not be a constant expression");
7390 assert((!VD || !ParamType->isNullPtrType()) &&
7391 "non-null value of type nullptr_t?");
7392 }
7393 }
7394
7395 if (Value.isAddrLabelDiff())
7396 return Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_addr_label_diff);
7397
7398 if (ArgPE) {
7399 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7400 CanonicalConverted =
7401 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7402 } else {
7403 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7404 CanonicalConverted =
7405 TemplateArgument(Context, ParamType.getCanonicalType(), Value);
7406 }
7407 return Arg;
7408 }
7409
7410 // These should have all been handled above using the C++17 rules.
7411 assert(!ArgPE && !StrictCheck);
7412
7413 // C++ [temp.arg.nontype]p5:
7414 // The following conversions are performed on each expression used
7415 // as a non-type template-argument. If a non-type
7416 // template-argument cannot be converted to the type of the
7417 // corresponding template-parameter then the program is
7418 // ill-formed.
7419 if (ParamType->isIntegralOrEnumerationType()) {
7420 // C++11:
7421 // -- for a non-type template-parameter of integral or
7422 // enumeration type, conversions permitted in a converted
7423 // constant expression are applied.
7424 //
7425 // C++98:
7426 // -- for a non-type template-parameter of integral or
7427 // enumeration type, integral promotions (4.5) and integral
7428 // conversions (4.7) are applied.
7429
7430 if (getLangOpts().CPlusPlus11) {
7431 // C++ [temp.arg.nontype]p1:
7432 // A template-argument for a non-type, non-template template-parameter
7433 // shall be one of:
7434 //
7435 // -- for a non-type template-parameter of integral or enumeration
7436 // type, a converted constant expression of the type of the
7437 // template-parameter; or
7438 llvm::APSInt Value;
7439 ExprResult ArgResult = CheckConvertedConstantExpression(
7440 From: Arg, T: ParamType, Value, CCE: CCEKind::TemplateArg);
7441 if (ArgResult.isInvalid())
7442 return ExprError();
7443 Arg = ArgResult.get();
7444
7445 // We can't check arbitrary value-dependent arguments.
7446 if (Arg->isValueDependent()) {
7447 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7448 CanonicalConverted =
7449 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7450 return Arg;
7451 }
7452
7453 // Widen the argument value to sizeof(parameter type). This is almost
7454 // always a no-op, except when the parameter type is bool. In
7455 // that case, this may extend the argument from 1 bit to 8 bits.
7456 QualType IntegerType = ParamType;
7457 if (const auto *ED = IntegerType->getAsEnumDecl())
7458 IntegerType = ED->getIntegerType();
7459 Value = Value.extOrTrunc(width: IntegerType->isBitIntType()
7460 ? Context.getIntWidth(T: IntegerType)
7461 : Context.getTypeSize(T: IntegerType));
7462
7463 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7464 CanonicalConverted =
7465 TemplateArgument(Context, Value, Context.getCanonicalType(T: ParamType));
7466 return Arg;
7467 }
7468
7469 ExprResult ArgResult = DefaultLvalueConversion(E: Arg);
7470 if (ArgResult.isInvalid())
7471 return ExprError();
7472 Arg = ArgResult.get();
7473
7474 QualType ArgType = Arg->getType();
7475
7476 // C++ [temp.arg.nontype]p1:
7477 // A template-argument for a non-type, non-template
7478 // template-parameter shall be one of:
7479 //
7480 // -- an integral constant-expression of integral or enumeration
7481 // type; or
7482 // -- the name of a non-type template-parameter; or
7483 llvm::APSInt Value;
7484 if (!ArgType->isIntegralOrEnumerationType()) {
7485 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_integral_or_enumeral)
7486 << ArgType << Arg->getSourceRange();
7487 NoteTemplateParameterLocation(Decl: *Param);
7488 return ExprError();
7489 }
7490 if (!Arg->isValueDependent()) {
7491 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7492 QualType T;
7493
7494 public:
7495 TmplArgICEDiagnoser(QualType T) : T(T) { }
7496
7497 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7498 SourceLocation Loc) override {
7499 return S.Diag(Loc, DiagID: diag::err_template_arg_not_ice) << T;
7500 }
7501 } Diagnoser(ArgType);
7502
7503 Arg = VerifyIntegerConstantExpression(E: Arg, Result: &Value, Diagnoser).get();
7504 if (!Arg)
7505 return ExprError();
7506 }
7507
7508 // From here on out, all we care about is the unqualified form
7509 // of the argument type.
7510 ArgType = ArgType.getUnqualifiedType();
7511
7512 // Try to convert the argument to the parameter's type.
7513 if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
7514 // Okay: no conversion necessary
7515 } else if (ParamType->isBooleanType()) {
7516 // This is an integral-to-boolean conversion.
7517 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralToBoolean).get();
7518 } else if (IsIntegralPromotion(From: Arg, FromType: ArgType, ToType: ParamType) ||
7519 !ParamType->isEnumeralType()) {
7520 // This is an integral promotion or conversion.
7521 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralCast).get();
7522 } else {
7523 // We can't perform this conversion.
7524 Diag(Loc: StartLoc, DiagID: diag::err_template_arg_not_convertible)
7525 << Arg->getType() << ParamType << Arg->getSourceRange();
7526 NoteTemplateParameterLocation(Decl: *Param);
7527 return ExprError();
7528 }
7529
7530 // Add the value of this argument to the list of converted
7531 // arguments. We use the bitwidth and signedness of the template
7532 // parameter.
7533 if (Arg->isValueDependent()) {
7534 // The argument is value-dependent. Create a new
7535 // TemplateArgument with the converted expression.
7536 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7537 CanonicalConverted =
7538 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7539 return Arg;
7540 }
7541
7542 QualType IntegerType = ParamType;
7543 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7544 IntegerType = ED->getIntegerType();
7545 }
7546
7547 if (ParamType->isBooleanType()) {
7548 // Value must be zero or one.
7549 Value = Value != 0;
7550 unsigned AllowedBits = Context.getTypeSize(T: IntegerType);
7551 if (Value.getBitWidth() != AllowedBits)
7552 Value = Value.extOrTrunc(width: AllowedBits);
7553 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7554 } else {
7555 llvm::APSInt OldValue = Value;
7556
7557 // Coerce the template argument's value to the value it will have
7558 // based on the template parameter's type.
7559 unsigned AllowedBits = IntegerType->isBitIntType()
7560 ? Context.getIntWidth(T: IntegerType)
7561 : Context.getTypeSize(T: IntegerType);
7562 if (Value.getBitWidth() != AllowedBits)
7563 Value = Value.extOrTrunc(width: AllowedBits);
7564 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7565
7566 // Complain if an unsigned parameter received a negative value.
7567 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7568 (OldValue.isSigned() && OldValue.isNegative())) {
7569 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_negative)
7570 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7571 << Arg->getSourceRange();
7572 NoteTemplateParameterLocation(Decl: *Param);
7573 }
7574
7575 // Complain if we overflowed the template parameter's type.
7576 unsigned RequiredBits;
7577 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7578 RequiredBits = OldValue.getActiveBits();
7579 else if (OldValue.isUnsigned())
7580 RequiredBits = OldValue.getActiveBits() + 1;
7581 else
7582 RequiredBits = OldValue.getSignificantBits();
7583 if (RequiredBits > AllowedBits) {
7584 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_too_large)
7585 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7586 << Arg->getSourceRange();
7587 NoteTemplateParameterLocation(Decl: *Param);
7588 }
7589 }
7590
7591 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7592 SugaredConverted = TemplateArgument(Context, Value, T);
7593 CanonicalConverted =
7594 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7595 return Arg;
7596 }
7597
7598 QualType ArgType = Arg->getType();
7599 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7600
7601 // Handle pointer-to-function, reference-to-function, and
7602 // pointer-to-member-function all in (roughly) the same way.
7603 if (// -- For a non-type template-parameter of type pointer to
7604 // function, only the function-to-pointer conversion (4.3) is
7605 // applied. If the template-argument represents a set of
7606 // overloaded functions (or a pointer to such), the matching
7607 // function is selected from the set (13.4).
7608 (ParamType->isPointerType() &&
7609 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7610 // -- For a non-type template-parameter of type reference to
7611 // function, no conversions apply. If the template-argument
7612 // represents a set of overloaded functions, the matching
7613 // function is selected from the set (13.4).
7614 (ParamType->isReferenceType() &&
7615 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7616 // -- For a non-type template-parameter of type pointer to
7617 // member function, no conversions apply. If the
7618 // template-argument represents a set of overloaded member
7619 // functions, the matching member function is selected from
7620 // the set (13.4).
7621 (ParamType->isMemberPointerType() &&
7622 ParamType->castAs<MemberPointerType>()->getPointeeType()
7623 ->isFunctionType())) {
7624
7625 if (Arg->getType() == Context.OverloadTy) {
7626 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg, TargetType: ParamType,
7627 Complain: true,
7628 Found&: FoundResult)) {
7629 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7630 return ExprError();
7631
7632 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7633 if (Res.isInvalid())
7634 return ExprError();
7635 Arg = Res.get();
7636 ArgType = Arg->getType();
7637 } else
7638 return ExprError();
7639 }
7640
7641 if (!ParamType->isMemberPointerType()) {
7642 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7643 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted,
7644 CanonicalConverted))
7645 return ExprError();
7646 return Arg;
7647 }
7648
7649 if (CheckTemplateArgumentPointerToMember(
7650 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7651 return ExprError();
7652 return Arg;
7653 }
7654
7655 if (ParamType->isPointerType()) {
7656 // -- for a non-type template-parameter of type pointer to
7657 // object, qualification conversions (4.4) and the
7658 // array-to-pointer conversion (4.2) are applied.
7659 // C++0x also allows a value of std::nullptr_t.
7660 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7661 "Only object pointers allowed here");
7662
7663 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7664 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted))
7665 return ExprError();
7666 return Arg;
7667 }
7668
7669 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7670 // -- For a non-type template-parameter of type reference to
7671 // object, no conversions apply. The type referred to by the
7672 // reference may be more cv-qualified than the (otherwise
7673 // identical) type of the template-argument. The
7674 // template-parameter is bound directly to the
7675 // template-argument, which must be an lvalue.
7676 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7677 "Only object references allowed here");
7678
7679 if (Arg->getType() == Context.OverloadTy) {
7680 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg,
7681 TargetType: ParamRefType->getPointeeType(),
7682 Complain: true,
7683 Found&: FoundResult)) {
7684 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7685 return ExprError();
7686 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7687 if (Res.isInvalid())
7688 return ExprError();
7689 Arg = Res.get();
7690 ArgType = Arg->getType();
7691 } else
7692 return ExprError();
7693 }
7694
7695 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7696 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted))
7697 return ExprError();
7698 return Arg;
7699 }
7700
7701 // Deal with parameters of type std::nullptr_t.
7702 if (ParamType->isNullPtrType()) {
7703 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7704 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7705 CanonicalConverted =
7706 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7707 return Arg;
7708 }
7709
7710 switch (isNullPointerValueTemplateArgument(S&: *this, Param, ParamType, Arg)) {
7711 case NPV_NotNullPointer:
7712 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_not_convertible)
7713 << Arg->getType() << ParamType;
7714 NoteTemplateParameterLocation(Decl: *Param);
7715 return ExprError();
7716
7717 case NPV_Error:
7718 return ExprError();
7719
7720 case NPV_NullPointer:
7721 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7722 SugaredConverted = TemplateArgument(ParamType,
7723 /*isNullPtr=*/true);
7724 CanonicalConverted = TemplateArgument(Context.getCanonicalType(T: ParamType),
7725 /*isNullPtr=*/true);
7726 return Arg;
7727 }
7728 }
7729
7730 // -- For a non-type template-parameter of type pointer to data
7731 // member, qualification conversions (4.4) are applied.
7732 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7733
7734 if (CheckTemplateArgumentPointerToMember(
7735 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7736 return ExprError();
7737 return Arg;
7738}
7739
7740static void DiagnoseTemplateParameterListArityMismatch(
7741 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7742 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7743
7744bool Sema::CheckDeclCompatibleWithTemplateTemplate(
7745 TemplateDecl *Template, TemplateTemplateParmDecl *Param,
7746 const TemplateArgumentLoc &Arg) {
7747 // C++0x [temp.arg.template]p1:
7748 // A template-argument for a template template-parameter shall be
7749 // the name of a class template or an alias template, expressed as an
7750 // id-expression. When the template-argument names a class template, only
7751 // primary class templates are considered when matching the
7752 // template template argument with the corresponding parameter;
7753 // partial specializations are not considered even if their
7754 // parameter lists match that of the template template parameter.
7755 //
7756
7757 TemplateNameKind Kind = TNK_Non_template;
7758 unsigned DiagFoundKind = 0;
7759
7760 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Val: Template)) {
7761 switch (TTP->templateParameterKind()) {
7762 case TemplateNameKind::TNK_Concept_template:
7763 DiagFoundKind = 3;
7764 break;
7765 case TemplateNameKind::TNK_Var_template:
7766 DiagFoundKind = 2;
7767 break;
7768 default:
7769 DiagFoundKind = 1;
7770 break;
7771 }
7772 Kind = TTP->templateParameterKind();
7773 } else if (isa<ConceptDecl>(Val: Template)) {
7774 Kind = TemplateNameKind::TNK_Concept_template;
7775 DiagFoundKind = 3;
7776 } else if (isa<FunctionTemplateDecl>(Val: Template)) {
7777 Kind = TemplateNameKind::TNK_Function_template;
7778 DiagFoundKind = 0;
7779 } else if (isa<VarTemplateDecl>(Val: Template)) {
7780 Kind = TemplateNameKind::TNK_Var_template;
7781 DiagFoundKind = 2;
7782 } else if (isa<ClassTemplateDecl>(Val: Template) ||
7783 isa<TypeAliasTemplateDecl>(Val: Template) ||
7784 isa<BuiltinTemplateDecl>(Val: Template)) {
7785 Kind = TemplateNameKind::TNK_Type_template;
7786 DiagFoundKind = 1;
7787 } else {
7788 assert(false && "Unexpected Decl");
7789 }
7790
7791 if (Kind == Param->templateParameterKind()) {
7792 return true;
7793 }
7794
7795 unsigned DiagKind = 0;
7796 switch (Param->templateParameterKind()) {
7797 case TemplateNameKind::TNK_Concept_template:
7798 DiagKind = 2;
7799 break;
7800 case TemplateNameKind::TNK_Var_template:
7801 DiagKind = 1;
7802 break;
7803 default:
7804 DiagKind = 0;
7805 break;
7806 }
7807 Diag(Loc: Arg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
7808 << DiagKind;
7809 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_arg_refers_to_template_here)
7810 << DiagFoundKind << Template;
7811 return false;
7812}
7813
7814/// Check a template argument against its corresponding
7815/// template template parameter.
7816///
7817/// This routine implements the semantics of C++ [temp.arg.template].
7818/// It returns true if an error occurred, and false otherwise.
7819bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7820 TemplateParameterList *Params,
7821 TemplateArgumentLoc &Arg,
7822 bool PartialOrdering,
7823 bool *StrictPackMatch) {
7824 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7825 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7826 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7827 if (!Template) {
7828 // FIXME: Handle AssumedTemplateNames
7829 // Any dependent template name is fine.
7830 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7831 return false;
7832 }
7833
7834 if (Template->isInvalidDecl())
7835 return true;
7836
7837 if (!CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg)) {
7838 return true;
7839 }
7840
7841 // C++1z [temp.arg.template]p3: (DR 150)
7842 // A template-argument matches a template template-parameter P when P
7843 // is at least as specialized as the template-argument A.
7844 if (!isTemplateTemplateParameterAtLeastAsSpecializedAs(
7845 PParam: Params, PArg: Param, AArg: Template, DefaultArgs, ArgLoc: Arg.getLocation(),
7846 PartialOrdering, StrictPackMatch))
7847 return true;
7848 // P2113
7849 // C++20[temp.func.order]p2
7850 // [...] If both deductions succeed, the partial ordering selects the
7851 // more constrained template (if one exists) as determined below.
7852 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7853 Params->getAssociatedConstraints(AC&: ParamsAC);
7854 // C++20[temp.arg.template]p3
7855 // [...] In this comparison, if P is unconstrained, the constraints on A
7856 // are not considered.
7857 if (ParamsAC.empty())
7858 return false;
7859
7860 Template->getAssociatedConstraints(AC&: TemplateAC);
7861
7862 bool IsParamAtLeastAsConstrained;
7863 if (IsAtLeastAsConstrained(D1: Param, AC1: ParamsAC, D2: Template, AC2: TemplateAC,
7864 Result&: IsParamAtLeastAsConstrained))
7865 return true;
7866 if (!IsParamAtLeastAsConstrained) {
7867 Diag(Loc: Arg.getLocation(),
7868 DiagID: diag::err_template_template_parameter_not_at_least_as_constrained)
7869 << Template << Param << Arg.getSourceRange();
7870 Diag(Loc: Param->getLocation(), DiagID: diag::note_entity_declared_at) << Param;
7871 Diag(Loc: Template->getLocation(), DiagID: diag::note_entity_declared_at) << Template;
7872 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Param, AC1: ParamsAC, D2: Template,
7873 AC2: TemplateAC);
7874 return true;
7875 }
7876 return false;
7877}
7878
7879static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7880 unsigned HereDiagID,
7881 unsigned ExternalDiagID) {
7882 if (Decl.getLocation().isValid())
7883 return S.Diag(Loc: Decl.getLocation(), DiagID: HereDiagID);
7884
7885 SmallString<128> Str;
7886 llvm::raw_svector_ostream Out(Str);
7887 PrintingPolicy PP = S.getPrintingPolicy();
7888 PP.TerseOutput = 1;
7889 Decl.print(Out, Policy: PP);
7890 return S.Diag(Loc: Decl.getLocation(), DiagID: ExternalDiagID) << Out.str();
7891}
7892
7893void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7894 std::optional<SourceRange> ParamRange) {
7895 SemaDiagnosticBuilder DB =
7896 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_decl_here,
7897 ExternalDiagID: diag::note_template_decl_external);
7898 if (ParamRange && ParamRange->isValid()) {
7899 assert(Decl.getLocation().isValid() &&
7900 "Parameter range has location when Decl does not");
7901 DB << *ParamRange;
7902 }
7903}
7904
7905void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7906 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_param_here,
7907 ExternalDiagID: diag::note_template_param_external);
7908}
7909
7910/// Given a non-type template argument that refers to a
7911/// declaration and the type of its corresponding non-type template
7912/// parameter, produce an expression that properly refers to that
7913/// declaration.
7914ExprResult Sema::BuildExpressionFromDeclTemplateArgument(
7915 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7916 NamedDecl *TemplateParam) {
7917 // C++ [temp.param]p8:
7918 //
7919 // A non-type template-parameter of type "array of T" or
7920 // "function returning T" is adjusted to be of type "pointer to
7921 // T" or "pointer to function returning T", respectively.
7922 if (ParamType->isArrayType())
7923 ParamType = Context.getArrayDecayedType(T: ParamType);
7924 else if (ParamType->isFunctionType())
7925 ParamType = Context.getPointerType(T: ParamType);
7926
7927 // For a NULL non-type template argument, return nullptr casted to the
7928 // parameter's type.
7929 if (Arg.getKind() == TemplateArgument::NullPtr) {
7930 return ImpCastExprToType(
7931 E: new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7932 Type: ParamType,
7933 CK: ParamType->getAs<MemberPointerType>()
7934 ? CK_NullToMemberPointer
7935 : CK_NullToPointer);
7936 }
7937 assert(Arg.getKind() == TemplateArgument::Declaration &&
7938 "Only declaration template arguments permitted here");
7939
7940 ValueDecl *VD = Arg.getAsDecl();
7941
7942 CXXScopeSpec SS;
7943 if (ParamType->isMemberPointerType()) {
7944 // If this is a pointer to member, we need to use a qualified name to
7945 // form a suitable pointer-to-member constant.
7946 assert(VD->getDeclContext()->isRecord() &&
7947 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7948 isa<IndirectFieldDecl>(VD)));
7949 CanQualType ClassType =
7950 Context.getCanonicalTagType(TD: cast<RecordDecl>(Val: VD->getDeclContext()));
7951 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7952 SS.MakeTrivial(Context, Qualifier, R: Loc);
7953 }
7954
7955 ExprResult RefExpr = BuildDeclarationNameExpr(
7956 SS, NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
7957 if (RefExpr.isInvalid())
7958 return ExprError();
7959
7960 // For a pointer, the argument declaration is the pointee. Take its address.
7961 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7962 if (ParamType->isPointerType() && !ElemT.isNull() &&
7963 Context.hasSimilarType(T1: ElemT, T2: ParamType->getPointeeType())) {
7964 // Decay an array argument if we want a pointer to its first element.
7965 RefExpr = DefaultFunctionArrayConversion(E: RefExpr.get());
7966 if (RefExpr.isInvalid())
7967 return ExprError();
7968 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7969 // For any other pointer, take the address (or form a pointer-to-member).
7970 RefExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_AddrOf, InputExpr: RefExpr.get());
7971 if (RefExpr.isInvalid())
7972 return ExprError();
7973 } else if (ParamType->isRecordType()) {
7974 assert(isa<TemplateParamObjectDecl>(VD) &&
7975 "arg for class template param not a template parameter object");
7976 // No conversions apply in this case.
7977 return RefExpr;
7978 } else {
7979 assert(ParamType->isReferenceType() &&
7980 "unexpected type for decl template argument");
7981 if (NonTypeTemplateParmDecl *NTTP =
7982 dyn_cast_if_present<NonTypeTemplateParmDecl>(Val: TemplateParam)) {
7983 QualType TemplateParamType = NTTP->getType();
7984 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7985 if (AT && AT->isDecltypeAuto()) {
7986 RefExpr = new (getASTContext()) SubstNonTypeTemplateParmExpr(
7987 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7988 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7989 /*PackIndex=*/std::nullopt,
7990 /*RefParam=*/true, /*Final=*/true);
7991 }
7992 }
7993 }
7994
7995 // At this point we should have the right value category.
7996 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7997 "value kind mismatch for non-type template argument");
7998
7999 // The type of the template parameter can differ from the type of the
8000 // argument in various ways; convert it now if necessary.
8001 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8002 if (!Context.hasSameType(T1: RefExpr.get()->getType(), T2: DestExprType)) {
8003 CastKind CK;
8004 if (Context.hasSimilarType(T1: RefExpr.get()->getType(), T2: DestExprType) ||
8005 IsFunctionConversion(FromType: RefExpr.get()->getType(), ToType: DestExprType)) {
8006 CK = CK_NoOp;
8007 } else if (ParamType->isVoidPointerType() &&
8008 RefExpr.get()->getType()->isPointerType()) {
8009 CK = CK_BitCast;
8010 } else {
8011 // FIXME: Pointers to members can need conversion derived-to-base or
8012 // base-to-derived conversions. We currently don't retain enough
8013 // information to convert properly (we need to track a cast path or
8014 // subobject number in the template argument).
8015 llvm_unreachable(
8016 "unexpected conversion required for non-type template argument");
8017 }
8018 RefExpr = ImpCastExprToType(E: RefExpr.get(), Type: DestExprType, CK,
8019 VK: RefExpr.get()->getValueKind());
8020 }
8021
8022 return RefExpr;
8023}
8024
8025/// Construct a new expression that refers to the given
8026/// integral template argument with the given source-location
8027/// information.
8028///
8029/// This routine takes care of the mapping from an integral template
8030/// argument (which may have any integral type) to the appropriate
8031/// literal value.
8032static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
8033 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8034 assert(OrigT->isIntegralOrEnumerationType());
8035
8036 // If this is an enum type that we're instantiating, we need to use an integer
8037 // type the same size as the enumerator. We don't want to build an
8038 // IntegerLiteral with enum type. The integer type of an enum type can be of
8039 // any integral type with C++11 enum classes, make sure we create the right
8040 // type of literal for it.
8041 QualType T = OrigT;
8042 if (const auto *ED = OrigT->getAsEnumDecl())
8043 T = ED->getIntegerType();
8044
8045 Expr *E;
8046 if (T->isAnyCharacterType()) {
8047 CharacterLiteralKind Kind;
8048 if (T->isWideCharType())
8049 Kind = CharacterLiteralKind::Wide;
8050 else if (T->isChar8Type() && S.getLangOpts().Char8)
8051 Kind = CharacterLiteralKind::UTF8;
8052 else if (T->isChar16Type())
8053 Kind = CharacterLiteralKind::UTF16;
8054 else if (T->isChar32Type())
8055 Kind = CharacterLiteralKind::UTF32;
8056 else
8057 Kind = CharacterLiteralKind::Ascii;
8058
8059 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8060 } else if (T->isBooleanType()) {
8061 E = CXXBoolLiteralExpr::Create(C: S.Context, Val: Int.getBoolValue(), Ty: T, Loc);
8062 } else {
8063 E = IntegerLiteral::Create(C: S.Context, V: Int, type: T, l: Loc);
8064 }
8065
8066 if (OrigT->isEnumeralType()) {
8067 // FIXME: This is a hack. We need a better way to handle substituted
8068 // non-type template parameters.
8069 E = CStyleCastExpr::Create(Context: S.Context, T: OrigT, VK: VK_PRValue, K: CK_IntegralCast, Op: E,
8070 BasePath: nullptr, FPO: S.CurFPFeatureOverrides(),
8071 WrittenTy: S.Context.getTrivialTypeSourceInfo(T: OrigT, Loc),
8072 L: Loc, R: Loc);
8073 }
8074
8075 return E;
8076}
8077
8078static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
8079 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8080 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8081 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8082 ILE->setType(T);
8083 return ILE;
8084 };
8085
8086 switch (Val.getKind()) {
8087 case APValue::AddrLabelDiff:
8088 // This cannot occur in a template argument at all.
8089 case APValue::Array:
8090 case APValue::Struct:
8091 case APValue::Union:
8092 // These can only occur within a template parameter object, which is
8093 // represented as a TemplateArgument::Declaration.
8094 llvm_unreachable("unexpected template argument value");
8095
8096 case APValue::Int:
8097 return BuildExpressionFromIntegralTemplateArgumentValue(S, OrigT: T, Int: Val.getInt(),
8098 Loc);
8099
8100 case APValue::Float:
8101 return FloatingLiteral::Create(C: S.Context, V: Val.getFloat(), /*IsExact=*/isexact: true,
8102 Type: T, L: Loc);
8103
8104 case APValue::FixedPoint:
8105 return FixedPointLiteral::CreateFromRawInt(
8106 C: S.Context, V: Val.getFixedPoint().getValue(), type: T, l: Loc,
8107 Scale: Val.getFixedPoint().getScale());
8108
8109 case APValue::ComplexInt: {
8110 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8111 return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
8112 S, OrigT: ElemT, Int: Val.getComplexIntReal(), Loc),
8113 BuildExpressionFromIntegralTemplateArgumentValue(
8114 S, OrigT: ElemT, Int: Val.getComplexIntImag(), Loc)});
8115 }
8116
8117 case APValue::ComplexFloat: {
8118 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8119 return MakeInitList(
8120 {FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatReal(), isexact: true,
8121 Type: ElemT, L: Loc),
8122 FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatImag(), isexact: true,
8123 Type: ElemT, L: Loc)});
8124 }
8125
8126 case APValue::Vector: {
8127 QualType ElemT = T->castAs<VectorType>()->getElementType();
8128 llvm::SmallVector<Expr *, 8> Elts;
8129 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8130 Elts.push_back(Elt: BuildExpressionFromNonTypeTemplateArgumentValue(
8131 S, T: ElemT, Val: Val.getVectorElt(I), Loc));
8132 return MakeInitList(Elts);
8133 }
8134
8135 case APValue::None:
8136 case APValue::Indeterminate:
8137 llvm_unreachable("Unexpected APValue kind.");
8138 case APValue::LValue:
8139 case APValue::MemberPointer:
8140 // There isn't necessarily a valid equivalent source-level syntax for
8141 // these; in particular, a naive lowering might violate access control.
8142 // So for now we lower to a ConstantExpr holding the value, wrapped around
8143 // an OpaqueValueExpr.
8144 // FIXME: We should have a better representation for this.
8145 ExprValueKind VK = VK_PRValue;
8146 if (T->isReferenceType()) {
8147 T = T->getPointeeType();
8148 VK = VK_LValue;
8149 }
8150 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8151 return ConstantExpr::Create(Context: S.Context, E: OVE, Result: Val);
8152 }
8153 llvm_unreachable("Unhandled APValue::ValueKind enum");
8154}
8155
8156ExprResult
8157Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
8158 SourceLocation Loc) {
8159 switch (Arg.getKind()) {
8160 case TemplateArgument::Null:
8161 case TemplateArgument::Type:
8162 case TemplateArgument::Template:
8163 case TemplateArgument::TemplateExpansion:
8164 case TemplateArgument::Pack:
8165 llvm_unreachable("not a non-type template argument");
8166
8167 case TemplateArgument::Expression:
8168 return Arg.getAsExpr();
8169
8170 case TemplateArgument::NullPtr:
8171 case TemplateArgument::Declaration:
8172 return BuildExpressionFromDeclTemplateArgument(
8173 Arg, ParamType: Arg.getNonTypeTemplateArgumentType(), Loc);
8174
8175 case TemplateArgument::Integral:
8176 return BuildExpressionFromIntegralTemplateArgumentValue(
8177 S&: *this, OrigT: Arg.getIntegralType(), Int: Arg.getAsIntegral(), Loc);
8178
8179 case TemplateArgument::StructuralValue:
8180 return BuildExpressionFromNonTypeTemplateArgumentValue(
8181 S&: *this, T: Arg.getStructuralValueType(), Val: Arg.getAsStructuralValue(), Loc);
8182 }
8183 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8184}
8185
8186/// Match two template parameters within template parameter lists.
8187static bool MatchTemplateParameterKind(
8188 Sema &S, NamedDecl *New,
8189 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8190 const NamedDecl *OldInstFrom, bool Complain,
8191 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8192 // Check the actual kind (type, non-type, template).
8193 if (Old->getKind() != New->getKind()) {
8194 if (Complain) {
8195 unsigned NextDiag = diag::err_template_param_different_kind;
8196 if (TemplateArgLoc.isValid()) {
8197 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8198 NextDiag = diag::note_template_param_different_kind;
8199 }
8200 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8201 << (Kind != Sema::TPL_TemplateMatch);
8202 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_prev_declaration)
8203 << (Kind != Sema::TPL_TemplateMatch);
8204 }
8205
8206 return false;
8207 }
8208
8209 // Check that both are parameter packs or neither are parameter packs.
8210 // However, if we are matching a template template argument to a
8211 // template template parameter, the template template parameter can have
8212 // a parameter pack where the template template argument does not.
8213 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8214 if (Complain) {
8215 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8216 if (TemplateArgLoc.isValid()) {
8217 S.Diag(Loc: TemplateArgLoc,
8218 DiagID: diag::err_template_arg_template_params_mismatch);
8219 NextDiag = diag::note_template_parameter_pack_non_pack;
8220 }
8221
8222 unsigned ParamKind = isa<TemplateTypeParmDecl>(Val: New)? 0
8223 : isa<NonTypeTemplateParmDecl>(Val: New)? 1
8224 : 2;
8225 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8226 << ParamKind << New->isParameterPack();
8227 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_parameter_pack_here)
8228 << ParamKind << Old->isParameterPack();
8229 }
8230
8231 return false;
8232 }
8233 // For non-type template parameters, check the type of the parameter.
8234 if (NonTypeTemplateParmDecl *OldNTTP =
8235 dyn_cast<NonTypeTemplateParmDecl>(Val: Old)) {
8236 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(Val: New);
8237
8238 // If we are matching a template template argument to a template
8239 // template parameter and one of the non-type template parameter types
8240 // is dependent, then we must wait until template instantiation time
8241 // to actually compare the arguments.
8242 if (Kind != Sema::TPL_TemplateTemplateParmMatch ||
8243 (!OldNTTP->getType()->isDependentType() &&
8244 !NewNTTP->getType()->isDependentType())) {
8245 // C++20 [temp.over.link]p6:
8246 // Two [non-type] template-parameters are equivalent [if] they have
8247 // equivalent types ignoring the use of type-constraints for
8248 // placeholder types
8249 QualType OldType = S.Context.getUnconstrainedType(T: OldNTTP->getType());
8250 QualType NewType = S.Context.getUnconstrainedType(T: NewNTTP->getType());
8251 if (!S.Context.hasSameType(T1: OldType, T2: NewType)) {
8252 if (Complain) {
8253 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8254 if (TemplateArgLoc.isValid()) {
8255 S.Diag(Loc: TemplateArgLoc,
8256 DiagID: diag::err_template_arg_template_params_mismatch);
8257 NextDiag = diag::note_template_nontype_parm_different_type;
8258 }
8259 S.Diag(Loc: NewNTTP->getLocation(), DiagID: NextDiag)
8260 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8261 S.Diag(Loc: OldNTTP->getLocation(),
8262 DiagID: diag::note_template_nontype_parm_prev_declaration)
8263 << OldNTTP->getType();
8264 }
8265 return false;
8266 }
8267 }
8268 }
8269 // For template template parameters, check the template parameter types.
8270 // The template parameter lists of template template
8271 // parameters must agree.
8272 else if (TemplateTemplateParmDecl *OldTTP =
8273 dyn_cast<TemplateTemplateParmDecl>(Val: Old)) {
8274 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(Val: New);
8275 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8276 return false;
8277 if (!S.TemplateParameterListsAreEqual(
8278 NewInstFrom, New: NewTTP->getTemplateParameters(), OldInstFrom,
8279 Old: OldTTP->getTemplateParameters(), Complain,
8280 Kind: (Kind == Sema::TPL_TemplateMatch
8281 ? Sema::TPL_TemplateTemplateParmMatch
8282 : Kind),
8283 TemplateArgLoc))
8284 return false;
8285 }
8286
8287 if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8288 Kind != Sema::TPL_TemplateTemplateParmMatch &&
8289 !isa<TemplateTemplateParmDecl>(Val: Old)) {
8290 const Expr *NewC = nullptr, *OldC = nullptr;
8291
8292 if (isa<TemplateTypeParmDecl>(Val: New)) {
8293 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: New)->getTypeConstraint())
8294 NewC = TC->getImmediatelyDeclaredConstraint();
8295 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: Old)->getTypeConstraint())
8296 OldC = TC->getImmediatelyDeclaredConstraint();
8297 } else if (isa<NonTypeTemplateParmDecl>(Val: New)) {
8298 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: New)
8299 ->getPlaceholderTypeConstraint())
8300 NewC = E;
8301 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: Old)
8302 ->getPlaceholderTypeConstraint())
8303 OldC = E;
8304 } else
8305 llvm_unreachable("unexpected template parameter type");
8306
8307 auto Diagnose = [&] {
8308 S.Diag(Loc: NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8309 DiagID: diag::err_template_different_type_constraint);
8310 S.Diag(Loc: OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8311 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8312 };
8313
8314 if (!NewC != !OldC) {
8315 if (Complain)
8316 Diagnose();
8317 return false;
8318 }
8319
8320 if (NewC) {
8321 if (!S.AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldC, New: NewInstFrom,
8322 NewConstr: NewC)) {
8323 if (Complain)
8324 Diagnose();
8325 return false;
8326 }
8327 }
8328 }
8329
8330 return true;
8331}
8332
8333/// Diagnose a known arity mismatch when comparing template argument
8334/// lists.
8335static
8336void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8337 TemplateParameterList *New,
8338 TemplateParameterList *Old,
8339 Sema::TemplateParameterListEqualKind Kind,
8340 SourceLocation TemplateArgLoc) {
8341 unsigned NextDiag = diag::err_template_param_list_different_arity;
8342 if (TemplateArgLoc.isValid()) {
8343 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8344 NextDiag = diag::note_template_param_list_different_arity;
8345 }
8346 S.Diag(Loc: New->getTemplateLoc(), DiagID: NextDiag)
8347 << (New->size() > Old->size())
8348 << (Kind != Sema::TPL_TemplateMatch)
8349 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8350 S.Diag(Loc: Old->getTemplateLoc(), DiagID: diag::note_template_prev_declaration)
8351 << (Kind != Sema::TPL_TemplateMatch)
8352 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8353}
8354
8355bool Sema::TemplateParameterListsAreEqual(
8356 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8357 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8358 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8359 if (Old->size() != New->size()) {
8360 if (Complain)
8361 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8362 TemplateArgLoc);
8363
8364 return false;
8365 }
8366
8367 // C++0x [temp.arg.template]p3:
8368 // A template-argument matches a template template-parameter (call it P)
8369 // when each of the template parameters in the template-parameter-list of
8370 // the template-argument's corresponding class template or alias template
8371 // (call it A) matches the corresponding template parameter in the
8372 // template-parameter-list of P. [...]
8373 TemplateParameterList::iterator NewParm = New->begin();
8374 TemplateParameterList::iterator NewParmEnd = New->end();
8375 for (TemplateParameterList::iterator OldParm = Old->begin(),
8376 OldParmEnd = Old->end();
8377 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8378 if (NewParm == NewParmEnd) {
8379 if (Complain)
8380 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8381 TemplateArgLoc);
8382 return false;
8383 }
8384 if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm,
8385 OldInstFrom, Complain, Kind,
8386 TemplateArgLoc))
8387 return false;
8388 }
8389
8390 // Make sure we exhausted all of the arguments.
8391 if (NewParm != NewParmEnd) {
8392 if (Complain)
8393 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8394 TemplateArgLoc);
8395
8396 return false;
8397 }
8398
8399 if (Kind != TPL_TemplateParamsEquivalent) {
8400 const Expr *NewRC = New->getRequiresClause();
8401 const Expr *OldRC = Old->getRequiresClause();
8402
8403 auto Diagnose = [&] {
8404 Diag(Loc: NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8405 DiagID: diag::err_template_different_requires_clause);
8406 Diag(Loc: OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8407 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8408 };
8409
8410 if (!NewRC != !OldRC) {
8411 if (Complain)
8412 Diagnose();
8413 return false;
8414 }
8415
8416 if (NewRC) {
8417 if (!AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldRC, New: NewInstFrom,
8418 NewConstr: NewRC)) {
8419 if (Complain)
8420 Diagnose();
8421 return false;
8422 }
8423 }
8424 }
8425
8426 return true;
8427}
8428
8429bool
8430Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8431 if (!S)
8432 return false;
8433
8434 // Find the nearest enclosing declaration scope.
8435 S = S->getDeclParent();
8436
8437 // C++ [temp.pre]p6: [P2096]
8438 // A template, explicit specialization, or partial specialization shall not
8439 // have C linkage.
8440 DeclContext *Ctx = S->getEntity();
8441 if (Ctx && Ctx->isExternCContext()) {
8442 SourceRange Range =
8443 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8444 ? TemplateParams->getParam(Idx: 0)->getSourceRange()
8445 : TemplateParams->getSourceRange();
8446 Diag(Loc: Range.getBegin(), DiagID: diag::err_template_linkage) << Range;
8447 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8448 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
8449 return true;
8450 }
8451 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8452
8453 // C++ [temp]p2:
8454 // A template-declaration can appear only as a namespace scope or
8455 // class scope declaration.
8456 // C++ [temp.expl.spec]p3:
8457 // An explicit specialization may be declared in any scope in which the
8458 // corresponding primary template may be defined.
8459 // C++ [temp.class.spec]p6: [P2096]
8460 // A partial specialization may be declared in any scope in which the
8461 // corresponding primary template may be defined.
8462 if (Ctx) {
8463 if (Ctx->isFileContext())
8464 return false;
8465 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Ctx)) {
8466 // C++ [temp.mem]p2:
8467 // A local class shall not have member templates.
8468 if (RD->isLocalClass())
8469 return Diag(Loc: TemplateParams->getTemplateLoc(),
8470 DiagID: diag::err_template_inside_local_class)
8471 << TemplateParams->getSourceRange();
8472 else
8473 return false;
8474 }
8475 }
8476
8477 return Diag(Loc: TemplateParams->getTemplateLoc(),
8478 DiagID: diag::err_template_outside_namespace_or_class_scope)
8479 << TemplateParams->getSourceRange();
8480}
8481
8482/// Determine what kind of template specialization the given declaration
8483/// is.
8484static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8485 if (!D)
8486 return TSK_Undeclared;
8487
8488 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D))
8489 return Record->getTemplateSpecializationKind();
8490 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D))
8491 return Function->getTemplateSpecializationKind();
8492 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D))
8493 return Var->getTemplateSpecializationKind();
8494
8495 return TSK_Undeclared;
8496}
8497
8498/// Check whether a specialization is well-formed in the current
8499/// context.
8500///
8501/// This routine determines whether a template specialization can be declared
8502/// in the current context (C++ [temp.expl.spec]p2).
8503///
8504/// \param S the semantic analysis object for which this check is being
8505/// performed.
8506///
8507/// \param Specialized the entity being specialized or instantiated, which
8508/// may be a kind of template (class template, function template, etc.) or
8509/// a member of a class template (member function, static data member,
8510/// member class).
8511///
8512/// \param PrevDecl the previous declaration of this entity, if any.
8513///
8514/// \param Loc the location of the explicit specialization or instantiation of
8515/// this entity.
8516///
8517/// \param IsPartialSpecialization whether this is a partial specialization of
8518/// a class template.
8519///
8520/// \returns true if there was an error that we cannot recover from, false
8521/// otherwise.
8522static bool CheckTemplateSpecializationScope(Sema &S,
8523 NamedDecl *Specialized,
8524 NamedDecl *PrevDecl,
8525 SourceLocation Loc,
8526 bool IsPartialSpecialization) {
8527 // Keep these "kind" numbers in sync with the %select statements in the
8528 // various diagnostics emitted by this routine.
8529 int EntityKind = 0;
8530 if (isa<ClassTemplateDecl>(Val: Specialized))
8531 EntityKind = IsPartialSpecialization? 1 : 0;
8532 else if (isa<VarTemplateDecl>(Val: Specialized))
8533 EntityKind = IsPartialSpecialization ? 3 : 2;
8534 else if (isa<FunctionTemplateDecl>(Val: Specialized))
8535 EntityKind = 4;
8536 else if (isa<CXXMethodDecl>(Val: Specialized))
8537 EntityKind = 5;
8538 else if (isa<VarDecl>(Val: Specialized))
8539 EntityKind = 6;
8540 else if (isa<RecordDecl>(Val: Specialized))
8541 EntityKind = 7;
8542 else if (isa<EnumDecl>(Val: Specialized) && S.getLangOpts().CPlusPlus11)
8543 EntityKind = 8;
8544 else {
8545 S.Diag(Loc, DiagID: diag::err_template_spec_unknown_kind)
8546 << S.getLangOpts().CPlusPlus11;
8547 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8548 return true;
8549 }
8550
8551 // C++ [temp.expl.spec]p2:
8552 // An explicit specialization may be declared in any scope in which
8553 // the corresponding primary template may be defined.
8554 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8555 S.Diag(Loc, DiagID: diag::err_template_spec_decl_function_scope)
8556 << Specialized;
8557 return true;
8558 }
8559
8560 // C++ [temp.class.spec]p6:
8561 // A class template partial specialization may be declared in any
8562 // scope in which the primary template may be defined.
8563 DeclContext *SpecializedContext =
8564 Specialized->getDeclContext()->getRedeclContext();
8565 DeclContext *DC = S.CurContext->getRedeclContext();
8566
8567 // Make sure that this redeclaration (or definition) occurs in the same
8568 // scope or an enclosing namespace.
8569 if (!(DC->isFileContext() ? DC->Encloses(DC: SpecializedContext)
8570 : DC->Equals(DC: SpecializedContext))) {
8571 if (isa<TranslationUnitDecl>(Val: SpecializedContext))
8572 S.Diag(Loc, DiagID: diag::err_template_spec_redecl_global_scope)
8573 << EntityKind << Specialized;
8574 else {
8575 auto *ND = cast<NamedDecl>(Val: SpecializedContext);
8576 int Diag = diag::err_template_spec_redecl_out_of_scope;
8577 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8578 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8579 S.Diag(Loc, DiagID: Diag) << EntityKind << Specialized
8580 << ND << isa<CXXRecordDecl>(Val: ND);
8581 }
8582
8583 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8584
8585 // Don't allow specializing in the wrong class during error recovery.
8586 // Otherwise, things can go horribly wrong.
8587 if (DC->isRecord())
8588 return true;
8589 }
8590
8591 return false;
8592}
8593
8594static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8595 if (!E->isTypeDependent())
8596 return SourceLocation();
8597 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8598 Checker.TraverseStmt(S: E);
8599 if (Checker.MatchLoc.isInvalid())
8600 return E->getSourceRange();
8601 return Checker.MatchLoc;
8602}
8603
8604static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8605 if (!TL.getType()->isDependentType())
8606 return SourceLocation();
8607 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8608 Checker.TraverseTypeLoc(TL);
8609 if (Checker.MatchLoc.isInvalid())
8610 return TL.getSourceRange();
8611 return Checker.MatchLoc;
8612}
8613
8614/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8615/// that checks non-type template partial specialization arguments.
8616static bool CheckNonTypeTemplatePartialSpecializationArgs(
8617 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8618 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8619 bool HasError = false;
8620 for (unsigned I = 0; I != NumArgs; ++I) {
8621 if (Args[I].getKind() == TemplateArgument::Pack) {
8622 if (CheckNonTypeTemplatePartialSpecializationArgs(
8623 S, TemplateNameLoc, Param, Args: Args[I].pack_begin(),
8624 NumArgs: Args[I].pack_size(), IsDefaultArgument))
8625 return true;
8626
8627 continue;
8628 }
8629
8630 if (Args[I].getKind() != TemplateArgument::Expression)
8631 continue;
8632
8633 Expr *ArgExpr = Args[I].getAsExpr();
8634 if (ArgExpr->containsErrors()) {
8635 HasError = true;
8636 continue;
8637 }
8638
8639 // We can have a pack expansion of any of the bullets below.
8640 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: ArgExpr))
8641 ArgExpr = Expansion->getPattern();
8642
8643 // Strip off any implicit casts we added as part of type checking.
8644 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
8645 ArgExpr = ICE->getSubExpr();
8646
8647 // C++ [temp.class.spec]p8:
8648 // A non-type argument is non-specialized if it is the name of a
8649 // non-type parameter. All other non-type arguments are
8650 // specialized.
8651 //
8652 // Below, we check the two conditions that only apply to
8653 // specialized non-type arguments, so skip any non-specialized
8654 // arguments.
8655 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ArgExpr))
8656 if (isa<NonTypeTemplateParmDecl>(Val: DRE->getDecl()))
8657 continue;
8658
8659 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ArgExpr);
8660 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8661 continue;
8662 }
8663
8664 // C++ [temp.class.spec]p9:
8665 // Within the argument list of a class template partial
8666 // specialization, the following restrictions apply:
8667 // -- A partially specialized non-type argument expression
8668 // shall not involve a template parameter of the partial
8669 // specialization except when the argument expression is a
8670 // simple identifier.
8671 // -- The type of a template parameter corresponding to a
8672 // specialized non-type argument shall not be dependent on a
8673 // parameter of the specialization.
8674 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8675 // We implement a compromise between the original rules and DR1315:
8676 // -- A specialized non-type template argument shall not be
8677 // type-dependent and the corresponding template parameter
8678 // shall have a non-dependent type.
8679 SourceRange ParamUseRange =
8680 findTemplateParameterInType(Depth: Param->getDepth(), E: ArgExpr);
8681 if (ParamUseRange.isValid()) {
8682 if (IsDefaultArgument) {
8683 S.Diag(Loc: TemplateNameLoc,
8684 DiagID: diag::err_dependent_non_type_arg_in_partial_spec);
8685 S.Diag(Loc: ParamUseRange.getBegin(),
8686 DiagID: diag::note_dependent_non_type_default_arg_in_partial_spec)
8687 << ParamUseRange;
8688 } else {
8689 S.Diag(Loc: ParamUseRange.getBegin(),
8690 DiagID: diag::err_dependent_non_type_arg_in_partial_spec)
8691 << ParamUseRange;
8692 }
8693 return true;
8694 }
8695
8696 ParamUseRange = findTemplateParameter(
8697 Depth: Param->getDepth(), TL: Param->getTypeSourceInfo()->getTypeLoc());
8698 if (ParamUseRange.isValid()) {
8699 S.Diag(Loc: IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8700 DiagID: diag::err_dependent_typed_non_type_arg_in_partial_spec)
8701 << Param->getType();
8702 S.NoteTemplateParameterLocation(Decl: *Param);
8703 return true;
8704 }
8705 }
8706
8707 return HasError;
8708}
8709
8710bool Sema::CheckTemplatePartialSpecializationArgs(
8711 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8712 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8713 // We have to be conservative when checking a template in a dependent
8714 // context.
8715 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8716 return false;
8717
8718 TemplateParameterList *TemplateParams =
8719 PrimaryTemplate->getTemplateParameters();
8720 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8721 NonTypeTemplateParmDecl *Param
8722 = dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: I));
8723 if (!Param)
8724 continue;
8725
8726 if (CheckNonTypeTemplatePartialSpecializationArgs(S&: *this, TemplateNameLoc,
8727 Param, Args: &TemplateArgs[I],
8728 NumArgs: 1, IsDefaultArgument: I >= NumExplicit))
8729 return true;
8730 }
8731
8732 return false;
8733}
8734
8735DeclResult Sema::ActOnClassTemplateSpecialization(
8736 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8737 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8738 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8739 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8740 assert(TUK != TagUseKind::Reference && "References are not specializations");
8741
8742 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8743 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8744 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8745
8746 // Find the class template we're specializing
8747 TemplateName Name = TemplateId.Template.get();
8748 ClassTemplateDecl *ClassTemplate
8749 = dyn_cast_or_null<ClassTemplateDecl>(Val: Name.getAsTemplateDecl());
8750
8751 if (!ClassTemplate) {
8752 Diag(Loc: TemplateNameLoc, DiagID: diag::err_not_class_template_specialization)
8753 << (Name.getAsTemplateDecl() &&
8754 isa<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl()));
8755 return true;
8756 }
8757
8758 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8759 auto Message = DSA->getMessage();
8760 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
8761 << ClassTemplate << !Message.empty() << Message;
8762 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
8763 }
8764
8765 if (S->isTemplateParamScope())
8766 EnterTemplatedContext(S, DC: ClassTemplate->getTemplatedDecl());
8767
8768 DeclContext *DC = ClassTemplate->getDeclContext();
8769
8770 bool isMemberSpecialization = false;
8771 bool isPartialSpecialization = false;
8772
8773 if (SS.isSet()) {
8774 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8775 diagnoseQualifiedDeclaration(SS, DC, Name: ClassTemplate->getDeclName(),
8776 Loc: TemplateNameLoc, TemplateId: &TemplateId,
8777 /*IsMemberSpecialization=*/false))
8778 return true;
8779 }
8780
8781 // Check the validity of the template headers that introduce this
8782 // template.
8783 // FIXME: We probably shouldn't complain about these headers for
8784 // friend declarations.
8785 bool Invalid = false;
8786 TemplateParameterList *TemplateParams =
8787 MatchTemplateParametersToScopeSpecifier(
8788 DeclStartLoc: KWLoc, DeclLoc: TemplateNameLoc, SS, TemplateId: &TemplateId, ParamLists: TemplateParameterLists,
8789 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
8790 if (Invalid)
8791 return true;
8792
8793 // Check that we can declare a template specialization here.
8794 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8795 return true;
8796
8797 if (TemplateParams && DC->isDependentContext()) {
8798 ContextRAII SavedContext(*this, DC);
8799 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
8800 return true;
8801 }
8802
8803 if (TemplateParams && TemplateParams->size() > 0) {
8804 isPartialSpecialization = true;
8805
8806 if (TUK == TagUseKind::Friend) {
8807 Diag(Loc: KWLoc, DiagID: diag::err_partial_specialization_friend)
8808 << SourceRange(LAngleLoc, RAngleLoc);
8809 return true;
8810 }
8811
8812 // C++ [temp.class.spec]p10:
8813 // The template parameter list of a specialization shall not
8814 // contain default template argument values.
8815 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8816 Decl *Param = TemplateParams->getParam(Idx: I);
8817 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
8818 if (TTP->hasDefaultArgument()) {
8819 Diag(Loc: TTP->getDefaultArgumentLoc(),
8820 DiagID: diag::err_default_arg_in_partial_spec);
8821 TTP->removeDefaultArgument();
8822 }
8823 } else if (NonTypeTemplateParmDecl *NTTP
8824 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
8825 if (NTTP->hasDefaultArgument()) {
8826 Diag(Loc: NTTP->getDefaultArgumentLoc(),
8827 DiagID: diag::err_default_arg_in_partial_spec)
8828 << NTTP->getDefaultArgument().getSourceRange();
8829 NTTP->removeDefaultArgument();
8830 }
8831 } else {
8832 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
8833 if (TTP->hasDefaultArgument()) {
8834 Diag(Loc: TTP->getDefaultArgument().getLocation(),
8835 DiagID: diag::err_default_arg_in_partial_spec)
8836 << TTP->getDefaultArgument().getSourceRange();
8837 TTP->removeDefaultArgument();
8838 }
8839 }
8840 }
8841 } else if (TemplateParams) {
8842 if (TUK == TagUseKind::Friend)
8843 Diag(Loc: KWLoc, DiagID: diag::err_template_spec_friend)
8844 << FixItHint::CreateRemoval(
8845 RemoveRange: SourceRange(TemplateParams->getTemplateLoc(),
8846 TemplateParams->getRAngleLoc()))
8847 << SourceRange(LAngleLoc, RAngleLoc);
8848 } else {
8849 assert(TUK == TagUseKind::Friend &&
8850 "should have a 'template<>' for this decl");
8851 }
8852
8853 // Check that the specialization uses the same tag kind as the
8854 // original template.
8855 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
8856 assert(Kind != TagTypeKind::Enum &&
8857 "Invalid enum tag in class template spec!");
8858 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(), NewTag: Kind,
8859 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
8860 Name: ClassTemplate->getIdentifier())) {
8861 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
8862 << ClassTemplate
8863 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
8864 Code: ClassTemplate->getTemplatedDecl()->getKindName());
8865 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
8866 DiagID: diag::note_previous_use);
8867 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8868 }
8869
8870 // Translate the parser's template argument list in our AST format.
8871 TemplateArgumentListInfo TemplateArgs =
8872 makeTemplateArgumentListInfo(S&: *this, TemplateId);
8873
8874 // Check for unexpanded parameter packs in any of the template arguments.
8875 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8876 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
8877 UPPC: isPartialSpecialization
8878 ? UPPC_PartialSpecialization
8879 : UPPC_ExplicitSpecialization))
8880 return true;
8881
8882 // Check that the template argument list is well-formed for this
8883 // template.
8884 CheckTemplateArgumentInfo CTAI;
8885 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
8886 /*DefaultArgs=*/{},
8887 /*PartialTemplateArgs=*/false, CTAI,
8888 /*UpdateArgsWithConversions=*/true))
8889 return true;
8890
8891 // Find the class template (partial) specialization declaration that
8892 // corresponds to these arguments.
8893 if (isPartialSpecialization) {
8894 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, PrimaryTemplate: ClassTemplate,
8895 NumExplicit: TemplateArgs.size(),
8896 TemplateArgs: CTAI.CanonicalConverted))
8897 return true;
8898
8899 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8900 // also do it during instantiation.
8901 if (!Name.isDependent() &&
8902 !TemplateSpecializationType::anyDependentTemplateArguments(
8903 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
8904 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
8905 << ClassTemplate->getDeclName();
8906 isPartialSpecialization = false;
8907 Invalid = true;
8908 }
8909 }
8910
8911 void *InsertPos = nullptr;
8912 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8913
8914 if (isPartialSpecialization)
8915 PrevDecl = ClassTemplate->findPartialSpecialization(
8916 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
8917 else
8918 PrevDecl =
8919 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
8920
8921 ClassTemplateSpecializationDecl *Specialization = nullptr;
8922
8923 // Check whether we can declare a class template specialization in
8924 // the current scope.
8925 if (TUK != TagUseKind::Friend &&
8926 CheckTemplateSpecializationScope(S&: *this, Specialized: ClassTemplate, PrevDecl,
8927 Loc: TemplateNameLoc,
8928 IsPartialSpecialization: isPartialSpecialization))
8929 return true;
8930
8931 if (!isPartialSpecialization) {
8932 // Create a new class template specialization declaration node for
8933 // this explicit specialization or friend declaration.
8934 Specialization = ClassTemplateSpecializationDecl::Create(
8935 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
8936 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
8937 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8938 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
8939 if (TemplateParameterLists.size() > 0) {
8940 Specialization->setTemplateParameterListsInfo(Context,
8941 TPLists: TemplateParameterLists);
8942 }
8943
8944 if (!PrevDecl)
8945 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
8946 } else {
8947 CanQualType CanonType = CanQualType::CreateUnsafe(
8948 Other: Context.getCanonicalTemplateSpecializationType(
8949 Keyword: ElaboratedTypeKeyword::None,
8950 T: TemplateName(ClassTemplate->getCanonicalDecl()),
8951 CanonicalArgs: CTAI.CanonicalConverted));
8952 if (Context.hasSameType(
8953 T1: CanonType,
8954 T2: ClassTemplate->getCanonicalInjectedSpecializationType(Ctx: Context)) &&
8955 (!Context.getLangOpts().CPlusPlus20 ||
8956 !TemplateParams->hasAssociatedConstraints())) {
8957 // C++ [temp.class.spec]p9b3:
8958 //
8959 // -- The argument list of the specialization shall not be identical
8960 // to the implicit argument list of the primary template.
8961 //
8962 // This rule has since been removed, because it's redundant given DR1495,
8963 // but we keep it because it produces better diagnostics and recovery.
8964 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
8965 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8966 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
8967 return CheckClassTemplate(
8968 S, TagSpec, TUK, KWLoc, SS, Name: ClassTemplate->getIdentifier(),
8969 NameLoc: TemplateNameLoc, Attr, TemplateParams, AS: AS_none,
8970 /*ModulePrivateLoc=*/SourceLocation(),
8971 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
8972 OuterTemplateParamLists: TemplateParameterLists.data());
8973 }
8974
8975 // Create a new class template partial specialization declaration node.
8976 ClassTemplatePartialSpecializationDecl *PrevPartial =
8977 cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl);
8978 ClassTemplatePartialSpecializationDecl *Partial =
8979 ClassTemplatePartialSpecializationDecl::Create(
8980 Context, TK: Kind, DC, StartLoc: KWLoc, IdLoc: TemplateNameLoc, Params: TemplateParams,
8981 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, CanonInjectedTST: CanonType, PrevDecl: PrevPartial);
8982 Partial->setTemplateArgsAsWritten(TemplateArgs);
8983 SetNestedNameSpecifier(S&: *this, T: Partial, SS);
8984 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8985 Partial->setTemplateParameterListsInfo(
8986 Context, TPLists: TemplateParameterLists.drop_back(N: 1));
8987 }
8988
8989 if (!PrevPartial)
8990 ClassTemplate->AddPartialSpecialization(D: Partial, InsertPos);
8991 Specialization = Partial;
8992
8993 // If we are providing an explicit specialization of a member class
8994 // template specialization, make a note of that.
8995 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8996 PrevPartial->setMemberSpecialization();
8997
8998 CheckTemplatePartialSpecialization(Partial);
8999 }
9000
9001 // C++ [temp.expl.spec]p6:
9002 // If a template, a member template or the member of a class template is
9003 // explicitly specialized then that specialization shall be declared
9004 // before the first use of that specialization that would cause an implicit
9005 // instantiation to take place, in every translation unit in which such a
9006 // use occurs; no diagnostic is required.
9007 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9008 bool Okay = false;
9009 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9010 // Is there any previous explicit specialization declaration?
9011 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9012 Okay = true;
9013 break;
9014 }
9015 }
9016
9017 if (!Okay) {
9018 SourceRange Range(TemplateNameLoc, RAngleLoc);
9019 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
9020 << Context.getCanonicalTagType(TD: Specialization) << Range;
9021
9022 Diag(Loc: PrevDecl->getPointOfInstantiation(),
9023 DiagID: diag::note_instantiation_required_here)
9024 << (PrevDecl->getTemplateSpecializationKind()
9025 != TSK_ImplicitInstantiation);
9026 return true;
9027 }
9028 }
9029
9030 // If this is not a friend, note that this is an explicit specialization.
9031 if (TUK != TagUseKind::Friend)
9032 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9033
9034 // Check that this isn't a redefinition of this specialization.
9035 if (TUK == TagUseKind::Definition) {
9036 RecordDecl *Def = Specialization->getDefinition();
9037 NamedDecl *Hidden = nullptr;
9038 bool HiddenDefVisible = false;
9039 if (Def && SkipBody &&
9040 isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible)) {
9041 SkipBody->ShouldSkip = true;
9042 SkipBody->Previous = Def;
9043 if (!HiddenDefVisible && Hidden)
9044 makeMergedDefinitionVisible(ND: Hidden);
9045 } else if (Def) {
9046 SourceRange Range(TemplateNameLoc, RAngleLoc);
9047 Diag(Loc: TemplateNameLoc, DiagID: diag::err_redefinition) << Specialization << Range;
9048 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
9049 Specialization->setInvalidDecl();
9050 return true;
9051 }
9052 }
9053
9054 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
9055 ProcessAPINotes(D: Specialization);
9056
9057 // Add alignment attributes if necessary; these attributes are checked when
9058 // the ASTContext lays out the structure.
9059 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9060 if (LangOpts.HLSL)
9061 Specialization->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
9062 AddAlignmentAttributesForRecord(RD: Specialization);
9063 AddMsStructLayoutForRecord(RD: Specialization);
9064 }
9065
9066 if (ModulePrivateLoc.isValid())
9067 Diag(Loc: Specialization->getLocation(), DiagID: diag::err_module_private_specialization)
9068 << (isPartialSpecialization? 1 : 0)
9069 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
9070
9071 // C++ [temp.expl.spec]p9:
9072 // A template explicit specialization is in the scope of the
9073 // namespace in which the template was defined.
9074 //
9075 // We actually implement this paragraph where we set the semantic
9076 // context (in the creation of the ClassTemplateSpecializationDecl),
9077 // but we also maintain the lexical context where the actual
9078 // definition occurs.
9079 Specialization->setLexicalDeclContext(CurContext);
9080
9081 // We may be starting the definition of this specialization.
9082 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9083 Specialization->startDefinition();
9084
9085 if (TUK == TagUseKind::Friend) {
9086 CanQualType CanonType = Context.getCanonicalTagType(TD: Specialization);
9087 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9088 Keyword: ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9089 QualifierLoc: SS.getWithLocInContext(Context),
9090 /*TemplateKeywordLoc=*/SourceLocation(), T: Name, TLoc: TemplateNameLoc,
9091 SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted, Canon: CanonType);
9092
9093 // Build the fully-sugared type for this class template
9094 // specialization as the user wrote in the specialization
9095 // itself. This means that we'll pretty-print the type retrieved
9096 // from the specialization's declaration the way that the user
9097 // actually wrote the specialization, rather than formatting the
9098 // name based on the "canonical" representation used to store the
9099 // template arguments in the specialization.
9100 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext,
9101 L: TemplateNameLoc,
9102 Friend_: WrittenTy,
9103 /*FIXME:*/FriendL: KWLoc);
9104 Friend->setAccess(AS_public);
9105 CurContext->addDecl(D: Friend);
9106 } else {
9107 // Add the specialization into its lexical context, so that it can
9108 // be seen when iterating through the list of declarations in that
9109 // context. However, specializations are not found by name lookup.
9110 CurContext->addDecl(D: Specialization);
9111 }
9112
9113 if (SkipBody && SkipBody->ShouldSkip)
9114 return SkipBody->Previous;
9115
9116 Specialization->setInvalidDecl(Invalid);
9117 inferGslOwnerPointerAttribute(Record: Specialization);
9118 return Specialization;
9119}
9120
9121Decl *Sema::ActOnTemplateDeclarator(Scope *S,
9122 MultiTemplateParamsArg TemplateParameterLists,
9123 Declarator &D) {
9124 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9125 ActOnDocumentableDecl(D: NewDecl);
9126 return NewDecl;
9127}
9128
9129ConceptDecl *Sema::ActOnStartConceptDefinition(
9130 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9131 const IdentifierInfo *Name, SourceLocation NameLoc) {
9132 DeclContext *DC = CurContext;
9133
9134 if (!DC->getRedeclContext()->isFileContext()) {
9135 Diag(Loc: NameLoc,
9136 DiagID: diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9137 return nullptr;
9138 }
9139
9140 if (TemplateParameterLists.size() > 1) {
9141 Diag(Loc: NameLoc, DiagID: diag::err_concept_extra_headers);
9142 return nullptr;
9143 }
9144
9145 TemplateParameterList *Params = TemplateParameterLists.front();
9146
9147 if (Params->size() == 0) {
9148 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_parameters);
9149 return nullptr;
9150 }
9151
9152 // Ensure that the parameter pack, if present, is the last parameter in the
9153 // template.
9154 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9155 ParamEnd = Params->end();
9156 ParamIt != ParamEnd; ++ParamIt) {
9157 Decl const *Param = *ParamIt;
9158 if (Param->isParameterPack()) {
9159 if (++ParamIt == ParamEnd)
9160 break;
9161 Diag(Loc: Param->getLocation(),
9162 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
9163 return nullptr;
9164 }
9165 }
9166
9167 ConceptDecl *NewDecl =
9168 ConceptDecl::Create(C&: Context, DC, L: NameLoc, Name, Params);
9169
9170 if (NewDecl->hasAssociatedConstraints()) {
9171 // C++2a [temp.concept]p4:
9172 // A concept shall not have associated constraints.
9173 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_associated_constraints);
9174 NewDecl->setInvalidDecl();
9175 }
9176
9177 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9178 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9179 forRedeclarationInCurContext());
9180 LookupName(R&: Previous, S);
9181 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9182 /*AllowInlineNamespace*/ false);
9183
9184 // We cannot properly handle redeclarations until we parse the constraint
9185 // expression, so only inject the name if we are sure we are not redeclaring a
9186 // symbol
9187 if (Previous.empty())
9188 PushOnScopeChains(D: NewDecl, S, AddToContext: true);
9189
9190 return NewDecl;
9191}
9192
9193static bool RemoveLookupResult(LookupResult &R, NamedDecl *C) {
9194 bool Found = false;
9195 LookupResult::Filter F = R.makeFilter();
9196 while (F.hasNext()) {
9197 NamedDecl *D = F.next();
9198 if (D == C) {
9199 F.erase();
9200 Found = true;
9201 break;
9202 }
9203 }
9204 F.done();
9205 return Found;
9206}
9207
9208ConceptDecl *
9209Sema::ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
9210 Expr *ConstraintExpr,
9211 const ParsedAttributesView &Attrs) {
9212 assert(!C->hasDefinition() && "Concept already defined");
9213 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr)) {
9214 C->setInvalidDecl();
9215 return nullptr;
9216 }
9217 C->setDefinition(ConstraintExpr);
9218 ProcessDeclAttributeList(S, D: C, AttrList: Attrs);
9219
9220 // Check for conflicting previous declaration.
9221 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9222 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9223 forRedeclarationInCurContext());
9224 LookupName(R&: Previous, S);
9225 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9226 /*AllowInlineNamespace*/ false);
9227 bool WasAlreadyAdded = RemoveLookupResult(R&: Previous, C);
9228 bool AddToScope = true;
9229 CheckConceptRedefinition(NewDecl: C, Previous, AddToScope);
9230
9231 ActOnDocumentableDecl(D: C);
9232 if (!WasAlreadyAdded && AddToScope)
9233 PushOnScopeChains(D: C, S);
9234
9235 return C;
9236}
9237
9238void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
9239 LookupResult &Previous, bool &AddToScope) {
9240 AddToScope = true;
9241
9242 if (Previous.empty())
9243 return;
9244
9245 auto *OldConcept = dyn_cast<ConceptDecl>(Val: Previous.getRepresentativeDecl()->getUnderlyingDecl());
9246 if (!OldConcept) {
9247 auto *Old = Previous.getRepresentativeDecl();
9248 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_kind)
9249 << NewDecl->getDeclName();
9250 notePreviousDefinition(Old, New: NewDecl->getLocation());
9251 AddToScope = false;
9252 return;
9253 }
9254 // Check if we can merge with a concept declaration.
9255 bool IsSame = Context.isSameEntity(X: NewDecl, Y: OldConcept);
9256 if (!IsSame) {
9257 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_concept)
9258 << NewDecl->getDeclName();
9259 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9260 AddToScope = false;
9261 return;
9262 }
9263 if (hasReachableDefinition(D: OldConcept) &&
9264 IsRedefinitionInModule(New: NewDecl, Old: OldConcept)) {
9265 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition)
9266 << NewDecl->getDeclName();
9267 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9268 AddToScope = false;
9269 return;
9270 }
9271 if (!Previous.isSingleResult()) {
9272 // FIXME: we should produce an error in case of ambig and failed lookups.
9273 // Other decls (e.g. namespaces) also have this shortcoming.
9274 return;
9275 }
9276 // We unwrap canonical decl late to check for module visibility.
9277 Context.setPrimaryMergedDecl(D: NewDecl, Primary: OldConcept->getCanonicalDecl());
9278}
9279
9280bool Sema::CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc) {
9281 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Val: Concept);
9282 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9283 Diag(Loc, DiagID: diag::err_recursive_concept) << CE;
9284 Diag(Loc: CE->getLocation(), DiagID: diag::note_declared_at);
9285 return true;
9286 }
9287 // Concept template parameters don't have a definition and can't
9288 // be defined recursively.
9289 return false;
9290}
9291
9292/// \brief Strips various properties off an implicit instantiation
9293/// that has just been explicitly specialized.
9294static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9295 if (MinGW || (isa<FunctionDecl>(Val: D) &&
9296 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization()))
9297 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9298
9299 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D))
9300 FD->setInlineSpecified(false);
9301}
9302
9303/// Compute the diagnostic location for an explicit instantiation
9304// declaration or definition.
9305static SourceLocation DiagLocForExplicitInstantiation(
9306 NamedDecl* D, SourceLocation PointOfInstantiation) {
9307 // Explicit instantiations following a specialization have no effect and
9308 // hence no PointOfInstantiation. In that case, walk decl backwards
9309 // until a valid name loc is found.
9310 SourceLocation PrevDiagLoc = PointOfInstantiation;
9311 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9312 Prev = Prev->getPreviousDecl()) {
9313 PrevDiagLoc = Prev->getLocation();
9314 }
9315 assert(PrevDiagLoc.isValid() &&
9316 "Explicit instantiation without point of instantiation?");
9317 return PrevDiagLoc;
9318}
9319
9320bool
9321Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9322 TemplateSpecializationKind NewTSK,
9323 NamedDecl *PrevDecl,
9324 TemplateSpecializationKind PrevTSK,
9325 SourceLocation PrevPointOfInstantiation,
9326 bool &HasNoEffect) {
9327 HasNoEffect = false;
9328
9329 switch (NewTSK) {
9330 case TSK_Undeclared:
9331 case TSK_ImplicitInstantiation:
9332 assert(
9333 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9334 "previous declaration must be implicit!");
9335 return false;
9336
9337 case TSK_ExplicitSpecialization:
9338 switch (PrevTSK) {
9339 case TSK_Undeclared:
9340 case TSK_ExplicitSpecialization:
9341 // Okay, we're just specializing something that is either already
9342 // explicitly specialized or has merely been mentioned without any
9343 // instantiation.
9344 return false;
9345
9346 case TSK_ImplicitInstantiation:
9347 if (PrevPointOfInstantiation.isInvalid()) {
9348 // The declaration itself has not actually been instantiated, so it is
9349 // still okay to specialize it.
9350 StripImplicitInstantiation(
9351 D: PrevDecl, MinGW: Context.getTargetInfo().getTriple().isOSCygMing());
9352 return false;
9353 }
9354 // Fall through
9355 [[fallthrough]];
9356
9357 case TSK_ExplicitInstantiationDeclaration:
9358 case TSK_ExplicitInstantiationDefinition:
9359 assert((PrevTSK == TSK_ImplicitInstantiation ||
9360 PrevPointOfInstantiation.isValid()) &&
9361 "Explicit instantiation without point of instantiation?");
9362
9363 // C++ [temp.expl.spec]p6:
9364 // If a template, a member template or the member of a class template
9365 // is explicitly specialized then that specialization shall be declared
9366 // before the first use of that specialization that would cause an
9367 // implicit instantiation to take place, in every translation unit in
9368 // which such a use occurs; no diagnostic is required.
9369 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9370 // Is there any previous explicit specialization declaration?
9371 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization)
9372 return false;
9373 }
9374
9375 Diag(Loc: NewLoc, DiagID: diag::err_specialization_after_instantiation)
9376 << PrevDecl;
9377 Diag(Loc: PrevPointOfInstantiation, DiagID: diag::note_instantiation_required_here)
9378 << (PrevTSK != TSK_ImplicitInstantiation);
9379
9380 return true;
9381 }
9382 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9383
9384 case TSK_ExplicitInstantiationDeclaration:
9385 switch (PrevTSK) {
9386 case TSK_ExplicitInstantiationDeclaration:
9387 // This explicit instantiation declaration is redundant (that's okay).
9388 HasNoEffect = true;
9389 return false;
9390
9391 case TSK_Undeclared:
9392 case TSK_ImplicitInstantiation:
9393 // We're explicitly instantiating something that may have already been
9394 // implicitly instantiated; that's fine.
9395 return false;
9396
9397 case TSK_ExplicitSpecialization:
9398 // C++0x [temp.explicit]p4:
9399 // For a given set of template parameters, if an explicit instantiation
9400 // of a template appears after a declaration of an explicit
9401 // specialization for that template, the explicit instantiation has no
9402 // effect.
9403 HasNoEffect = true;
9404 return false;
9405
9406 case TSK_ExplicitInstantiationDefinition:
9407 // C++0x [temp.explicit]p10:
9408 // If an entity is the subject of both an explicit instantiation
9409 // declaration and an explicit instantiation definition in the same
9410 // translation unit, the definition shall follow the declaration.
9411 Diag(Loc: NewLoc,
9412 DiagID: diag::err_explicit_instantiation_declaration_after_definition);
9413
9414 // Explicit instantiations following a specialization have no effect and
9415 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9416 // until a valid name loc is found.
9417 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9418 DiagID: diag::note_explicit_instantiation_definition_here);
9419 HasNoEffect = true;
9420 return false;
9421 }
9422 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9423
9424 case TSK_ExplicitInstantiationDefinition:
9425 switch (PrevTSK) {
9426 case TSK_Undeclared:
9427 case TSK_ImplicitInstantiation:
9428 // We're explicitly instantiating something that may have already been
9429 // implicitly instantiated; that's fine.
9430 return false;
9431
9432 case TSK_ExplicitSpecialization:
9433 // C++ DR 259, C++0x [temp.explicit]p4:
9434 // For a given set of template parameters, if an explicit
9435 // instantiation of a template appears after a declaration of
9436 // an explicit specialization for that template, the explicit
9437 // instantiation has no effect.
9438 Diag(Loc: NewLoc, DiagID: diag::warn_explicit_instantiation_after_specialization)
9439 << PrevDecl;
9440 Diag(Loc: PrevDecl->getLocation(),
9441 DiagID: diag::note_previous_template_specialization);
9442 HasNoEffect = true;
9443 return false;
9444
9445 case TSK_ExplicitInstantiationDeclaration:
9446 // We're explicitly instantiating a definition for something for which we
9447 // were previously asked to suppress instantiations. That's fine.
9448
9449 // C++0x [temp.explicit]p4:
9450 // For a given set of template parameters, if an explicit instantiation
9451 // of a template appears after a declaration of an explicit
9452 // specialization for that template, the explicit instantiation has no
9453 // effect.
9454 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9455 // Is there any previous explicit specialization declaration?
9456 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9457 HasNoEffect = true;
9458 break;
9459 }
9460 }
9461
9462 return false;
9463
9464 case TSK_ExplicitInstantiationDefinition:
9465 // C++0x [temp.spec]p5:
9466 // For a given template and a given set of template-arguments,
9467 // - an explicit instantiation definition shall appear at most once
9468 // in a program,
9469
9470 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9471 Diag(Loc: NewLoc, DiagID: (getLangOpts().MSVCCompat)
9472 ? diag::ext_explicit_instantiation_duplicate
9473 : diag::err_explicit_instantiation_duplicate)
9474 << PrevDecl;
9475 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9476 DiagID: diag::note_previous_explicit_instantiation);
9477 HasNoEffect = true;
9478 return false;
9479 }
9480 }
9481
9482 llvm_unreachable("Missing specialization/instantiation case?");
9483}
9484
9485bool Sema::CheckDependentFunctionTemplateSpecialization(
9486 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9487 LookupResult &Previous) {
9488 // Remove anything from Previous that isn't a function template in
9489 // the correct context.
9490 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9491 LookupResult::Filter F = Previous.makeFilter();
9492 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9493 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9494 while (F.hasNext()) {
9495 NamedDecl *D = F.next()->getUnderlyingDecl();
9496 if (!isa<FunctionTemplateDecl>(Val: D)) {
9497 F.erase();
9498 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAFunctionTemplate, y&: D));
9499 continue;
9500 }
9501
9502 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9503 NS: D->getDeclContext()->getRedeclContext())) {
9504 F.erase();
9505 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAMemberOfEnclosing, y&: D));
9506 continue;
9507 }
9508 }
9509 F.done();
9510
9511 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9512 if (Previous.empty()) {
9513 Diag(Loc: FD->getLocation(), DiagID: diag::err_dependent_function_template_spec_no_match)
9514 << IsFriend;
9515 for (auto &P : DiscardedCandidates)
9516 Diag(Loc: P.second->getLocation(),
9517 DiagID: diag::note_dependent_function_template_spec_discard_reason)
9518 << P.first << IsFriend;
9519 return true;
9520 }
9521
9522 FD->setDependentTemplateSpecialization(Context, Templates: Previous.asUnresolvedSet(),
9523 TemplateArgs: ExplicitTemplateArgs);
9524 return false;
9525}
9526
9527bool Sema::CheckFunctionTemplateSpecialization(
9528 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9529 LookupResult &Previous, bool QualifiedFriend) {
9530 // The set of function template specializations that could match this
9531 // explicit function template specialization.
9532 UnresolvedSet<8> Candidates;
9533 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9534 /*ForTakingAddress=*/false);
9535
9536 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9537 ConvertedTemplateArgs;
9538
9539 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9540 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9541 I != E; ++I) {
9542 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9543 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Ovl)) {
9544 // Only consider templates found within the same semantic lookup scope as
9545 // FD.
9546 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9547 NS: Ovl->getDeclContext()->getRedeclContext()))
9548 continue;
9549
9550 QualType FT = FD->getType();
9551 // C++11 [dcl.constexpr]p8:
9552 // A constexpr specifier for a non-static member function that is not
9553 // a constructor declares that member function to be const.
9554 //
9555 // When matching a constexpr member function template specialization
9556 // against the primary template, we don't yet know whether the
9557 // specialization has an implicit 'const' (because we don't know whether
9558 // it will be a static member function until we know which template it
9559 // specializes). This rule was removed in C++14.
9560 if (auto *NewMD = dyn_cast<CXXMethodDecl>(Val: FD);
9561 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9562 !isa<CXXConstructorDecl, CXXDestructorDecl>(Val: NewMD)) {
9563 auto *OldMD = dyn_cast<CXXMethodDecl>(Val: FunTmpl->getTemplatedDecl());
9564 if (OldMD && OldMD->isConst()) {
9565 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9566 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9567 EPI.TypeQuals.addConst();
9568 FT = Context.getFunctionType(ResultTy: FPT->getReturnType(),
9569 Args: FPT->getParamTypes(), EPI);
9570 }
9571 }
9572
9573 TemplateArgumentListInfo Args;
9574 if (ExplicitTemplateArgs)
9575 Args = *ExplicitTemplateArgs;
9576
9577 // C++ [temp.expl.spec]p11:
9578 // A trailing template-argument can be left unspecified in the
9579 // template-id naming an explicit function template specialization
9580 // provided it can be deduced from the function argument type.
9581 // Perform template argument deduction to determine whether we may be
9582 // specializing this template.
9583 // FIXME: It is somewhat wasteful to build
9584 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9585 FunctionDecl *Specialization = nullptr;
9586 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9587 FunctionTemplate: cast<FunctionTemplateDecl>(Val: FunTmpl->getFirstDecl()),
9588 ExplicitTemplateArgs: ExplicitTemplateArgs ? &Args : nullptr, ArgFunctionType: FT, Specialization, Info);
9589 TDK != TemplateDeductionResult::Success) {
9590 // Template argument deduction failed; record why it failed, so
9591 // that we can provide nifty diagnostics.
9592 FailedCandidates.addCandidate().set(
9593 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9594 Info: MakeDeductionFailureInfo(Context, TDK, Info));
9595 (void)TDK;
9596 continue;
9597 }
9598
9599 // Target attributes are part of the cuda function signature, so
9600 // the deduced template's cuda target must match that of the
9601 // specialization. Given that C++ template deduction does not
9602 // take target attributes into account, we reject candidates
9603 // here that have a different target.
9604 if (LangOpts.CUDA &&
9605 CUDA().IdentifyTarget(D: Specialization,
9606 /* IgnoreImplicitHDAttr = */ true) !=
9607 CUDA().IdentifyTarget(D: FD, /* IgnoreImplicitHDAttr = */ true)) {
9608 FailedCandidates.addCandidate().set(
9609 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9610 Info: MakeDeductionFailureInfo(
9611 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
9612 continue;
9613 }
9614
9615 // Record this candidate.
9616 if (ExplicitTemplateArgs)
9617 ConvertedTemplateArgs[Specialization] = std::move(Args);
9618 Candidates.addDecl(D: Specialization, AS: I.getAccess());
9619 }
9620 }
9621
9622 // For a qualified friend declaration (with no explicit marker to indicate
9623 // that a template specialization was intended), note all (template and
9624 // non-template) candidates.
9625 if (QualifiedFriend && Candidates.empty()) {
9626 Diag(Loc: FD->getLocation(), DiagID: diag::err_qualified_friend_no_match)
9627 << FD->getDeclName() << FDLookupContext;
9628 // FIXME: We should form a single candidate list and diagnose all
9629 // candidates at once, to get proper sorting and limiting.
9630 for (auto *OldND : Previous) {
9631 if (auto *OldFD = dyn_cast<FunctionDecl>(Val: OldND->getUnderlyingDecl()))
9632 NoteOverloadCandidate(Found: OldND, Fn: OldFD, RewriteKind: CRK_None, DestType: FD->getType(), TakingAddress: false);
9633 }
9634 FailedCandidates.NoteCandidates(S&: *this, Loc: FD->getLocation());
9635 return true;
9636 }
9637
9638 // Find the most specialized function template.
9639 UnresolvedSetIterator Result = getMostSpecialized(
9640 SBegin: Candidates.begin(), SEnd: Candidates.end(), FailedCandidates, Loc: FD->getLocation(),
9641 NoneDiag: PDiag(DiagID: diag::err_function_template_spec_no_match) << FD->getDeclName(),
9642 AmbigDiag: PDiag(DiagID: diag::err_function_template_spec_ambiguous)
9643 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9644 CandidateDiag: PDiag(DiagID: diag::note_function_template_spec_matched));
9645
9646 if (Result == Candidates.end())
9647 return true;
9648
9649 // Ignore access information; it doesn't figure into redeclaration checking.
9650 FunctionDecl *Specialization = cast<FunctionDecl>(Val: *Result);
9651
9652 if (const auto *PT = Specialization->getPrimaryTemplate();
9653 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9654 auto Message = DSA->getMessage();
9655 Diag(Loc: FD->getLocation(), DiagID: diag::warn_invalid_specialization)
9656 << PT << !Message.empty() << Message;
9657 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
9658 }
9659
9660 // C++23 [except.spec]p13:
9661 // An exception specification is considered to be needed when:
9662 // - [...]
9663 // - the exception specification is compared to that of another declaration
9664 // (e.g., an explicit specialization or an overriding virtual function);
9665 // - [...]
9666 //
9667 // The exception specification of a defaulted function is evaluated as
9668 // described above only when needed; similarly, the noexcept-specifier of a
9669 // specialization of a function template or member function of a class
9670 // template is instantiated only when needed.
9671 //
9672 // The standard doesn't specify what the "comparison with another declaration"
9673 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9674 // not state which properties of an explicit specialization must match the
9675 // primary template.
9676 //
9677 // We assume that an explicit specialization must correspond with (per
9678 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9679 // the declaration produced by substitution into the function template.
9680 //
9681 // Since the determination whether two function declarations correspond does
9682 // not consider exception specification, we only need to instantiate it once
9683 // we determine the primary template when comparing types per
9684 // [basic.link]p11.1.
9685 auto *SpecializationFPT =
9686 Specialization->getType()->castAs<FunctionProtoType>();
9687 // If the function has a dependent exception specification, resolve it after
9688 // we have selected the primary template so we can check whether it matches.
9689 if (getLangOpts().CPlusPlus17 &&
9690 isUnresolvedExceptionSpec(ESpecType: SpecializationFPT->getExceptionSpecType()) &&
9691 !ResolveExceptionSpec(Loc: FD->getLocation(), FPT: SpecializationFPT))
9692 return true;
9693
9694 FunctionTemplateSpecializationInfo *SpecInfo
9695 = Specialization->getTemplateSpecializationInfo();
9696 assert(SpecInfo && "Function template specialization info missing?");
9697
9698 // Note: do not overwrite location info if previous template
9699 // specialization kind was explicit.
9700 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9701 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9702 Specialization->setLocation(FD->getLocation());
9703 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9704 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9705 // function can differ from the template declaration with respect to
9706 // the constexpr specifier.
9707 // FIXME: We need an update record for this AST mutation.
9708 // FIXME: What if there are multiple such prior declarations (for instance,
9709 // from different modules)?
9710 Specialization->setConstexprKind(FD->getConstexprKind());
9711 }
9712
9713 // FIXME: Check if the prior specialization has a point of instantiation.
9714 // If so, we have run afoul of .
9715
9716 // If this is a friend declaration, then we're not really declaring
9717 // an explicit specialization.
9718 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9719
9720 // Check the scope of this explicit specialization.
9721 if (!isFriend &&
9722 CheckTemplateSpecializationScope(S&: *this,
9723 Specialized: Specialization->getPrimaryTemplate(),
9724 PrevDecl: Specialization, Loc: FD->getLocation(),
9725 IsPartialSpecialization: false))
9726 return true;
9727
9728 // C++ [temp.expl.spec]p6:
9729 // If a template, a member template or the member of a class template is
9730 // explicitly specialized then that specialization shall be declared
9731 // before the first use of that specialization that would cause an implicit
9732 // instantiation to take place, in every translation unit in which such a
9733 // use occurs; no diagnostic is required.
9734 bool HasNoEffect = false;
9735 if (!isFriend &&
9736 CheckSpecializationInstantiationRedecl(NewLoc: FD->getLocation(),
9737 NewTSK: TSK_ExplicitSpecialization,
9738 PrevDecl: Specialization,
9739 PrevTSK: SpecInfo->getTemplateSpecializationKind(),
9740 PrevPointOfInstantiation: SpecInfo->getPointOfInstantiation(),
9741 HasNoEffect))
9742 return true;
9743
9744 // Mark the prior declaration as an explicit specialization, so that later
9745 // clients know that this is an explicit specialization.
9746 // A dependent friend specialization which has a definition should be treated
9747 // as explicit specialization, despite being invalid.
9748 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9749 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9750 // Since explicit specializations do not inherit '=delete' from their
9751 // primary function template - check if the 'specialization' that was
9752 // implicitly generated (during template argument deduction for partial
9753 // ordering) from the most specialized of all the function templates that
9754 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9755 // first check that it was implicitly generated during template argument
9756 // deduction by making sure it wasn't referenced, and then reset the deleted
9757 // flag to not-deleted, so that we can inherit that information from 'FD'.
9758 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9759 !Specialization->getCanonicalDecl()->isReferenced()) {
9760 // FIXME: This assert will not hold in the presence of modules.
9761 assert(
9762 Specialization->getCanonicalDecl() == Specialization &&
9763 "This must be the only existing declaration of this specialization");
9764 // FIXME: We need an update record for this AST mutation.
9765 Specialization->setDeletedAsWritten(D: false);
9766 }
9767 // FIXME: We need an update record for this AST mutation.
9768 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9769 MarkUnusedFileScopedDecl(D: Specialization);
9770 }
9771
9772 // Turn the given function declaration into a function template
9773 // specialization, with the template arguments from the previous
9774 // specialization.
9775 // Take copies of (semantic and syntactic) template argument lists.
9776 TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
9777 Context, Args: Specialization->getTemplateSpecializationArgs()->asArray());
9778 FD->setFunctionTemplateSpecialization(
9779 Template: Specialization->getPrimaryTemplate(), TemplateArgs: TemplArgs, /*InsertPos=*/nullptr,
9780 TSK: SpecInfo->getTemplateSpecializationKind(),
9781 TemplateArgsAsWritten: ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9782
9783 // A function template specialization inherits the target attributes
9784 // of its template. (We require the attributes explicitly in the
9785 // code to match, but a template may have implicit attributes by
9786 // virtue e.g. of being constexpr, and it passes these implicit
9787 // attributes on to its specializations.)
9788 if (LangOpts.CUDA)
9789 CUDA().inheritTargetAttrs(FD, TD: *Specialization->getPrimaryTemplate());
9790
9791 // The "previous declaration" for this function template specialization is
9792 // the prior function template specialization.
9793 Previous.clear();
9794 Previous.addDecl(D: Specialization);
9795 return false;
9796}
9797
9798bool
9799Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9800 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9801 "Only for non-template members");
9802
9803 // Try to find the member we are instantiating.
9804 NamedDecl *FoundInstantiation = nullptr;
9805 NamedDecl *Instantiation = nullptr;
9806 NamedDecl *InstantiatedFrom = nullptr;
9807 MemberSpecializationInfo *MSInfo = nullptr;
9808
9809 if (Previous.empty()) {
9810 // Nowhere to look anyway.
9811 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Member)) {
9812 UnresolvedSet<8> Candidates;
9813 for (NamedDecl *Candidate : Previous) {
9814 auto *Method = dyn_cast<CXXMethodDecl>(Val: Candidate->getUnderlyingDecl());
9815 // Ignore any candidates that aren't member functions.
9816 if (!Method)
9817 continue;
9818
9819 QualType Adjusted = Function->getType();
9820 if (!hasExplicitCallingConv(T: Adjusted))
9821 Adjusted = adjustCCAndNoReturn(ArgFunctionType: Adjusted, FunctionType: Method->getType());
9822 // Ignore any candidates with the wrong type.
9823 // This doesn't handle deduced return types, but both function
9824 // declarations should be undeduced at this point.
9825 // FIXME: The exception specification should probably be ignored when
9826 // comparing the types.
9827 if (!Context.hasSameType(T1: Adjusted, T2: Method->getType()))
9828 continue;
9829
9830 // Ignore any candidates with unsatisfied constraints.
9831 if (ConstraintSatisfaction Satisfaction;
9832 Method->getTrailingRequiresClause() &&
9833 (CheckFunctionConstraints(FD: Method, Satisfaction,
9834 /*UsageLoc=*/Member->getLocation(),
9835 /*ForOverloadResolution=*/true) ||
9836 !Satisfaction.IsSatisfied))
9837 continue;
9838
9839 Candidates.addDecl(D: Candidate);
9840 }
9841
9842 // If we have no viable candidates left after filtering, we are done.
9843 if (Candidates.empty())
9844 return false;
9845
9846 // Find the function that is more constrained than every other function it
9847 // has been compared to.
9848 UnresolvedSetIterator Best = Candidates.begin();
9849 CXXMethodDecl *BestMethod = nullptr;
9850 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9851 I != E; ++I) {
9852 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9853 if (I == Best ||
9854 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) == Method) {
9855 Best = I;
9856 BestMethod = Method;
9857 }
9858 }
9859
9860 FoundInstantiation = *Best;
9861 Instantiation = BestMethod;
9862 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9863 MSInfo = BestMethod->getMemberSpecializationInfo();
9864
9865 // Make sure the best candidate is more constrained than all of the others.
9866 bool Ambiguous = false;
9867 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9868 I != E; ++I) {
9869 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9870 if (I != Best &&
9871 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) != BestMethod) {
9872 Ambiguous = true;
9873 break;
9874 }
9875 }
9876
9877 if (Ambiguous) {
9878 Diag(Loc: Member->getLocation(), DiagID: diag::err_function_member_spec_ambiguous)
9879 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9880 for (NamedDecl *Candidate : Candidates) {
9881 Candidate = Candidate->getUnderlyingDecl();
9882 Diag(Loc: Candidate->getLocation(), DiagID: diag::note_function_member_spec_matched)
9883 << Candidate;
9884 }
9885 return true;
9886 }
9887 } else if (isa<VarDecl>(Val: Member)) {
9888 VarDecl *PrevVar;
9889 if (Previous.isSingleResult() &&
9890 (PrevVar = dyn_cast<VarDecl>(Val: Previous.getFoundDecl())))
9891 if (PrevVar->isStaticDataMember()) {
9892 FoundInstantiation = Previous.getRepresentativeDecl();
9893 Instantiation = PrevVar;
9894 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9895 MSInfo = PrevVar->getMemberSpecializationInfo();
9896 }
9897 } else if (isa<RecordDecl>(Val: Member)) {
9898 CXXRecordDecl *PrevRecord;
9899 if (Previous.isSingleResult() &&
9900 (PrevRecord = dyn_cast<CXXRecordDecl>(Val: Previous.getFoundDecl()))) {
9901 FoundInstantiation = Previous.getRepresentativeDecl();
9902 Instantiation = PrevRecord;
9903 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9904 MSInfo = PrevRecord->getMemberSpecializationInfo();
9905 }
9906 } else if (isa<EnumDecl>(Val: Member)) {
9907 EnumDecl *PrevEnum;
9908 if (Previous.isSingleResult() &&
9909 (PrevEnum = dyn_cast<EnumDecl>(Val: Previous.getFoundDecl()))) {
9910 FoundInstantiation = Previous.getRepresentativeDecl();
9911 Instantiation = PrevEnum;
9912 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9913 MSInfo = PrevEnum->getMemberSpecializationInfo();
9914 }
9915 }
9916
9917 if (!Instantiation) {
9918 // There is no previous declaration that matches. Since member
9919 // specializations are always out-of-line, the caller will complain about
9920 // this mismatch later.
9921 return false;
9922 }
9923
9924 // A member specialization in a friend declaration isn't really declaring
9925 // an explicit specialization, just identifying a specific (possibly implicit)
9926 // specialization. Don't change the template specialization kind.
9927 //
9928 // FIXME: Is this really valid? Other compilers reject.
9929 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9930 // Preserve instantiation information.
9931 if (InstantiatedFrom && isa<CXXMethodDecl>(Val: Member)) {
9932 cast<CXXMethodDecl>(Val: Member)->setInstantiationOfMemberFunction(
9933 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom),
9934 TSK: cast<CXXMethodDecl>(Val: Instantiation)->getTemplateSpecializationKind());
9935 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Val: Member)) {
9936 cast<CXXRecordDecl>(Val: Member)->setInstantiationOfMemberClass(
9937 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom),
9938 TSK: cast<CXXRecordDecl>(Val: Instantiation)->getTemplateSpecializationKind());
9939 }
9940
9941 Previous.clear();
9942 Previous.addDecl(D: FoundInstantiation);
9943 return false;
9944 }
9945
9946 // Make sure that this is a specialization of a member.
9947 if (!InstantiatedFrom) {
9948 Diag(Loc: Member->getLocation(), DiagID: diag::err_spec_member_not_instantiated)
9949 << Member;
9950 Diag(Loc: Instantiation->getLocation(), DiagID: diag::note_specialized_decl);
9951 return true;
9952 }
9953
9954 // C++ [temp.expl.spec]p6:
9955 // If a template, a member template or the member of a class template is
9956 // explicitly specialized then that specialization shall be declared
9957 // before the first use of that specialization that would cause an implicit
9958 // instantiation to take place, in every translation unit in which such a
9959 // use occurs; no diagnostic is required.
9960 assert(MSInfo && "Member specialization info missing?");
9961
9962 bool HasNoEffect = false;
9963 if (CheckSpecializationInstantiationRedecl(NewLoc: Member->getLocation(),
9964 NewTSK: TSK_ExplicitSpecialization,
9965 PrevDecl: Instantiation,
9966 PrevTSK: MSInfo->getTemplateSpecializationKind(),
9967 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
9968 HasNoEffect))
9969 return true;
9970
9971 // Check the scope of this explicit specialization.
9972 if (CheckTemplateSpecializationScope(S&: *this,
9973 Specialized: InstantiatedFrom,
9974 PrevDecl: Instantiation, Loc: Member->getLocation(),
9975 IsPartialSpecialization: false))
9976 return true;
9977
9978 // Note that this member specialization is an "instantiation of" the
9979 // corresponding member of the original template.
9980 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Val: Member)) {
9981 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Val: Instantiation);
9982 if (InstantiationFunction->getTemplateSpecializationKind() ==
9983 TSK_ImplicitInstantiation) {
9984 // Explicit specializations of member functions of class templates do not
9985 // inherit '=delete' from the member function they are specializing.
9986 if (InstantiationFunction->isDeleted()) {
9987 // FIXME: This assert will not hold in the presence of modules.
9988 assert(InstantiationFunction->getCanonicalDecl() ==
9989 InstantiationFunction);
9990 // FIXME: We need an update record for this AST mutation.
9991 InstantiationFunction->setDeletedAsWritten(D: false);
9992 }
9993 }
9994
9995 MemberFunction->setInstantiationOfMemberFunction(
9996 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
9997 } else if (auto *MemberVar = dyn_cast<VarDecl>(Val: Member)) {
9998 MemberVar->setInstantiationOfStaticDataMember(
9999 VD: cast<VarDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10000 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
10001 MemberClass->setInstantiationOfMemberClass(
10002 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10003 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Val: Member)) {
10004 MemberEnum->setInstantiationOfMemberEnum(
10005 ED: cast<EnumDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10006 } else {
10007 llvm_unreachable("unknown member specialization kind");
10008 }
10009
10010 // Save the caller the trouble of having to figure out which declaration
10011 // this specialization matches.
10012 Previous.clear();
10013 Previous.addDecl(D: FoundInstantiation);
10014 return false;
10015}
10016
10017/// Complete the explicit specialization of a member of a class template by
10018/// updating the instantiated member to be marked as an explicit specialization.
10019///
10020/// \param OrigD The member declaration instantiated from the template.
10021/// \param Loc The location of the explicit specialization of the member.
10022template<typename DeclT>
10023static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10024 SourceLocation Loc) {
10025 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10026 return;
10027
10028 // FIXME: Inform AST mutation listeners of this AST mutation.
10029 // FIXME: If there are multiple in-class declarations of the member (from
10030 // multiple modules, or a declaration and later definition of a member type),
10031 // should we update all of them?
10032 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10033 OrigD->setLocation(Loc);
10034}
10035
10036void Sema::CompleteMemberSpecialization(NamedDecl *Member,
10037 LookupResult &Previous) {
10038 NamedDecl *Instantiation = cast<NamedDecl>(Val: Member->getCanonicalDecl());
10039 if (Instantiation == Member)
10040 return;
10041
10042 if (auto *Function = dyn_cast<CXXMethodDecl>(Val: Instantiation))
10043 completeMemberSpecializationImpl(S&: *this, OrigD: Function, Loc: Member->getLocation());
10044 else if (auto *Var = dyn_cast<VarDecl>(Val: Instantiation))
10045 completeMemberSpecializationImpl(S&: *this, OrigD: Var, Loc: Member->getLocation());
10046 else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: Instantiation))
10047 completeMemberSpecializationImpl(S&: *this, OrigD: Record, Loc: Member->getLocation());
10048 else if (auto *Enum = dyn_cast<EnumDecl>(Val: Instantiation))
10049 completeMemberSpecializationImpl(S&: *this, OrigD: Enum, Loc: Member->getLocation());
10050 else
10051 llvm_unreachable("unknown member specialization kind");
10052}
10053
10054/// Check the scope of an explicit instantiation.
10055///
10056/// \returns true if a serious error occurs, false otherwise.
10057static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
10058 SourceLocation InstLoc,
10059 bool WasQualifiedName) {
10060 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
10061 DeclContext *CurContext = S.CurContext->getRedeclContext();
10062
10063 if (CurContext->isRecord()) {
10064 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_in_class)
10065 << D;
10066 return true;
10067 }
10068
10069 // C++11 [temp.explicit]p3:
10070 // An explicit instantiation shall appear in an enclosing namespace of its
10071 // template. If the name declared in the explicit instantiation is an
10072 // unqualified name, the explicit instantiation shall appear in the
10073 // namespace where its template is declared or, if that namespace is inline
10074 // (7.3.1), any namespace from its enclosing namespace set.
10075 //
10076 // This is DR275, which we do not retroactively apply to C++98/03.
10077 if (WasQualifiedName) {
10078 if (CurContext->Encloses(DC: OrigContext))
10079 return false;
10080 } else {
10081 if (CurContext->InEnclosingNamespaceSetOf(NS: OrigContext))
10082 return false;
10083 }
10084
10085 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: OrigContext)) {
10086 if (WasQualifiedName)
10087 S.Diag(Loc: InstLoc,
10088 DiagID: S.getLangOpts().CPlusPlus11?
10089 diag::err_explicit_instantiation_out_of_scope :
10090 diag::warn_explicit_instantiation_out_of_scope_0x)
10091 << D << NS;
10092 else
10093 S.Diag(Loc: InstLoc,
10094 DiagID: S.getLangOpts().CPlusPlus11?
10095 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10096 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10097 << D << NS;
10098 } else
10099 S.Diag(Loc: InstLoc,
10100 DiagID: S.getLangOpts().CPlusPlus11?
10101 diag::err_explicit_instantiation_must_be_global :
10102 diag::warn_explicit_instantiation_must_be_global_0x)
10103 << D;
10104 S.Diag(Loc: D->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10105 return false;
10106}
10107
10108/// Common checks for whether an explicit instantiation of \p D is valid.
10109static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
10110 SourceLocation InstLoc,
10111 bool WasQualifiedName,
10112 TemplateSpecializationKind TSK) {
10113 // C++ [temp.explicit]p13:
10114 // An explicit instantiation declaration shall not name a specialization of
10115 // a template with internal linkage.
10116 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10117 D->getFormalLinkage() == Linkage::Internal) {
10118 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_internal_linkage) << D;
10119 return true;
10120 }
10121
10122 // C++11 [temp.explicit]p3: [DR 275]
10123 // An explicit instantiation shall appear in an enclosing namespace of its
10124 // template.
10125 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10126 return true;
10127
10128 return false;
10129}
10130
10131/// Determine whether the given scope specifier has a template-id in it.
10132static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
10133 // C++11 [temp.explicit]p3:
10134 // If the explicit instantiation is for a member function, a member class
10135 // or a static data member of a class template specialization, the name of
10136 // the class template specialization in the qualified-id for the member
10137 // name shall be a simple-template-id.
10138 //
10139 // C++98 has the same restriction, just worded differently.
10140 for (NestedNameSpecifier NNS = SS.getScopeRep();
10141 NNS.getKind() == NestedNameSpecifier::Kind::Type;
10142 /**/) {
10143 const Type *T = NNS.getAsType();
10144 if (isa<TemplateSpecializationType>(Val: T))
10145 return true;
10146 NNS = T->getPrefix();
10147 }
10148 return false;
10149}
10150
10151/// Make a dllexport or dllimport attr on a class template specialization take
10152/// effect.
10153static void dllExportImportClassTemplateSpecialization(
10154 Sema &S, ClassTemplateSpecializationDecl *Def) {
10155 auto *A = cast_or_null<InheritableAttr>(Val: getDLLAttr(D: Def));
10156 assert(A && "dllExportImportClassTemplateSpecialization called "
10157 "on Def without dllexport or dllimport");
10158
10159 // We reject explicit instantiations in class scope, so there should
10160 // never be any delayed exported classes to worry about.
10161 assert(S.DelayedDllExportClasses.empty() &&
10162 "delayed exports present at explicit instantiation");
10163 S.checkClassLevelDLLAttribute(Class: Def);
10164
10165 // Propagate attribute to base class templates.
10166 for (auto &B : Def->bases()) {
10167 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10168 Val: B.getType()->getAsCXXRecordDecl()))
10169 S.propagateDLLAttrToBaseClassTemplate(Class: Def, ClassAttr: A, BaseTemplateSpec: BT, BaseLoc: B.getBeginLoc());
10170 }
10171
10172 S.referenceDLLExportedClassMethods();
10173}
10174
10175DeclResult Sema::ActOnExplicitInstantiation(
10176 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10177 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10178 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10179 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10180 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10181 // Find the class template we're specializing
10182 TemplateName Name = TemplateD.get();
10183 TemplateDecl *TD = Name.getAsTemplateDecl();
10184 // Check that the specialization uses the same tag kind as the
10185 // original template.
10186 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10187 assert(Kind != TagTypeKind::Enum &&
10188 "Invalid enum tag in class template explicit instantiation!");
10189
10190 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: TD);
10191
10192 if (!ClassTemplate) {
10193 NonTagKind NTK = getNonTagTypeDeclKind(D: TD, TTK: Kind);
10194 Diag(Loc: TemplateNameLoc, DiagID: diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10195 Diag(Loc: TD->getLocation(), DiagID: diag::note_previous_use);
10196 return true;
10197 }
10198
10199 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(),
10200 NewTag: Kind, /*isDefinition*/false, NewTagLoc: KWLoc,
10201 Name: ClassTemplate->getIdentifier())) {
10202 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
10203 << ClassTemplate
10204 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
10205 Code: ClassTemplate->getTemplatedDecl()->getKindName());
10206 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
10207 DiagID: diag::note_previous_use);
10208 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10209 }
10210
10211 // C++0x [temp.explicit]p2:
10212 // There are two forms of explicit instantiation: an explicit instantiation
10213 // definition and an explicit instantiation declaration. An explicit
10214 // instantiation declaration begins with the extern keyword. [...]
10215 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10216 ? TSK_ExplicitInstantiationDefinition
10217 : TSK_ExplicitInstantiationDeclaration;
10218
10219 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10220 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10221 // Check for dllexport class template instantiation declarations,
10222 // except for MinGW mode.
10223 for (const ParsedAttr &AL : Attr) {
10224 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10225 Diag(Loc: ExternLoc,
10226 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10227 Diag(Loc: AL.getLoc(), DiagID: diag::note_attribute);
10228 break;
10229 }
10230 }
10231
10232 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10233 Diag(Loc: ExternLoc,
10234 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10235 Diag(Loc: A->getLocation(), DiagID: diag::note_attribute);
10236 }
10237 }
10238
10239 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10240 // instantiation declarations for most purposes.
10241 bool DLLImportExplicitInstantiationDef = false;
10242 if (TSK == TSK_ExplicitInstantiationDefinition &&
10243 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10244 // Check for dllimport class template instantiation definitions.
10245 bool DLLImport =
10246 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10247 for (const ParsedAttr &AL : Attr) {
10248 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10249 DLLImport = true;
10250 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10251 // dllexport trumps dllimport here.
10252 DLLImport = false;
10253 break;
10254 }
10255 }
10256 if (DLLImport) {
10257 TSK = TSK_ExplicitInstantiationDeclaration;
10258 DLLImportExplicitInstantiationDef = true;
10259 }
10260 }
10261
10262 // Translate the parser's template argument list in our AST format.
10263 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10264 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10265
10266 // Check that the template argument list is well-formed for this
10267 // template.
10268 CheckTemplateArgumentInfo CTAI;
10269 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
10270 /*DefaultArgs=*/{}, PartialTemplateArgs: false, CTAI,
10271 /*UpdateArgsWithConversions=*/true,
10272 /*ConstraintsNotSatisfied=*/nullptr))
10273 return true;
10274
10275 // Find the class template specialization declaration that
10276 // corresponds to these arguments.
10277 void *InsertPos = nullptr;
10278 ClassTemplateSpecializationDecl *PrevDecl =
10279 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
10280
10281 TemplateSpecializationKind PrevDecl_TSK
10282 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10283
10284 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10285 Context.getTargetInfo().getTriple().isOSCygMing()) {
10286 // Check for dllexport class template instantiation definitions in MinGW
10287 // mode, if a previous declaration of the instantiation was seen.
10288 for (const ParsedAttr &AL : Attr) {
10289 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10290 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10291 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attr_dllexport_explicit_inst_def);
10292 } else {
10293 Diag(Loc: AL.getLoc(),
10294 DiagID: diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10295 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_prev_decl_missing_dllexport);
10296 }
10297 break;
10298 }
10299 }
10300 }
10301
10302 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10303 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10304 llvm::none_of(Range: Attr, P: [](const ParsedAttr &AL) {
10305 return AL.getKind() == ParsedAttr::AT_DLLExport;
10306 })) {
10307 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10308 Diag(Loc: TemplateLoc, DiagID: diag::warn_dllexport_on_decl_ignored);
10309 Diag(Loc: DEA->getLoc(), DiagID: diag::note_dllexport_on_decl);
10310 }
10311 }
10312
10313 if (CheckExplicitInstantiation(S&: *this, D: ClassTemplate, InstLoc: TemplateNameLoc,
10314 WasQualifiedName: SS.isSet(), TSK))
10315 return true;
10316
10317 ClassTemplateSpecializationDecl *Specialization = nullptr;
10318
10319 bool HasNoEffect = false;
10320 if (PrevDecl) {
10321 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateNameLoc, NewTSK: TSK,
10322 PrevDecl, PrevTSK: PrevDecl_TSK,
10323 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
10324 HasNoEffect))
10325 return PrevDecl;
10326
10327 // Even though HasNoEffect == true means that this explicit instantiation
10328 // has no effect on semantics, we go on to put its syntax in the AST.
10329
10330 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10331 PrevDecl_TSK == TSK_Undeclared) {
10332 // Since the only prior class template specialization with these
10333 // arguments was referenced but not declared, reuse that
10334 // declaration node as our own, updating the source location
10335 // for the template name to reflect our new declaration.
10336 // (Other source locations will be updated later.)
10337 Specialization = PrevDecl;
10338 Specialization->setLocation(TemplateNameLoc);
10339 PrevDecl = nullptr;
10340 }
10341
10342 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10343 DLLImportExplicitInstantiationDef) {
10344 // The new specialization might add a dllimport attribute.
10345 HasNoEffect = false;
10346 }
10347 }
10348
10349 if (!Specialization) {
10350 // Create a new class template specialization declaration node for
10351 // this explicit specialization.
10352 Specialization = ClassTemplateSpecializationDecl::Create(
10353 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
10354 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
10355 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
10356
10357 // A MSInheritanceAttr attached to the previous declaration must be
10358 // propagated to the new node prior to instantiation.
10359 if (PrevDecl) {
10360 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10361 auto *Clone = A->clone(C&: getASTContext());
10362 Clone->setInherited(true);
10363 Specialization->addAttr(A: Clone);
10364 Consumer.AssignInheritanceModel(RD: Specialization);
10365 }
10366 }
10367
10368 if (!HasNoEffect && !PrevDecl) {
10369 // Insert the new specialization.
10370 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
10371 }
10372 }
10373
10374 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10375
10376 // Set source locations for keywords.
10377 Specialization->setExternKeywordLoc(ExternLoc);
10378 Specialization->setTemplateKeywordLoc(TemplateLoc);
10379 Specialization->setBraceRange(SourceRange());
10380
10381 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10382 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
10383 ProcessAPINotes(D: Specialization);
10384
10385 // Add the explicit instantiation into its lexical context. However,
10386 // since explicit instantiations are never found by name lookup, we
10387 // just put it into the declaration context directly.
10388 Specialization->setLexicalDeclContext(CurContext);
10389 CurContext->addDecl(D: Specialization);
10390
10391 // Syntax is now OK, so return if it has no other effect on semantics.
10392 if (HasNoEffect) {
10393 // Set the template specialization kind.
10394 Specialization->setTemplateSpecializationKind(TSK);
10395 return Specialization;
10396 }
10397
10398 // C++ [temp.explicit]p3:
10399 // A definition of a class template or class member template
10400 // shall be in scope at the point of the explicit instantiation of
10401 // the class template or class member template.
10402 //
10403 // This check comes when we actually try to perform the
10404 // instantiation.
10405 ClassTemplateSpecializationDecl *Def
10406 = cast_or_null<ClassTemplateSpecializationDecl>(
10407 Val: Specialization->getDefinition());
10408 if (!Def)
10409 InstantiateClassTemplateSpecialization(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Specialization, TSK,
10410 /*Complain=*/true,
10411 PrimaryStrictPackMatch: CTAI.StrictPackMatch);
10412 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10413 MarkVTableUsed(Loc: TemplateNameLoc, Class: Specialization, DefinitionRequired: true);
10414 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10415 }
10416
10417 // Instantiate the members of this class template specialization.
10418 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10419 Val: Specialization->getDefinition());
10420 if (Def) {
10421 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10422 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10423 // TSK_ExplicitInstantiationDefinition
10424 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10425 (TSK == TSK_ExplicitInstantiationDefinition ||
10426 DLLImportExplicitInstantiationDef)) {
10427 // FIXME: Need to notify the ASTMutationListener that we did this.
10428 Def->setTemplateSpecializationKind(TSK);
10429
10430 if (!getDLLAttr(D: Def) && getDLLAttr(D: Specialization) &&
10431 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10432 // An explicit instantiation definition can add a dll attribute to a
10433 // template with a previous instantiation declaration. MinGW doesn't
10434 // allow this.
10435 auto *A = cast<InheritableAttr>(
10436 Val: getDLLAttr(D: Specialization)->clone(C&: getASTContext()));
10437 A->setInherited(true);
10438 Def->addAttr(A);
10439 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10440 }
10441 }
10442
10443 // Fix a TSK_ImplicitInstantiation followed by a
10444 // TSK_ExplicitInstantiationDefinition
10445 bool NewlyDLLExported =
10446 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10447 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10448 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10449 // An explicit instantiation definition can add a dll attribute to a
10450 // template with a previous implicit instantiation. MinGW doesn't allow
10451 // this. We limit clang to only adding dllexport, to avoid potentially
10452 // strange codegen behavior. For example, if we extend this conditional
10453 // to dllimport, and we have a source file calling a method on an
10454 // implicitly instantiated template class instance and then declaring a
10455 // dllimport explicit instantiation definition for the same template
10456 // class, the codegen for the method call will not respect the dllimport,
10457 // while it will with cl. The Def will already have the DLL attribute,
10458 // since the Def and Specialization will be the same in the case of
10459 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10460 // attribute to the Specialization; we just need to make it take effect.
10461 assert(Def == Specialization &&
10462 "Def and Specialization should match for implicit instantiation");
10463 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10464 }
10465
10466 // In MinGW mode, export the template instantiation if the declaration
10467 // was marked dllexport.
10468 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10469 Context.getTargetInfo().getTriple().isOSCygMing() &&
10470 PrevDecl->hasAttr<DLLExportAttr>()) {
10471 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10472 }
10473
10474 // Set the template specialization kind. Make sure it is set before
10475 // instantiating the members which will trigger ASTConsumer callbacks.
10476 Specialization->setTemplateSpecializationKind(TSK);
10477 InstantiateClassTemplateSpecializationMembers(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Def, TSK);
10478 } else {
10479
10480 // Set the template specialization kind.
10481 Specialization->setTemplateSpecializationKind(TSK);
10482 }
10483
10484 return Specialization;
10485}
10486
10487DeclResult
10488Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10489 SourceLocation TemplateLoc, unsigned TagSpec,
10490 SourceLocation KWLoc, CXXScopeSpec &SS,
10491 IdentifierInfo *Name, SourceLocation NameLoc,
10492 const ParsedAttributesView &Attr) {
10493
10494 bool Owned = false;
10495 bool IsDependent = false;
10496 Decl *TagD =
10497 ActOnTag(S, TagSpec, TUK: TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10498 Attr, AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10499 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent, ScopedEnumKWLoc: SourceLocation(),
10500 ScopedEnumUsesClassTag: false, UnderlyingType: TypeResult(), /*IsTypeSpecifier*/ false,
10501 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10502 .get();
10503 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10504
10505 if (!TagD)
10506 return true;
10507
10508 TagDecl *Tag = cast<TagDecl>(Val: TagD);
10509 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10510
10511 if (Tag->isInvalidDecl())
10512 return true;
10513
10514 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: Tag);
10515 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10516 if (!Pattern) {
10517 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_nontemplate_type)
10518 << Context.getCanonicalTagType(TD: Record);
10519 Diag(Loc: Record->getLocation(), DiagID: diag::note_nontemplate_decl_here);
10520 return true;
10521 }
10522
10523 // C++0x [temp.explicit]p2:
10524 // If the explicit instantiation is for a class or member class, the
10525 // elaborated-type-specifier in the declaration shall include a
10526 // simple-template-id.
10527 //
10528 // C++98 has the same restriction, just worded differently.
10529 if (!ScopeSpecifierHasTemplateId(SS))
10530 Diag(Loc: TemplateLoc, DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10531 << Record << SS.getRange();
10532
10533 // C++0x [temp.explicit]p2:
10534 // There are two forms of explicit instantiation: an explicit instantiation
10535 // definition and an explicit instantiation declaration. An explicit
10536 // instantiation declaration begins with the extern keyword. [...]
10537 TemplateSpecializationKind TSK
10538 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10539 : TSK_ExplicitInstantiationDeclaration;
10540
10541 CheckExplicitInstantiation(S&: *this, D: Record, InstLoc: NameLoc, WasQualifiedName: true, TSK);
10542
10543 // Verify that it is okay to explicitly instantiate here.
10544 CXXRecordDecl *PrevDecl
10545 = cast_or_null<CXXRecordDecl>(Val: Record->getPreviousDecl());
10546 if (!PrevDecl && Record->getDefinition())
10547 PrevDecl = Record;
10548 if (PrevDecl) {
10549 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10550 bool HasNoEffect = false;
10551 assert(MSInfo && "No member specialization information?");
10552 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateLoc, NewTSK: TSK,
10553 PrevDecl,
10554 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10555 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10556 HasNoEffect))
10557 return true;
10558 if (HasNoEffect)
10559 return TagD;
10560 }
10561
10562 CXXRecordDecl *RecordDef
10563 = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10564 if (!RecordDef) {
10565 // C++ [temp.explicit]p3:
10566 // A definition of a member class of a class template shall be in scope
10567 // at the point of an explicit instantiation of the member class.
10568 CXXRecordDecl *Def
10569 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
10570 if (!Def) {
10571 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_undefined_member)
10572 << 0 << Record->getDeclName() << Record->getDeclContext();
10573 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_forward_declaration)
10574 << Pattern;
10575 return true;
10576 } else {
10577 if (InstantiateClass(PointOfInstantiation: NameLoc, Instantiation: Record, Pattern: Def,
10578 TemplateArgs: getTemplateInstantiationArgs(D: Record),
10579 TSK))
10580 return true;
10581
10582 RecordDef = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10583 if (!RecordDef)
10584 return true;
10585 }
10586 }
10587
10588 // Instantiate all of the members of the class.
10589 InstantiateClassMembers(PointOfInstantiation: NameLoc, Instantiation: RecordDef,
10590 TemplateArgs: getTemplateInstantiationArgs(D: Record), TSK);
10591
10592 if (TSK == TSK_ExplicitInstantiationDefinition)
10593 MarkVTableUsed(Loc: NameLoc, Class: RecordDef, DefinitionRequired: true);
10594
10595 // FIXME: We don't have any representation for explicit instantiations of
10596 // member classes. Such a representation is not needed for compilation, but it
10597 // should be available for clients that want to see all of the declarations in
10598 // the source code.
10599 return TagD;
10600}
10601
10602DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10603 SourceLocation ExternLoc,
10604 SourceLocation TemplateLoc,
10605 Declarator &D) {
10606 // Explicit instantiations always require a name.
10607 // TODO: check if/when DNInfo should replace Name.
10608 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10609 DeclarationName Name = NameInfo.getName();
10610 if (!Name) {
10611 if (!D.isInvalidType())
10612 Diag(Loc: D.getDeclSpec().getBeginLoc(),
10613 DiagID: diag::err_explicit_instantiation_requires_name)
10614 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10615
10616 return true;
10617 }
10618
10619 // Get the innermost enclosing declaration scope.
10620 S = S->getDeclParent();
10621
10622 // Determine the type of the declaration.
10623 TypeSourceInfo *T = GetTypeForDeclarator(D);
10624 QualType R = T->getType();
10625 if (R.isNull())
10626 return true;
10627
10628 // C++ [dcl.stc]p1:
10629 // A storage-class-specifier shall not be specified in [...] an explicit
10630 // instantiation (14.7.2) directive.
10631 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10632 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_of_typedef)
10633 << Name;
10634 return true;
10635 } else if (D.getDeclSpec().getStorageClassSpec()
10636 != DeclSpec::SCS_unspecified) {
10637 // Complain about then remove the storage class specifier.
10638 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_storage_class)
10639 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10640
10641 D.getMutableDeclSpec().ClearStorageClassSpecs();
10642 }
10643
10644 // C++0x [temp.explicit]p1:
10645 // [...] An explicit instantiation of a function template shall not use the
10646 // inline or constexpr specifiers.
10647 // Presumably, this also applies to member functions of class templates as
10648 // well.
10649 if (D.getDeclSpec().isInlineSpecified())
10650 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10651 DiagID: getLangOpts().CPlusPlus11 ?
10652 diag::err_explicit_instantiation_inline :
10653 diag::warn_explicit_instantiation_inline_0x)
10654 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10655 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10656 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10657 // not already specified.
10658 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10659 DiagID: diag::err_explicit_instantiation_constexpr);
10660
10661 // A deduction guide is not on the list of entities that can be explicitly
10662 // instantiated.
10663 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10664 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
10665 << /*explicit instantiation*/ 0;
10666 return true;
10667 }
10668
10669 // C++0x [temp.explicit]p2:
10670 // There are two forms of explicit instantiation: an explicit instantiation
10671 // definition and an explicit instantiation declaration. An explicit
10672 // instantiation declaration begins with the extern keyword. [...]
10673 TemplateSpecializationKind TSK
10674 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10675 : TSK_ExplicitInstantiationDeclaration;
10676
10677 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10678 LookupParsedName(R&: Previous, S, SS: &D.getCXXScopeSpec(),
10679 /*ObjectType=*/QualType());
10680
10681 if (!R->isFunctionType()) {
10682 // C++ [temp.explicit]p1:
10683 // A [...] static data member of a class template can be explicitly
10684 // instantiated from the member definition associated with its class
10685 // template.
10686 // C++1y [temp.explicit]p1:
10687 // A [...] variable [...] template specialization can be explicitly
10688 // instantiated from its template.
10689 if (Previous.isAmbiguous())
10690 return true;
10691
10692 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10693 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10694
10695 if (!PrevTemplate) {
10696 if (!Prev || !Prev->isStaticDataMember()) {
10697 // We expect to see a static data member here.
10698 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_not_known)
10699 << Name;
10700 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10701 P != PEnd; ++P)
10702 Diag(Loc: (*P)->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10703 return true;
10704 }
10705
10706 if (!Prev->getInstantiatedFromStaticDataMember()) {
10707 // FIXME: Check for explicit specialization?
10708 Diag(Loc: D.getIdentifierLoc(),
10709 DiagID: diag::err_explicit_instantiation_data_member_not_instantiated)
10710 << Prev;
10711 Diag(Loc: Prev->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10712 // FIXME: Can we provide a note showing where this was declared?
10713 return true;
10714 }
10715 } else {
10716 // Explicitly instantiate a variable template.
10717
10718 // C++1y [dcl.spec.auto]p6:
10719 // ... A program that uses auto or decltype(auto) in a context not
10720 // explicitly allowed in this section is ill-formed.
10721 //
10722 // This includes auto-typed variable template instantiations.
10723 if (R->isUndeducedType()) {
10724 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10725 DiagID: diag::err_auto_not_allowed_var_inst);
10726 return true;
10727 }
10728
10729 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10730 // C++1y [temp.explicit]p3:
10731 // If the explicit instantiation is for a variable, the unqualified-id
10732 // in the declaration shall be a template-id.
10733 Diag(Loc: D.getIdentifierLoc(),
10734 DiagID: diag::err_explicit_instantiation_without_template_id)
10735 << PrevTemplate;
10736 Diag(Loc: PrevTemplate->getLocation(),
10737 DiagID: diag::note_explicit_instantiation_here);
10738 return true;
10739 }
10740
10741 // Translate the parser's template argument list into our AST format.
10742 TemplateArgumentListInfo TemplateArgs =
10743 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10744
10745 DeclResult Res =
10746 CheckVarTemplateId(Template: PrevTemplate, TemplateLoc, TemplateNameLoc: D.getIdentifierLoc(),
10747 TemplateArgs, /*SetWrittenArgs=*/true);
10748 if (Res.isInvalid())
10749 return true;
10750
10751 if (!Res.isUsable()) {
10752 // We somehow specified dependent template arguments in an explicit
10753 // instantiation. This should probably only happen during error
10754 // recovery.
10755 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_dependent);
10756 return true;
10757 }
10758
10759 // Ignore access control bits, we don't need them for redeclaration
10760 // checking.
10761 Prev = cast<VarDecl>(Val: Res.get());
10762 }
10763
10764 // C++0x [temp.explicit]p2:
10765 // If the explicit instantiation is for a member function, a member class
10766 // or a static data member of a class template specialization, the name of
10767 // the class template specialization in the qualified-id for the member
10768 // name shall be a simple-template-id.
10769 //
10770 // C++98 has the same restriction, just worded differently.
10771 //
10772 // This does not apply to variable template specializations, where the
10773 // template-id is in the unqualified-id instead.
10774 if (!ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()) && !PrevTemplate)
10775 Diag(Loc: D.getIdentifierLoc(),
10776 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10777 << Prev << D.getCXXScopeSpec().getRange();
10778
10779 CheckExplicitInstantiation(S&: *this, D: Prev, InstLoc: D.getIdentifierLoc(), WasQualifiedName: true, TSK);
10780
10781 // Verify that it is okay to explicitly instantiate here.
10782 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10783 SourceLocation POI = Prev->getPointOfInstantiation();
10784 bool HasNoEffect = false;
10785 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK, PrevDecl: Prev,
10786 PrevTSK, PrevPointOfInstantiation: POI, HasNoEffect))
10787 return true;
10788
10789 if (!HasNoEffect) {
10790 // Instantiate static data member or variable template.
10791 Prev->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
10792 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: Prev)) {
10793 VTSD->setExternKeywordLoc(ExternLoc);
10794 VTSD->setTemplateKeywordLoc(TemplateLoc);
10795 }
10796
10797 // Merge attributes.
10798 ProcessDeclAttributeList(S, D: Prev, AttrList: D.getDeclSpec().getAttributes());
10799 if (PrevTemplate)
10800 ProcessAPINotes(D: Prev);
10801
10802 if (TSK == TSK_ExplicitInstantiationDefinition)
10803 InstantiateVariableDefinition(PointOfInstantiation: D.getIdentifierLoc(), Var: Prev);
10804 }
10805
10806 // Check the new variable specialization against the parsed input.
10807 if (PrevTemplate && !Context.hasSameType(T1: Prev->getType(), T2: R)) {
10808 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10809 DiagID: diag::err_invalid_var_template_spec_type)
10810 << 0 << PrevTemplate << R << Prev->getType();
10811 Diag(Loc: PrevTemplate->getLocation(), DiagID: diag::note_template_declared_here)
10812 << 2 << PrevTemplate->getDeclName();
10813 return true;
10814 }
10815
10816 // FIXME: Create an ExplicitInstantiation node?
10817 return (Decl*) nullptr;
10818 }
10819
10820 // If the declarator is a template-id, translate the parser's template
10821 // argument list into our AST format.
10822 bool HasExplicitTemplateArgs = false;
10823 TemplateArgumentListInfo TemplateArgs;
10824 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10825 TemplateArgs = makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10826 HasExplicitTemplateArgs = true;
10827 }
10828
10829 // C++ [temp.explicit]p1:
10830 // A [...] function [...] can be explicitly instantiated from its template.
10831 // A member function [...] of a class template can be explicitly
10832 // instantiated from the member definition associated with its class
10833 // template.
10834 UnresolvedSet<8> TemplateMatches;
10835 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10836 OverloadCandidateSet::CSK_Normal);
10837 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10838 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10839 P != PEnd; ++P) {
10840 NamedDecl *Prev = *P;
10841 if (!HasExplicitTemplateArgs) {
10842 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Prev)) {
10843 QualType Adjusted = adjustCCAndNoReturn(ArgFunctionType: R, FunctionType: Method->getType(),
10844 /*AdjustExceptionSpec*/true);
10845 if (Context.hasSameUnqualifiedType(T1: Method->getType(), T2: Adjusted)) {
10846 if (Method->getPrimaryTemplate()) {
10847 TemplateMatches.addDecl(D: Method, AS: P.getAccess());
10848 } else {
10849 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10850 C.FoundDecl = P.getPair();
10851 C.Function = Method;
10852 C.Viable = true;
10853 ConstraintSatisfaction S;
10854 if (Method->getTrailingRequiresClause() &&
10855 (CheckFunctionConstraints(FD: Method, Satisfaction&: S, UsageLoc: D.getIdentifierLoc(),
10856 /*ForOverloadResolution=*/true) ||
10857 !S.IsSatisfied)) {
10858 C.Viable = false;
10859 C.FailureKind = ovl_fail_constraints_not_satisfied;
10860 }
10861 }
10862 }
10863 }
10864 }
10865
10866 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Prev);
10867 if (!FunTmpl)
10868 continue;
10869
10870 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10871 FunctionDecl *Specialization = nullptr;
10872 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
10873 FunctionTemplate: FunTmpl, ExplicitTemplateArgs: (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), ArgFunctionType: R,
10874 Specialization, Info);
10875 TDK != TemplateDeductionResult::Success) {
10876 // Keep track of almost-matches.
10877 FailedTemplateCandidates.addCandidate().set(
10878 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
10879 Info: MakeDeductionFailureInfo(Context, TDK, Info));
10880 (void)TDK;
10881 continue;
10882 }
10883
10884 // Target attributes are part of the cuda function signature, so
10885 // the cuda target of the instantiated function must match that of its
10886 // template. Given that C++ template deduction does not take
10887 // target attributes into account, we reject candidates here that
10888 // have a different target.
10889 if (LangOpts.CUDA &&
10890 CUDA().IdentifyTarget(D: Specialization,
10891 /* IgnoreImplicitHDAttr = */ true) !=
10892 CUDA().IdentifyTarget(Attrs: D.getDeclSpec().getAttributes())) {
10893 FailedTemplateCandidates.addCandidate().set(
10894 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
10895 Info: MakeDeductionFailureInfo(
10896 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
10897 continue;
10898 }
10899
10900 TemplateMatches.addDecl(D: Specialization, AS: P.getAccess());
10901 }
10902
10903 FunctionDecl *Specialization = nullptr;
10904 if (!NonTemplateMatches.empty()) {
10905 unsigned Msg = 0;
10906 OverloadCandidateDisplayKind DisplayKind;
10907 OverloadCandidateSet::iterator Best;
10908 switch (NonTemplateMatches.BestViableFunction(S&: *this, Loc: D.getIdentifierLoc(),
10909 Best)) {
10910 case OR_Success:
10911 case OR_Deleted:
10912 Specialization = cast<FunctionDecl>(Val: Best->Function);
10913 break;
10914 case OR_Ambiguous:
10915 Msg = diag::err_explicit_instantiation_ambiguous;
10916 DisplayKind = OCD_AmbiguousCandidates;
10917 break;
10918 case OR_No_Viable_Function:
10919 Msg = diag::err_explicit_instantiation_no_candidate;
10920 DisplayKind = OCD_AllCandidates;
10921 break;
10922 }
10923 if (Msg) {
10924 PartialDiagnostic Diag = PDiag(DiagID: Msg) << Name;
10925 NonTemplateMatches.NoteCandidates(
10926 PA: PartialDiagnosticAt(D.getIdentifierLoc(), Diag), S&: *this, OCD: DisplayKind,
10927 Args: {});
10928 return true;
10929 }
10930 }
10931
10932 if (!Specialization) {
10933 // Find the most specialized function template specialization.
10934 UnresolvedSetIterator Result = getMostSpecialized(
10935 SBegin: TemplateMatches.begin(), SEnd: TemplateMatches.end(),
10936 FailedCandidates&: FailedTemplateCandidates, Loc: D.getIdentifierLoc(),
10937 NoneDiag: PDiag(DiagID: diag::err_explicit_instantiation_not_known) << Name,
10938 AmbigDiag: PDiag(DiagID: diag::err_explicit_instantiation_ambiguous) << Name,
10939 CandidateDiag: PDiag(DiagID: diag::note_explicit_instantiation_candidate));
10940
10941 if (Result == TemplateMatches.end())
10942 return true;
10943
10944 // Ignore access control bits, we don't need them for redeclaration checking.
10945 Specialization = cast<FunctionDecl>(Val: *Result);
10946 }
10947
10948 // C++11 [except.spec]p4
10949 // In an explicit instantiation an exception-specification may be specified,
10950 // but is not required.
10951 // If an exception-specification is specified in an explicit instantiation
10952 // directive, it shall be compatible with the exception-specifications of
10953 // other declarations of that function.
10954 if (auto *FPT = R->getAs<FunctionProtoType>())
10955 if (FPT->hasExceptionSpec()) {
10956 unsigned DiagID =
10957 diag::err_mismatched_exception_spec_explicit_instantiation;
10958 if (getLangOpts().MicrosoftExt)
10959 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10960 bool Result = CheckEquivalentExceptionSpec(
10961 DiagID: PDiag(DiagID) << Specialization->getType(),
10962 NoteID: PDiag(DiagID: diag::note_explicit_instantiation_here),
10963 Old: Specialization->getType()->getAs<FunctionProtoType>(),
10964 OldLoc: Specialization->getLocation(), New: FPT, NewLoc: D.getBeginLoc());
10965 // In Microsoft mode, mismatching exception specifications just cause a
10966 // warning.
10967 if (!getLangOpts().MicrosoftExt && Result)
10968 return true;
10969 }
10970
10971 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10972 Diag(Loc: D.getIdentifierLoc(),
10973 DiagID: diag::err_explicit_instantiation_member_function_not_instantiated)
10974 << Specialization
10975 << (Specialization->getTemplateSpecializationKind() ==
10976 TSK_ExplicitSpecialization);
10977 Diag(Loc: Specialization->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10978 return true;
10979 }
10980
10981 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10982 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10983 PrevDecl = Specialization;
10984
10985 if (PrevDecl) {
10986 bool HasNoEffect = false;
10987 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK,
10988 PrevDecl,
10989 PrevTSK: PrevDecl->getTemplateSpecializationKind(),
10990 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
10991 HasNoEffect))
10992 return true;
10993
10994 // FIXME: We may still want to build some representation of this
10995 // explicit specialization.
10996 if (HasNoEffect)
10997 return (Decl*) nullptr;
10998 }
10999
11000 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11001 // functions
11002 // valarray<size_t>::valarray(size_t) and
11003 // valarray<size_t>::~valarray()
11004 // that it declared to have internal linkage with the internal_linkage
11005 // attribute. Ignore the explicit instantiation declaration in this case.
11006 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11007 TSK == TSK_ExplicitInstantiationDeclaration) {
11008 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getDeclContext()))
11009 if (RD->getIdentifier() && RD->getIdentifier()->isStr(Str: "valarray") &&
11010 RD->isInStdNamespace())
11011 return (Decl*) nullptr;
11012 }
11013
11014 ProcessDeclAttributeList(S, D: Specialization, AttrList: D.getDeclSpec().getAttributes());
11015 ProcessAPINotes(D: Specialization);
11016
11017 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11018 // instantiation declarations.
11019 if (TSK == TSK_ExplicitInstantiationDefinition &&
11020 Specialization->hasAttr<DLLImportAttr>() &&
11021 Context.getTargetInfo().getCXXABI().isMicrosoft())
11022 TSK = TSK_ExplicitInstantiationDeclaration;
11023
11024 Specialization->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
11025
11026 if (Specialization->isDefined()) {
11027 // Let the ASTConsumer know that this function has been explicitly
11028 // instantiated now, and its linkage might have changed.
11029 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Specialization));
11030 } else if (TSK == TSK_ExplicitInstantiationDefinition)
11031 InstantiateFunctionDefinition(PointOfInstantiation: D.getIdentifierLoc(), Function: Specialization);
11032
11033 // C++0x [temp.explicit]p2:
11034 // If the explicit instantiation is for a member function, a member class
11035 // or a static data member of a class template specialization, the name of
11036 // the class template specialization in the qualified-id for the member
11037 // name shall be a simple-template-id.
11038 //
11039 // C++98 has the same restriction, just worded differently.
11040 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11041 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11042 D.getCXXScopeSpec().isSet() &&
11043 !ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()))
11044 Diag(Loc: D.getIdentifierLoc(),
11045 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
11046 << Specialization << D.getCXXScopeSpec().getRange();
11047
11048 CheckExplicitInstantiation(
11049 S&: *this,
11050 D: FunTmpl ? (NamedDecl *)FunTmpl
11051 : Specialization->getInstantiatedFromMemberFunction(),
11052 InstLoc: D.getIdentifierLoc(), WasQualifiedName: D.getCXXScopeSpec().isSet(), TSK);
11053
11054 // FIXME: Create some kind of ExplicitInstantiationDecl here.
11055 return (Decl*) nullptr;
11056}
11057
11058TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11059 const CXXScopeSpec &SS,
11060 const IdentifierInfo *Name,
11061 SourceLocation TagLoc,
11062 SourceLocation NameLoc) {
11063 // This has to hold, because SS is expected to be defined.
11064 assert(Name && "Expected a name in a dependent tag");
11065
11066 NestedNameSpecifier NNS = SS.getScopeRep();
11067 if (!NNS)
11068 return true;
11069
11070 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
11071
11072 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11073 Diag(Loc: NameLoc, DiagID: diag::err_dependent_tag_decl)
11074 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11075 return true;
11076 }
11077
11078 // Create the resulting type.
11079 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
11080 QualType Result = Context.getDependentNameType(Keyword: Kwd, NNS, Name);
11081
11082 // Create type-source location information for this type.
11083 TypeLocBuilder TLB;
11084 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: Result);
11085 TL.setElaboratedKeywordLoc(TagLoc);
11086 TL.setQualifierLoc(SS.getWithLocInContext(Context));
11087 TL.setNameLoc(NameLoc);
11088 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
11089}
11090
11091TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11092 const CXXScopeSpec &SS,
11093 const IdentifierInfo &II,
11094 SourceLocation IdLoc,
11095 ImplicitTypenameContext IsImplicitTypename) {
11096 if (SS.isInvalid())
11097 return true;
11098
11099 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11100 DiagCompat(Loc: TypenameLoc, CompatDiagId: diag_compat::typename_outside_of_template)
11101 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11102
11103 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11104 TypeSourceInfo *TSI = nullptr;
11105 QualType T =
11106 CheckTypenameType(Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11107 : ElaboratedTypeKeyword::None,
11108 KeywordLoc: TypenameLoc, QualifierLoc, II, IILoc: IdLoc, TSI: &TSI,
11109 /*DeducedTSTContext=*/true);
11110 if (T.isNull())
11111 return true;
11112 return CreateParsedType(T, TInfo: TSI);
11113}
11114
11115TypeResult
11116Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11117 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11118 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11119 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11120 ASTTemplateArgsPtr TemplateArgsIn,
11121 SourceLocation RAngleLoc) {
11122 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11123 Diag(Loc: TypenameLoc, DiagID: getLangOpts().CPlusPlus11
11124 ? diag::compat_cxx11_typename_outside_of_template
11125 : diag::compat_pre_cxx11_typename_outside_of_template)
11126 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11127
11128 // Strangely, non-type results are not ignored by this lookup, so the
11129 // program is ill-formed if it finds an injected-class-name.
11130 if (TypenameLoc.isValid()) {
11131 auto *LookupRD =
11132 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: false));
11133 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11134 Diag(Loc: TemplateIILoc,
11135 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
11136 << TemplateII << 0 /*injected-class-name used as template name*/
11137 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11138 }
11139 }
11140
11141 // Translate the parser's template argument list in our AST format.
11142 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11143 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11144
11145 QualType T = CheckTemplateIdType(
11146 Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11147 : ElaboratedTypeKeyword::None,
11148 Name: TemplateIn.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
11149 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11150 if (T.isNull())
11151 return true;
11152
11153 // Provide source-location information for the template specialization type.
11154 TypeLocBuilder Builder;
11155 TemplateSpecializationTypeLoc SpecTL
11156 = Builder.push<TemplateSpecializationTypeLoc>(T);
11157 SpecTL.set(ElaboratedKeywordLoc: TypenameLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
11158 NameLoc: TemplateIILoc, TAL: TemplateArgs);
11159 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11160 return CreateParsedType(T, TInfo: TSI);
11161}
11162
11163/// Determine whether this failed name lookup should be treated as being
11164/// disabled by a usage of std::enable_if.
11165static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
11166 SourceRange &CondRange, Expr *&Cond) {
11167 // We must be looking for a ::type...
11168 if (!II.isStr(Str: "type"))
11169 return false;
11170
11171 // ... within an explicitly-written template specialization...
11172 if (NNS.getNestedNameSpecifier().getKind() != NestedNameSpecifier::Kind::Type)
11173 return false;
11174
11175 // FIXME: Look through sugar.
11176 auto EnableIfTSTLoc =
11177 NNS.castAsTypeLoc().getAs<TemplateSpecializationTypeLoc>();
11178 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11179 return false;
11180 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11181
11182 // ... which names a complete class template declaration...
11183 const TemplateDecl *EnableIfDecl =
11184 EnableIfTST->getTemplateName().getAsTemplateDecl();
11185 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11186 return false;
11187
11188 // ... called "enable_if".
11189 const IdentifierInfo *EnableIfII =
11190 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11191 if (!EnableIfII || !EnableIfII->isStr(Str: "enable_if"))
11192 return false;
11193
11194 // Assume the first template argument is the condition.
11195 CondRange = EnableIfTSTLoc.getArgLoc(i: 0).getSourceRange();
11196
11197 // Dig out the condition.
11198 Cond = nullptr;
11199 if (EnableIfTSTLoc.getArgLoc(i: 0).getArgument().getKind()
11200 != TemplateArgument::Expression)
11201 return true;
11202
11203 Cond = EnableIfTSTLoc.getArgLoc(i: 0).getSourceExpression();
11204
11205 // Ignore Boolean literals; they add no value.
11206 if (isa<CXXBoolLiteralExpr>(Val: Cond->IgnoreParenCasts()))
11207 Cond = nullptr;
11208
11209 return true;
11210}
11211
11212QualType
11213Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11214 SourceLocation KeywordLoc,
11215 NestedNameSpecifierLoc QualifierLoc,
11216 const IdentifierInfo &II,
11217 SourceLocation IILoc,
11218 TypeSourceInfo **TSI,
11219 bool DeducedTSTContext) {
11220 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11221 DeducedTSTContext);
11222 if (T.isNull())
11223 return QualType();
11224
11225 TypeLocBuilder TLB;
11226 if (isa<DependentNameType>(Val: T)) {
11227 auto TL = TLB.push<DependentNameTypeLoc>(T);
11228 TL.setElaboratedKeywordLoc(KeywordLoc);
11229 TL.setQualifierLoc(QualifierLoc);
11230 TL.setNameLoc(IILoc);
11231 } else if (isa<DeducedTemplateSpecializationType>(Val: T)) {
11232 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
11233 TL.setElaboratedKeywordLoc(KeywordLoc);
11234 TL.setQualifierLoc(QualifierLoc);
11235 TL.setNameLoc(IILoc);
11236 } else if (isa<TemplateTypeParmType>(Val: T)) {
11237 // FIXME: There might be a 'typename' keyword here, but we just drop it
11238 // as it can't be represented.
11239 assert(!QualifierLoc);
11240 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11241 } else if (isa<TagType>(Val: T)) {
11242 auto TL = TLB.push<TagTypeLoc>(T);
11243 TL.setElaboratedKeywordLoc(KeywordLoc);
11244 TL.setQualifierLoc(QualifierLoc);
11245 TL.setNameLoc(IILoc);
11246 } else if (isa<TypedefType>(Val: T)) {
11247 TLB.push<TypedefTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11248 } else {
11249 TLB.push<UnresolvedUsingTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11250 }
11251 *TSI = TLB.getTypeSourceInfo(Context, T);
11252 return T;
11253}
11254
11255/// Build the type that describes a C++ typename specifier,
11256/// e.g., "typename T::type".
11257QualType
11258Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11259 SourceLocation KeywordLoc,
11260 NestedNameSpecifierLoc QualifierLoc,
11261 const IdentifierInfo &II,
11262 SourceLocation IILoc, bool DeducedTSTContext) {
11263 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11264
11265 CXXScopeSpec SS;
11266 SS.Adopt(Other: QualifierLoc);
11267
11268 DeclContext *Ctx = nullptr;
11269 if (QualifierLoc) {
11270 Ctx = computeDeclContext(SS);
11271 if (!Ctx) {
11272 // If the nested-name-specifier is dependent and couldn't be
11273 // resolved to a type, build a typename type.
11274 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11275 return Context.getDependentNameType(Keyword,
11276 NNS: QualifierLoc.getNestedNameSpecifier(),
11277 Name: &II);
11278 }
11279
11280 // If the nested-name-specifier refers to the current instantiation,
11281 // the "typename" keyword itself is superfluous. In C++03, the
11282 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11283 // allows such extraneous "typename" keywords, and we retroactively
11284 // apply this DR to C++03 code with only a warning. In any case we continue.
11285
11286 if (RequireCompleteDeclContext(SS, DC: Ctx))
11287 return QualType();
11288 }
11289
11290 DeclarationName Name(&II);
11291 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11292 if (Ctx)
11293 LookupQualifiedName(R&: Result, LookupCtx: Ctx, SS);
11294 else
11295 LookupName(R&: Result, S: CurScope);
11296 unsigned DiagID = 0;
11297 Decl *Referenced = nullptr;
11298 switch (Result.getResultKind()) {
11299 case LookupResultKind::NotFound: {
11300 // If we're looking up 'type' within a template named 'enable_if', produce
11301 // a more specific diagnostic.
11302 SourceRange CondRange;
11303 Expr *Cond = nullptr;
11304 if (Ctx && isEnableIf(NNS: QualifierLoc, II, CondRange, Cond)) {
11305 // If we have a condition, narrow it down to the specific failed
11306 // condition.
11307 if (Cond) {
11308 Expr *FailedCond;
11309 std::string FailedDescription;
11310 std::tie(args&: FailedCond, args&: FailedDescription) =
11311 findFailedBooleanCondition(Cond);
11312
11313 Diag(Loc: FailedCond->getExprLoc(),
11314 DiagID: diag::err_typename_nested_not_found_requirement)
11315 << FailedDescription
11316 << FailedCond->getSourceRange();
11317 return QualType();
11318 }
11319
11320 Diag(Loc: CondRange.getBegin(),
11321 DiagID: diag::err_typename_nested_not_found_enable_if)
11322 << Ctx << CondRange;
11323 return QualType();
11324 }
11325
11326 DiagID = Ctx ? diag::err_typename_nested_not_found
11327 : diag::err_unknown_typename;
11328 break;
11329 }
11330
11331 case LookupResultKind::FoundUnresolvedValue: {
11332 // We found a using declaration that is a value. Most likely, the using
11333 // declaration itself is meant to have the 'typename' keyword.
11334 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11335 IILoc);
11336 Diag(Loc: IILoc, DiagID: diag::err_typename_refers_to_using_value_decl)
11337 << Name << Ctx << FullRange;
11338 if (UnresolvedUsingValueDecl *Using
11339 = dyn_cast<UnresolvedUsingValueDecl>(Val: Result.getRepresentativeDecl())){
11340 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11341 Diag(Loc, DiagID: diag::note_using_value_decl_missing_typename)
11342 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
11343 }
11344 }
11345 // Fall through to create a dependent typename type, from which we can
11346 // recover better.
11347 [[fallthrough]];
11348
11349 case LookupResultKind::NotFoundInCurrentInstantiation:
11350 // Okay, it's a member of an unknown instantiation.
11351 return Context.getDependentNameType(Keyword,
11352 NNS: QualifierLoc.getNestedNameSpecifier(),
11353 Name: &II);
11354
11355 case LookupResultKind::Found:
11356 // FXIME: Missing support for UsingShadowDecl on this path?
11357 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: Result.getFoundDecl())) {
11358 // C++ [class.qual]p2:
11359 // In a lookup in which function names are not ignored and the
11360 // nested-name-specifier nominates a class C, if the name specified
11361 // after the nested-name-specifier, when looked up in C, is the
11362 // injected-class-name of C [...] then the name is instead considered
11363 // to name the constructor of class C.
11364 //
11365 // Unlike in an elaborated-type-specifier, function names are not ignored
11366 // in typename-specifier lookup. However, they are ignored in all the
11367 // contexts where we form a typename type with no keyword (that is, in
11368 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11369 //
11370 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11371 // ignore functions, but that appears to be an oversight.
11372 checkTypeDeclType(LookupCtx: Ctx,
11373 DCK: Keyword == ElaboratedTypeKeyword::Typename
11374 ? DiagCtorKind::Typename
11375 : DiagCtorKind::None,
11376 TD: Type, NameLoc: IILoc);
11377 // FIXME: This appears to be the only case where a template type parameter
11378 // can have an elaborated keyword. We should preserve it somehow.
11379 if (isa<TemplateTypeParmDecl>(Val: Type)) {
11380 assert(Keyword == ElaboratedTypeKeyword::Typename);
11381 assert(!QualifierLoc);
11382 Keyword = ElaboratedTypeKeyword::None;
11383 }
11384 return Context.getTypeDeclType(
11385 Keyword, Qualifier: QualifierLoc.getNestedNameSpecifier(), Decl: Type);
11386 }
11387
11388 // C++ [dcl.type.simple]p2:
11389 // A type-specifier of the form
11390 // typename[opt] nested-name-specifier[opt] template-name
11391 // is a placeholder for a deduced class type [...].
11392 if (getLangOpts().CPlusPlus17) {
11393 if (auto *TD = getAsTypeTemplateDecl(D: Result.getFoundDecl())) {
11394 if (!DeducedTSTContext) {
11395 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11396 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11397 Diag(Loc: IILoc, DiagID: diag::err_dependent_deduced_tst)
11398 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
11399 << QualType(Qualifier.getAsType(), 0);
11400 else
11401 Diag(Loc: IILoc, DiagID: diag::err_deduced_tst)
11402 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD));
11403 NoteTemplateLocation(Decl: *TD);
11404 return QualType();
11405 }
11406 TemplateName Name = Context.getQualifiedTemplateName(
11407 Qualifier: QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11408 Template: TemplateName(TD));
11409 return Context.getDeducedTemplateSpecializationType(
11410 Keyword, Template: Name, /*DeducedType=*/QualType(), /*IsDependent=*/false);
11411 }
11412 }
11413
11414 DiagID = Ctx ? diag::err_typename_nested_not_type
11415 : diag::err_typename_not_type;
11416 Referenced = Result.getFoundDecl();
11417 break;
11418
11419 case LookupResultKind::FoundOverloaded:
11420 DiagID = Ctx ? diag::err_typename_nested_not_type
11421 : diag::err_typename_not_type;
11422 Referenced = *Result.begin();
11423 break;
11424
11425 case LookupResultKind::Ambiguous:
11426 return QualType();
11427 }
11428
11429 // If we get here, it's because name lookup did not find a
11430 // type. Emit an appropriate diagnostic and return an error.
11431 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11432 IILoc);
11433 if (Ctx)
11434 Diag(Loc: IILoc, DiagID) << FullRange << Name << Ctx;
11435 else
11436 Diag(Loc: IILoc, DiagID) << FullRange << Name;
11437 if (Referenced)
11438 Diag(Loc: Referenced->getLocation(),
11439 DiagID: Ctx ? diag::note_typename_member_refers_here
11440 : diag::note_typename_refers_here)
11441 << Name;
11442 return QualType();
11443}
11444
11445namespace {
11446 // See Sema::RebuildTypeInCurrentInstantiation
11447 class CurrentInstantiationRebuilder
11448 : public TreeTransform<CurrentInstantiationRebuilder> {
11449 SourceLocation Loc;
11450 DeclarationName Entity;
11451
11452 public:
11453 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11454
11455 CurrentInstantiationRebuilder(Sema &SemaRef,
11456 SourceLocation Loc,
11457 DeclarationName Entity)
11458 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11459 Loc(Loc), Entity(Entity) { }
11460
11461 /// Determine whether the given type \p T has already been
11462 /// transformed.
11463 ///
11464 /// For the purposes of type reconstruction, a type has already been
11465 /// transformed if it is NULL or if it is not dependent.
11466 bool AlreadyTransformed(QualType T) {
11467 return T.isNull() || !T->isInstantiationDependentType();
11468 }
11469
11470 /// Returns the location of the entity whose type is being
11471 /// rebuilt.
11472 SourceLocation getBaseLocation() { return Loc; }
11473
11474 /// Returns the name of the entity whose type is being rebuilt.
11475 DeclarationName getBaseEntity() { return Entity; }
11476
11477 /// Sets the "base" location and entity when that
11478 /// information is known based on another transformation.
11479 void setBase(SourceLocation Loc, DeclarationName Entity) {
11480 this->Loc = Loc;
11481 this->Entity = Entity;
11482 }
11483
11484 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11485 // Lambdas never need to be transformed.
11486 return E;
11487 }
11488 };
11489} // end anonymous namespace
11490
11491TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11492 SourceLocation Loc,
11493 DeclarationName Name) {
11494 if (!T || !T->getType()->isInstantiationDependentType())
11495 return T;
11496
11497 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11498 return Rebuilder.TransformType(TSI: T);
11499}
11500
11501ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11502 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11503 DeclarationName());
11504 return Rebuilder.TransformExpr(E);
11505}
11506
11507bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11508 if (SS.isInvalid())
11509 return true;
11510
11511 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11512 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11513 DeclarationName());
11514 NestedNameSpecifierLoc Rebuilt
11515 = Rebuilder.TransformNestedNameSpecifierLoc(NNS: QualifierLoc);
11516 if (!Rebuilt)
11517 return true;
11518
11519 SS.Adopt(Other: Rebuilt);
11520 return false;
11521}
11522
11523bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11524 TemplateParameterList *Params) {
11525 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11526 Decl *Param = Params->getParam(Idx: I);
11527
11528 // There is nothing to rebuild in a type parameter.
11529 if (isa<TemplateTypeParmDecl>(Val: Param))
11530 continue;
11531
11532 // Rebuild the template parameter list of a template template parameter.
11533 if (TemplateTemplateParmDecl *TTP
11534 = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) {
11535 if (RebuildTemplateParamsInCurrentInstantiation(
11536 Params: TTP->getTemplateParameters()))
11537 return true;
11538
11539 continue;
11540 }
11541
11542 // Rebuild the type of a non-type template parameter.
11543 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Val: Param);
11544 TypeSourceInfo *NewTSI
11545 = RebuildTypeInCurrentInstantiation(T: NTTP->getTypeSourceInfo(),
11546 Loc: NTTP->getLocation(),
11547 Name: NTTP->getDeclName());
11548 if (!NewTSI)
11549 return true;
11550
11551 if (NewTSI->getType()->isUndeducedType()) {
11552 // C++17 [temp.dep.expr]p3:
11553 // An id-expression is type-dependent if it contains
11554 // - an identifier associated by name lookup with a non-type
11555 // template-parameter declared with a type that contains a
11556 // placeholder type (7.1.7.4),
11557 NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: NewTSI);
11558 }
11559
11560 if (NewTSI != NTTP->getTypeSourceInfo()) {
11561 NTTP->setTypeSourceInfo(NewTSI);
11562 NTTP->setType(NewTSI->getType());
11563 }
11564 }
11565
11566 return false;
11567}
11568
11569std::string
11570Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11571 const TemplateArgumentList &Args) {
11572 return getTemplateArgumentBindingsText(Params, Args: Args.data(), NumArgs: Args.size());
11573}
11574
11575std::string
11576Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11577 const TemplateArgument *Args,
11578 unsigned NumArgs) {
11579 SmallString<128> Str;
11580 llvm::raw_svector_ostream Out(Str);
11581
11582 if (!Params || Params->size() == 0 || NumArgs == 0)
11583 return std::string();
11584
11585 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11586 if (I >= NumArgs)
11587 break;
11588
11589 if (I == 0)
11590 Out << "[with ";
11591 else
11592 Out << ", ";
11593
11594 if (const IdentifierInfo *Id = Params->getParam(Idx: I)->getIdentifier()) {
11595 Out << Id->getName();
11596 } else {
11597 Out << '$' << I;
11598 }
11599
11600 Out << " = ";
11601 Args[I].print(Policy: getPrintingPolicy(), Out,
11602 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
11603 Policy: getPrintingPolicy(), TPL: Params, Idx: I));
11604 }
11605
11606 Out << ']';
11607 return std::string(Out.str());
11608}
11609
11610void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11611 CachedTokens &Toks) {
11612 if (!FD)
11613 return;
11614
11615 auto LPT = std::make_unique<LateParsedTemplate>();
11616
11617 // Take tokens to avoid allocations
11618 LPT->Toks.swap(RHS&: Toks);
11619 LPT->D = FnD;
11620 LPT->FPO = getCurFPFeatures();
11621 LateParsedTemplateMap.insert(KV: std::make_pair(x&: FD, y: std::move(LPT)));
11622
11623 FD->setLateTemplateParsed(true);
11624}
11625
11626void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11627 if (!FD)
11628 return;
11629 FD->setLateTemplateParsed(false);
11630}
11631
11632bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11633 DeclContext *DC = CurContext;
11634
11635 while (DC) {
11636 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
11637 const FunctionDecl *FD = RD->isLocalClass();
11638 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11639 } else if (DC->isTranslationUnit() || DC->isNamespace())
11640 return false;
11641
11642 DC = DC->getParent();
11643 }
11644 return false;
11645}
11646
11647namespace {
11648/// Walk the path from which a declaration was instantiated, and check
11649/// that every explicit specialization along that path is visible. This enforces
11650/// C++ [temp.expl.spec]/6:
11651///
11652/// If a template, a member template or a member of a class template is
11653/// explicitly specialized then that specialization shall be declared before
11654/// the first use of that specialization that would cause an implicit
11655/// instantiation to take place, in every translation unit in which such a
11656/// use occurs; no diagnostic is required.
11657///
11658/// and also C++ [temp.class.spec]/1:
11659///
11660/// A partial specialization shall be declared before the first use of a
11661/// class template specialization that would make use of the partial
11662/// specialization as the result of an implicit or explicit instantiation
11663/// in every translation unit in which such a use occurs; no diagnostic is
11664/// required.
11665class ExplicitSpecializationVisibilityChecker {
11666 Sema &S;
11667 SourceLocation Loc;
11668 llvm::SmallVector<Module *, 8> Modules;
11669 Sema::AcceptableKind Kind;
11670
11671public:
11672 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11673 Sema::AcceptableKind Kind)
11674 : S(S), Loc(Loc), Kind(Kind) {}
11675
11676 void check(NamedDecl *ND) {
11677 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
11678 return checkImpl(Spec: FD);
11679 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
11680 return checkImpl(Spec: RD);
11681 if (auto *VD = dyn_cast<VarDecl>(Val: ND))
11682 return checkImpl(Spec: VD);
11683 if (auto *ED = dyn_cast<EnumDecl>(Val: ND))
11684 return checkImpl(Spec: ED);
11685 }
11686
11687private:
11688 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11689 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11690 : Sema::MissingImportKind::ExplicitSpecialization;
11691 const bool Recover = true;
11692
11693 // If we got a custom set of modules (because only a subset of the
11694 // declarations are interesting), use them, otherwise let
11695 // diagnoseMissingImport intelligently pick some.
11696 if (Modules.empty())
11697 S.diagnoseMissingImport(Loc, Decl: D, MIK: Kind, Recover);
11698 else
11699 S.diagnoseMissingImport(Loc, Decl: D, DeclLoc: D->getLocation(), Modules, MIK: Kind, Recover);
11700 }
11701
11702 bool CheckMemberSpecialization(const NamedDecl *D) {
11703 return Kind == Sema::AcceptableKind::Visible
11704 ? S.hasVisibleMemberSpecialization(D)
11705 : S.hasReachableMemberSpecialization(D);
11706 }
11707
11708 bool CheckExplicitSpecialization(const NamedDecl *D) {
11709 return Kind == Sema::AcceptableKind::Visible
11710 ? S.hasVisibleExplicitSpecialization(D)
11711 : S.hasReachableExplicitSpecialization(D);
11712 }
11713
11714 bool CheckDeclaration(const NamedDecl *D) {
11715 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11716 : S.hasReachableDeclaration(D);
11717 }
11718
11719 // Check a specific declaration. There are three problematic cases:
11720 //
11721 // 1) The declaration is an explicit specialization of a template
11722 // specialization.
11723 // 2) The declaration is an explicit specialization of a member of an
11724 // templated class.
11725 // 3) The declaration is an instantiation of a template, and that template
11726 // is an explicit specialization of a member of a templated class.
11727 //
11728 // We don't need to go any deeper than that, as the instantiation of the
11729 // surrounding class / etc is not triggered by whatever triggered this
11730 // instantiation, and thus should be checked elsewhere.
11731 template<typename SpecDecl>
11732 void checkImpl(SpecDecl *Spec) {
11733 bool IsHiddenExplicitSpecialization = false;
11734 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11735 // Some invalid friend declarations are written as specializations but are
11736 // instantiated implicitly.
11737 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11738 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11739 if (SpecKind == TSK_ExplicitSpecialization) {
11740 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11741 ? !CheckMemberSpecialization(D: Spec)
11742 : !CheckExplicitSpecialization(D: Spec);
11743 } else {
11744 checkInstantiated(Spec);
11745 }
11746
11747 if (IsHiddenExplicitSpecialization)
11748 diagnose(D: Spec->getMostRecentDecl(), IsPartialSpec: false);
11749 }
11750
11751 void checkInstantiated(FunctionDecl *FD) {
11752 if (auto *TD = FD->getPrimaryTemplate())
11753 checkTemplate(TD);
11754 }
11755
11756 void checkInstantiated(CXXRecordDecl *RD) {
11757 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD);
11758 if (!SD)
11759 return;
11760
11761 auto From = SD->getSpecializedTemplateOrPartial();
11762 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11763 checkTemplate(TD);
11764 else if (auto *TD =
11765 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11766 if (!CheckDeclaration(D: TD))
11767 diagnose(D: TD, IsPartialSpec: true);
11768 checkTemplate(TD);
11769 }
11770 }
11771
11772 void checkInstantiated(VarDecl *RD) {
11773 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(Val: RD);
11774 if (!SD)
11775 return;
11776
11777 auto From = SD->getSpecializedTemplateOrPartial();
11778 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11779 checkTemplate(TD);
11780 else if (auto *TD =
11781 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11782 if (!CheckDeclaration(D: TD))
11783 diagnose(D: TD, IsPartialSpec: true);
11784 checkTemplate(TD);
11785 }
11786 }
11787
11788 void checkInstantiated(EnumDecl *FD) {}
11789
11790 template<typename TemplDecl>
11791 void checkTemplate(TemplDecl *TD) {
11792 if (TD->isMemberSpecialization()) {
11793 if (!CheckMemberSpecialization(D: TD))
11794 diagnose(D: TD->getMostRecentDecl(), IsPartialSpec: false);
11795 }
11796 }
11797};
11798} // end anonymous namespace
11799
11800void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11801 if (!getLangOpts().Modules)
11802 return;
11803
11804 ExplicitSpecializationVisibilityChecker(*this, Loc,
11805 Sema::AcceptableKind::Visible)
11806 .check(ND: Spec);
11807}
11808
11809void Sema::checkSpecializationReachability(SourceLocation Loc,
11810 NamedDecl *Spec) {
11811 if (!getLangOpts().CPlusPlusModules)
11812 return checkSpecializationVisibility(Loc, Spec);
11813
11814 ExplicitSpecializationVisibilityChecker(*this, Loc,
11815 Sema::AcceptableKind::Reachable)
11816 .check(ND: Spec);
11817}
11818
11819SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
11820 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11821 return N->getLocation();
11822 if (const auto *FD = dyn_cast<FunctionDecl>(Val: N)) {
11823 if (!FD->isFunctionTemplateSpecialization())
11824 return FD->getLocation();
11825 } else if (!isa<ClassTemplateSpecializationDecl,
11826 VarTemplateSpecializationDecl>(Val: N)) {
11827 return N->getLocation();
11828 }
11829 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11830 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11831 continue;
11832 return CSC.PointOfInstantiation;
11833 }
11834 return N->getLocation();
11835}
11836