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 QualifiedLookupValidatorCCC FilterCCC(!SS.isEmpty());
523 FilterCCC.WantTypeSpecifiers = false;
524 FilterCCC.WantExpressionKeywords = false;
525 FilterCCC.WantRemainingKeywords = false;
526 FilterCCC.WantCXXNamedCasts = true;
527 if (TypoCorrection Corrected = CorrectTypo(
528 Typo: Found.getLookupNameInfo(), LookupKind: Found.getLookupKind(), S, SS: &SS, CCC&: FilterCCC,
529 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
530 if (auto *ND = Corrected.getFoundDecl())
531 Found.addDecl(D: ND);
532 FilterAcceptableTemplateNames(R&: Found);
533 if (Found.isAmbiguous()) {
534 Found.clear();
535 } else if (!Found.empty()) {
536 // Do not erase the typo-corrected result to avoid duplicated
537 // diagnostics.
538 AllowFunctionTemplatesInLookup = true;
539 Found.setLookupName(Corrected.getCorrection());
540 if (LookupCtx) {
541 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
542 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
543 Name.getAsString() == CorrectedStr;
544 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_template_suggest)
545 << Name << LookupCtx << DroppedSpecifier
546 << SS.getRange());
547 } else {
548 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_template_suggest) << Name);
549 }
550
551 if (Corrected.WillReplaceSpecifier()) {
552 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
553 // In order to be valid, a non-empty CXXScopeSpec needs a source
554 // range.
555 SS.MakeTrivial(Context, Qualifier: NNS,
556 R: NNS ? Found.getNameLoc() : SourceRange());
557 }
558 }
559 }
560 }
561
562 NamedDecl *ExampleLookupResult =
563 Found.empty() ? nullptr : Found.getRepresentativeDecl();
564 FilterAcceptableTemplateNames(R&: Found, AllowFunctionTemplates: AllowFunctionTemplatesInLookup);
565 if (Found.empty()) {
566 if (IsDependent) {
567 Found.setNotFoundInCurrentInstantiation();
568 return false;
569 }
570
571 // If a 'template' keyword was used, a lookup that finds only non-template
572 // names is an error.
573 if (ExampleLookupResult && RequiredTemplate) {
574 Diag(Loc: Found.getNameLoc(), DiagID: diag::err_template_kw_refers_to_non_template)
575 << Found.getLookupName() << SS.getRange()
576 << RequiredTemplate.hasTemplateKeyword()
577 << RequiredTemplate.getTemplateKeywordLoc();
578 Diag(Loc: ExampleLookupResult->getUnderlyingDecl()->getLocation(),
579 DiagID: diag::note_template_kw_refers_to_non_template)
580 << Found.getLookupName();
581 return true;
582 }
583
584 return false;
585 }
586
587 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
588 !getLangOpts().CPlusPlus11) {
589 // C++03 [basic.lookup.classref]p1:
590 // [...] If the lookup in the class of the object expression finds a
591 // template, the name is also looked up in the context of the entire
592 // postfix-expression and [...]
593 //
594 // Note: C++11 does not perform this second lookup.
595 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
596 LookupOrdinaryName);
597 FoundOuter.setTemplateNameLookup(true);
598 LookupName(R&: FoundOuter, S);
599 // FIXME: We silently accept an ambiguous lookup here, in violation of
600 // [basic.lookup]/1.
601 FilterAcceptableTemplateNames(R&: FoundOuter, /*AllowFunctionTemplates=*/false);
602
603 NamedDecl *OuterTemplate;
604 if (FoundOuter.empty()) {
605 // - if the name is not found, the name found in the class of the
606 // object expression is used, otherwise
607 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
608 !(OuterTemplate =
609 getAsTemplateNameDecl(D: FoundOuter.getFoundDecl()))) {
610 // - if the name is found in the context of the entire
611 // postfix-expression and does not name a class template, the name
612 // found in the class of the object expression is used, otherwise
613 FoundOuter.clear();
614 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
615 // - if the name found is a class template, it must refer to the same
616 // entity as the one found in the class of the object expression,
617 // otherwise the program is ill-formed.
618 if (!Found.isSingleResult() ||
619 getAsTemplateNameDecl(D: Found.getFoundDecl())->getCanonicalDecl() !=
620 OuterTemplate->getCanonicalDecl()) {
621 Diag(Loc: Found.getNameLoc(),
622 DiagID: diag::ext_nested_name_member_ref_lookup_ambiguous)
623 << Found.getLookupName()
624 << ObjectType;
625 Diag(Loc: Found.getRepresentativeDecl()->getLocation(),
626 DiagID: diag::note_ambig_member_ref_object_type)
627 << ObjectType;
628 Diag(Loc: FoundOuter.getFoundDecl()->getLocation(),
629 DiagID: diag::note_ambig_member_ref_scope);
630
631 // Recover by taking the template that we found in the object
632 // expression's type.
633 }
634 }
635 }
636
637 return false;
638}
639
640void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
641 SourceLocation Less,
642 SourceLocation Greater) {
643 if (TemplateName.isInvalid())
644 return;
645
646 DeclarationNameInfo NameInfo;
647 CXXScopeSpec SS;
648 LookupNameKind LookupKind;
649
650 DeclContext *LookupCtx = nullptr;
651 NamedDecl *Found = nullptr;
652 bool MissingTemplateKeyword = false;
653
654 // Figure out what name we looked up.
655 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: TemplateName.get())) {
656 NameInfo = DRE->getNameInfo();
657 SS.Adopt(Other: DRE->getQualifierLoc());
658 LookupKind = LookupOrdinaryName;
659 Found = DRE->getFoundDecl();
660 } else if (auto *ME = dyn_cast<MemberExpr>(Val: TemplateName.get())) {
661 NameInfo = ME->getMemberNameInfo();
662 SS.Adopt(Other: ME->getQualifierLoc());
663 LookupKind = LookupMemberName;
664 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
665 Found = ME->getMemberDecl();
666 } else if (auto *DSDRE =
667 dyn_cast<DependentScopeDeclRefExpr>(Val: TemplateName.get())) {
668 NameInfo = DSDRE->getNameInfo();
669 SS.Adopt(Other: DSDRE->getQualifierLoc());
670 MissingTemplateKeyword = true;
671 } else if (auto *DSME =
672 dyn_cast<CXXDependentScopeMemberExpr>(Val: TemplateName.get())) {
673 NameInfo = DSME->getMemberNameInfo();
674 SS.Adopt(Other: DSME->getQualifierLoc());
675 MissingTemplateKeyword = true;
676 } else {
677 llvm_unreachable("unexpected kind of potential template name");
678 }
679
680 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
681 // was missing.
682 if (MissingTemplateKeyword) {
683 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_template_kw_missing)
684 << NameInfo.getName() << SourceRange(Less, Greater);
685 return;
686 }
687
688 // Try to correct the name by looking for templates and C++ named casts.
689 struct TemplateCandidateFilter : CorrectionCandidateCallback {
690 Sema &S;
691 TemplateCandidateFilter(Sema &S) : S(S) {
692 WantTypeSpecifiers = false;
693 WantExpressionKeywords = false;
694 WantRemainingKeywords = false;
695 WantCXXNamedCasts = true;
696 };
697 bool ValidateCandidate(const TypoCorrection &Candidate) override {
698 if (auto *ND = Candidate.getCorrectionDecl())
699 return S.getAsTemplateNameDecl(D: ND);
700 return Candidate.isKeyword();
701 }
702
703 std::unique_ptr<CorrectionCandidateCallback> clone() override {
704 return std::make_unique<TemplateCandidateFilter>(args&: *this);
705 }
706 };
707
708 DeclarationName Name = NameInfo.getName();
709 TemplateCandidateFilter CCC(*this);
710 if (TypoCorrection Corrected =
711 CorrectTypo(Typo: NameInfo, LookupKind, S, SS: &SS, CCC,
712 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
713 auto *ND = Corrected.getFoundDecl();
714 if (ND)
715 ND = getAsTemplateNameDecl(D: ND);
716 if (ND || Corrected.isKeyword()) {
717 if (LookupCtx) {
718 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
719 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
720 Name.getAsString() == CorrectedStr;
721 diagnoseTypo(Correction: Corrected,
722 TypoDiag: PDiag(DiagID: diag::err_non_template_in_member_template_id_suggest)
723 << Name << LookupCtx << DroppedSpecifier
724 << SS.getRange(), ErrorRecovery: false);
725 } else {
726 diagnoseTypo(Correction: Corrected,
727 TypoDiag: PDiag(DiagID: diag::err_non_template_in_template_id_suggest)
728 << Name, ErrorRecovery: false);
729 }
730 if (Found)
731 Diag(Loc: Found->getLocation(),
732 DiagID: diag::note_non_template_in_template_id_found);
733 return;
734 }
735 }
736
737 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_non_template_in_template_id)
738 << Name << SourceRange(Less, Greater);
739 if (Found)
740 Diag(Loc: Found->getLocation(), DiagID: diag::note_non_template_in_template_id_found);
741}
742
743ExprResult
744Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
745 SourceLocation TemplateKWLoc,
746 const DeclarationNameInfo &NameInfo,
747 bool isAddressOfOperand,
748 const TemplateArgumentListInfo *TemplateArgs) {
749 if (SS.isEmpty()) {
750 // FIXME: This codepath is only used by dependent unqualified names
751 // (e.g. a dependent conversion-function-id, or operator= once we support
752 // it). It doesn't quite do the right thing, and it will silently fail if
753 // getCurrentThisType() returns null.
754 QualType ThisType = getCurrentThisType();
755 if (ThisType.isNull())
756 return ExprError();
757
758 return CXXDependentScopeMemberExpr::Create(
759 Ctx: Context, /*Base=*/nullptr, BaseType: ThisType,
760 /*IsArrow=*/!Context.getLangOpts().HLSL,
761 /*OperatorLoc=*/SourceLocation(),
762 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
763 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
764 }
765 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
766}
767
768ExprResult
769Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
770 SourceLocation TemplateKWLoc,
771 const DeclarationNameInfo &NameInfo,
772 const TemplateArgumentListInfo *TemplateArgs) {
773 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
774 if (!SS.isValid())
775 return CreateRecoveryExpr(
776 Begin: SS.getBeginLoc(),
777 End: TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), SubExprs: {});
778
779 return DependentScopeDeclRefExpr::Create(
780 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
781 TemplateArgs);
782}
783
784ExprResult
785Sema::BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
786 QualType ParamType, SourceLocation Loc,
787 TemplateArgument Arg,
788 UnsignedOrNone PackIndex, bool Final) {
789 // The template argument itself might be an expression, in which case we just
790 // return that expression. This happens when substituting into an alias
791 // template.
792 Expr *Replacement;
793 if (Arg.getKind() == TemplateArgument::Expression) {
794 Replacement = Arg.getAsExpr();
795 } else {
796 ExprResult result =
797 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
798 if (result.isInvalid())
799 return ExprError();
800 Replacement = result.get();
801 }
802 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
803 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
804 AssociatedDecl, ParamType, Index, PackIndex, Final);
805}
806
807bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
808 NamedDecl *Instantiation,
809 bool InstantiatedFromMember,
810 const NamedDecl *Pattern,
811 const NamedDecl *PatternDef,
812 TemplateSpecializationKind TSK,
813 bool Complain, bool *Unreachable) {
814 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
815 isa<VarDecl>(Instantiation));
816
817 bool IsEntityBeingDefined = false;
818 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(Val: PatternDef))
819 IsEntityBeingDefined = TD->isBeingDefined();
820
821 if (PatternDef && !IsEntityBeingDefined) {
822 NamedDecl *SuggestedDef = nullptr;
823 if (!hasReachableDefinition(D: const_cast<NamedDecl *>(PatternDef),
824 Suggested: &SuggestedDef,
825 /*OnlyNeedComplete*/ false)) {
826 if (Unreachable)
827 *Unreachable = true;
828 // If we're allowed to diagnose this and recover, do so.
829 bool Recover = Complain && !isSFINAEContext();
830 if (Complain)
831 diagnoseMissingImport(Loc: PointOfInstantiation, Decl: SuggestedDef,
832 MIK: Sema::MissingImportKind::Definition, Recover);
833 return !Recover;
834 }
835 return false;
836 }
837
838 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
839 return true;
840
841 CanQualType InstantiationTy;
842 if (TagDecl *TD = dyn_cast<TagDecl>(Val: Instantiation))
843 InstantiationTy = Context.getCanonicalTagType(TD);
844 if (PatternDef) {
845 Diag(Loc: PointOfInstantiation,
846 DiagID: diag::err_template_instantiate_within_definition)
847 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
848 << InstantiationTy;
849 // Not much point in noting the template declaration here, since
850 // we're lexically inside it.
851 Instantiation->setInvalidDecl();
852 } else if (InstantiatedFromMember) {
853 if (isa<FunctionDecl>(Val: Instantiation)) {
854 Diag(Loc: PointOfInstantiation,
855 DiagID: diag::err_explicit_instantiation_undefined_member)
856 << /*member function*/ 1 << Instantiation->getDeclName()
857 << Instantiation->getDeclContext();
858 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
859 } else {
860 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
861 Diag(Loc: PointOfInstantiation,
862 DiagID: diag::err_implicit_instantiate_member_undefined)
863 << InstantiationTy;
864 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_member_declared_at);
865 }
866 } else {
867 if (isa<FunctionDecl>(Val: Instantiation)) {
868 Diag(Loc: PointOfInstantiation,
869 DiagID: diag::err_explicit_instantiation_undefined_func_template)
870 << Pattern;
871 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
872 } else if (isa<TagDecl>(Val: Instantiation)) {
873 Diag(Loc: PointOfInstantiation, DiagID: diag::err_template_instantiate_undefined)
874 << (TSK != TSK_ImplicitInstantiation)
875 << InstantiationTy;
876 NoteTemplateLocation(Decl: *Pattern);
877 } else {
878 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
879 if (isa<VarTemplateSpecializationDecl>(Val: Instantiation)) {
880 Diag(Loc: PointOfInstantiation,
881 DiagID: diag::err_explicit_instantiation_undefined_var_template)
882 << Instantiation;
883 Instantiation->setInvalidDecl();
884 } else
885 Diag(Loc: PointOfInstantiation,
886 DiagID: diag::err_explicit_instantiation_undefined_member)
887 << /*static data member*/ 2 << Instantiation->getDeclName()
888 << Instantiation->getDeclContext();
889 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
890 }
891 }
892
893 // In general, Instantiation isn't marked invalid to get more than one
894 // error for multiple undefined instantiations. But the code that does
895 // explicit declaration -> explicit definition conversion can't handle
896 // invalid declarations, so mark as invalid in that case.
897 if (TSK == TSK_ExplicitInstantiationDeclaration)
898 Instantiation->setInvalidDecl();
899 return true;
900}
901
902void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
903 bool SupportedForCompatibility) {
904 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
905
906 // C++23 [temp.local]p6:
907 // The name of a template-parameter shall not be bound to any following.
908 // declaration whose locus is contained by the scope to which the
909 // template-parameter belongs.
910 //
911 // When MSVC compatibility is enabled, the diagnostic is always a warning
912 // by default. Otherwise, it an error unless SupportedForCompatibility is
913 // true, in which case it is a default-to-error warning.
914 unsigned DiagId =
915 getLangOpts().MSVCCompat
916 ? diag::ext_template_param_shadow
917 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
918 : diag::err_template_param_shadow);
919 const auto *ND = cast<NamedDecl>(Val: PrevDecl);
920 Diag(Loc, DiagID: DiagId) << ND->getDeclName();
921 NoteTemplateParameterLocation(Decl: *ND);
922}
923
924TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
925 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(Val: D)) {
926 D = Temp->getTemplatedDecl();
927 return Temp;
928 }
929 return nullptr;
930}
931
932ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
933 SourceLocation EllipsisLoc) const {
934 assert(Kind == Template &&
935 "Only template template arguments can be pack expansions here");
936 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
937 "Template template argument pack expansion without packs");
938 ParsedTemplateArgument Result(*this);
939 Result.EllipsisLoc = EllipsisLoc;
940 return Result;
941}
942
943static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
944 const ParsedTemplateArgument &Arg) {
945
946 switch (Arg.getKind()) {
947 case ParsedTemplateArgument::Type: {
948 TypeSourceInfo *TSI;
949 QualType T = SemaRef.GetTypeFromParser(Ty: Arg.getAsType(), TInfo: &TSI);
950 if (!TSI)
951 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc: Arg.getNameLoc());
952 return TemplateArgumentLoc(TemplateArgument(T), TSI);
953 }
954
955 case ParsedTemplateArgument::NonType: {
956 Expr *E = Arg.getAsExpr();
957 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
958 }
959
960 case ParsedTemplateArgument::Template: {
961 TemplateName Template = Arg.getAsTemplate().get();
962 TemplateArgument TArg;
963 if (Arg.getEllipsisLoc().isValid())
964 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
965 else
966 TArg = Template;
967 return TemplateArgumentLoc(
968 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
969 Arg.getScopeSpec().getWithLocInContext(Context&: SemaRef.Context),
970 Arg.getNameLoc(), Arg.getEllipsisLoc());
971 }
972 }
973
974 llvm_unreachable("Unhandled parsed template argument");
975}
976
977void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
978 TemplateArgumentListInfo &TemplateArgs) {
979 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
980 TemplateArgs.addArgument(Loc: translateTemplateArgument(SemaRef&: *this,
981 Arg: TemplateArgsIn[I]));
982}
983
984static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
985 SourceLocation Loc,
986 const IdentifierInfo *Name) {
987 NamedDecl *PrevDecl =
988 SemaRef.LookupSingleName(S, Name, Loc, NameKind: Sema::LookupOrdinaryName,
989 Redecl: RedeclarationKind::ForVisibleRedeclaration);
990 if (PrevDecl && PrevDecl->isTemplateParameter())
991 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
992}
993
994ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
995 TypeSourceInfo *TInfo;
996 QualType T = GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TInfo);
997 if (T.isNull())
998 return ParsedTemplateArgument();
999 assert(TInfo && "template argument with no location");
1000
1001 // If we might have formed a deduced template specialization type, convert
1002 // it to a template template argument.
1003 if (getLangOpts().CPlusPlus17) {
1004 TypeLoc TL = TInfo->getTypeLoc();
1005 SourceLocation EllipsisLoc;
1006 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1007 EllipsisLoc = PET.getEllipsisLoc();
1008 TL = PET.getPatternLoc();
1009 }
1010
1011 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1012 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1013 CXXScopeSpec SS;
1014 SS.Adopt(Other: DTST.getQualifierLoc());
1015 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1016 TemplateTy::make(P: Name),
1017 DTST.getTemplateNameLoc());
1018 if (EllipsisLoc.isValid())
1019 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1020 return Result;
1021 }
1022 }
1023
1024 // This is a normal type template argument. Note, if the type template
1025 // argument is an injected-class-name for a template, it has a dual nature
1026 // and can be used as either a type or a template. We handle that in
1027 // convertTypeTemplateArgumentToTemplate.
1028 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1029 ParsedType.get().getAsOpaquePtr(),
1030 TInfo->getTypeLoc().getBeginLoc());
1031}
1032
1033NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1034 SourceLocation EllipsisLoc,
1035 SourceLocation KeyLoc,
1036 IdentifierInfo *ParamName,
1037 SourceLocation ParamNameLoc,
1038 unsigned Depth, unsigned Position,
1039 SourceLocation EqualLoc,
1040 ParsedType DefaultArg,
1041 bool HasTypeConstraint) {
1042 assert(S->isTemplateParamScope() &&
1043 "Template type parameter not in template parameter scope!");
1044
1045 bool IsParameterPack = EllipsisLoc.isValid();
1046 TemplateTypeParmDecl *Param
1047 = TemplateTypeParmDecl::Create(C: Context, DC: Context.getTranslationUnitDecl(),
1048 KeyLoc, NameLoc: ParamNameLoc, D: Depth, P: Position,
1049 Id: ParamName, Typename, ParameterPack: IsParameterPack,
1050 HasTypeConstraint);
1051 Param->setAccess(AS_public);
1052
1053 if (Param->isParameterPack())
1054 if (auto *CSI = getEnclosingLambdaOrBlock())
1055 CSI->LocalPacks.push_back(Elt: Param);
1056
1057 if (ParamName) {
1058 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: ParamNameLoc, Name: ParamName);
1059
1060 // Add the template parameter into the current scope.
1061 S->AddDecl(D: Param);
1062 IdResolver.AddDecl(D: Param);
1063 }
1064
1065 // C++0x [temp.param]p9:
1066 // A default template-argument may be specified for any kind of
1067 // template-parameter that is not a template parameter pack.
1068 if (DefaultArg && IsParameterPack) {
1069 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1070 DefaultArg = nullptr;
1071 }
1072
1073 // Handle the default argument, if provided.
1074 if (DefaultArg) {
1075 TypeSourceInfo *DefaultTInfo;
1076 GetTypeFromParser(Ty: DefaultArg, TInfo: &DefaultTInfo);
1077
1078 assert(DefaultTInfo && "expected source information for type");
1079
1080 // Check for unexpanded parameter packs.
1081 if (DiagnoseUnexpandedParameterPack(Loc: ParamNameLoc, T: DefaultTInfo,
1082 UPPC: UPPC_DefaultArgument))
1083 return Param;
1084
1085 // Check the template argument itself.
1086 if (CheckTemplateArgument(Arg: DefaultTInfo)) {
1087 Param->setInvalidDecl();
1088 return Param;
1089 }
1090
1091 Param->setDefaultArgument(
1092 C: Context, DefArg: TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1093 }
1094
1095 return Param;
1096}
1097
1098/// Convert the parser's template argument list representation into our form.
1099static TemplateArgumentListInfo
1100makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1101 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1102 TemplateId.RAngleLoc);
1103 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1104 TemplateId.NumArgs);
1105 S.translateTemplateArguments(TemplateArgsIn: TemplateArgsPtr, TemplateArgs);
1106 return TemplateArgs;
1107}
1108
1109bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1110
1111 TemplateName TN = TypeConstr->Template.get();
1112 NamedDecl *CD = nullptr;
1113 bool IsTypeConcept = false;
1114 bool RequiresArguments = false;
1115 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: TN.getAsTemplateDecl())) {
1116 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1117 RequiresArguments =
1118 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1119 CD = TTP;
1120 } else {
1121 CD = TN.getAsTemplateDecl();
1122 IsTypeConcept = cast<ConceptDecl>(Val: CD)->isTypeConcept();
1123 RequiresArguments = cast<ConceptDecl>(Val: CD)
1124 ->getTemplateParameters()
1125 ->getMinRequiredArguments() > 1;
1126 }
1127
1128 // C++2a [temp.param]p4:
1129 // [...] The concept designated by a type-constraint shall be a type
1130 // concept ([temp.concept]).
1131 if (!IsTypeConcept) {
1132 Diag(Loc: TypeConstr->TemplateNameLoc,
1133 DiagID: diag::err_type_constraint_non_type_concept);
1134 return true;
1135 }
1136
1137 if (CheckConceptUseInDefinition(Concept: CD, Loc: TypeConstr->TemplateNameLoc))
1138 return true;
1139
1140 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1141
1142 if (!WereArgsSpecified && RequiresArguments) {
1143 Diag(Loc: TypeConstr->TemplateNameLoc,
1144 DiagID: diag::err_type_constraint_missing_arguments)
1145 << CD;
1146 return true;
1147 }
1148 return false;
1149}
1150
1151bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1152 TemplateIdAnnotation *TypeConstr,
1153 TemplateTypeParmDecl *ConstrainedParameter,
1154 SourceLocation EllipsisLoc) {
1155 return BuildTypeConstraint(SS, TypeConstraint: TypeConstr, ConstrainedParameter, EllipsisLoc,
1156 AllowUnexpandedPack: false);
1157}
1158
1159bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1160 TemplateIdAnnotation *TypeConstr,
1161 TemplateTypeParmDecl *ConstrainedParameter,
1162 SourceLocation EllipsisLoc,
1163 bool AllowUnexpandedPack) {
1164
1165 if (CheckTypeConstraint(TypeConstr))
1166 return true;
1167
1168 TemplateName TN = TypeConstr->Template.get();
1169 TemplateDecl *CD = cast<TemplateDecl>(Val: TN.getAsTemplateDecl());
1170 UsingShadowDecl *USD = TN.getAsUsingShadowDecl();
1171
1172 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1173 TypeConstr->TemplateNameLoc);
1174
1175 TemplateArgumentListInfo TemplateArgs;
1176 if (TypeConstr->LAngleLoc.isValid()) {
1177 TemplateArgs =
1178 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TypeConstr);
1179
1180 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1181 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1182 if (DiagnoseUnexpandedParameterPack(Arg, UPPC: UPPC_TypeConstraint))
1183 return true;
1184 }
1185 }
1186 }
1187 return AttachTypeConstraint(
1188 NS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1189 NameInfo: ConceptName, NamedConcept: CD, /*FoundDecl=*/USD ? cast<NamedDecl>(Val: USD) : CD,
1190 TemplateArgs: TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1191 ConstrainedParameter, EllipsisLoc);
1192}
1193
1194template <typename ArgumentLocAppender>
1195static ExprResult formImmediatelyDeclaredConstraint(
1196 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1197 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1198 SourceLocation RAngleLoc, QualType ConstrainedType,
1199 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1200 SourceLocation EllipsisLoc) {
1201
1202 TemplateArgumentListInfo ConstraintArgs;
1203 ConstraintArgs.addArgument(
1204 Loc: S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(ConstrainedType),
1205 /*NTTPType=*/QualType(), Loc: ParamNameLoc));
1206
1207 ConstraintArgs.setRAngleLoc(RAngleLoc);
1208 ConstraintArgs.setLAngleLoc(LAngleLoc);
1209 Appender(ConstraintArgs);
1210
1211 // C++2a [temp.param]p4:
1212 // [...] This constraint-expression E is called the immediately-declared
1213 // constraint of T. [...]
1214 CXXScopeSpec SS;
1215 SS.Adopt(Other: NS);
1216 ExprResult ImmediatelyDeclaredConstraint;
1217 if (auto *CD = dyn_cast<ConceptDecl>(Val: NamedConcept)) {
1218 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1219 SS, /*TemplateKWLoc=*/SourceLocation(), ConceptNameInfo: NameInfo,
1220 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, NamedConcept: CD, TemplateArgs: &ConstraintArgs,
1221 /*DoCheckConstraintSatisfaction=*/
1222 !S.inParameterMappingSubstitution());
1223 }
1224 // We have a template template parameter
1225 else {
1226 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(Val: NamedConcept);
1227 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1228 SS, NameInfo, Template: CDT, TemplateLoc: SourceLocation(), TemplateArgs: &ConstraintArgs);
1229 }
1230 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1231 return ImmediatelyDeclaredConstraint;
1232
1233 // C++2a [temp.param]p4:
1234 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1235 //
1236 // We have the following case:
1237 //
1238 // template<typename T> concept C1 = true;
1239 // template<C1... T> struct s1;
1240 //
1241 // The constraint: (C1<T> && ...)
1242 //
1243 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1244 // any unqualified lookups for 'operator&&' here.
1245 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/Callee: nullptr,
1246 /*LParenLoc=*/SourceLocation(),
1247 LHS: ImmediatelyDeclaredConstraint.get(), Operator: BO_LAnd,
1248 EllipsisLoc, /*RHS=*/nullptr,
1249 /*RParenLoc=*/SourceLocation(),
1250 /*NumExpansions=*/std::nullopt);
1251}
1252
1253bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1254 DeclarationNameInfo NameInfo,
1255 TemplateDecl *NamedConcept,
1256 NamedDecl *FoundDecl,
1257 const TemplateArgumentListInfo *TemplateArgs,
1258 TemplateTypeParmDecl *ConstrainedParameter,
1259 SourceLocation EllipsisLoc) {
1260 // C++2a [temp.param]p4:
1261 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1262 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1263 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1264 TemplateArgs ? ASTTemplateArgumentListInfo::Create(C: Context,
1265 List: *TemplateArgs) : nullptr;
1266
1267 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1268
1269 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1270 S&: *this, NS, NameInfo, NamedConcept, FoundDecl,
1271 LAngleLoc: TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1272 RAngleLoc: TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1273 ConstrainedType: ParamAsArgument, ParamNameLoc: ConstrainedParameter->getLocation(),
1274 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1275 if (TemplateArgs)
1276 for (const auto &ArgLoc : TemplateArgs->arguments())
1277 ConstraintArgs.addArgument(Loc: ArgLoc);
1278 },
1279 EllipsisLoc);
1280 if (ImmediatelyDeclaredConstraint.isInvalid())
1281 return true;
1282
1283 auto *CL = ConceptReference::Create(C: Context, /*NNS=*/NS,
1284 /*TemplateKWLoc=*/SourceLocation{},
1285 /*ConceptNameInfo=*/NameInfo,
1286 /*FoundDecl=*/FoundDecl,
1287 /*NamedConcept=*/NamedConcept,
1288 /*ArgsWritten=*/ArgsAsWritten);
1289 ConstrainedParameter->setTypeConstraint(
1290 CR: CL, ImmediatelyDeclaredConstraint: ImmediatelyDeclaredConstraint.get(), ArgPackSubstIndex: std::nullopt);
1291 return false;
1292}
1293
1294bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1295 NonTypeTemplateParmDecl *NewConstrainedParm,
1296 NonTypeTemplateParmDecl *OrigConstrainedParm,
1297 SourceLocation EllipsisLoc) {
1298 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1299 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1300 Diag(Loc: NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1301 DiagID: diag::err_unsupported_placeholder_constraint)
1302 << NewConstrainedParm->getTypeSourceInfo()
1303 ->getTypeLoc()
1304 .getSourceRange();
1305 return true;
1306 }
1307 // FIXME: Concepts: This should be the type of the placeholder, but this is
1308 // unclear in the wording right now.
1309 DeclRefExpr *Ref =
1310 BuildDeclRefExpr(D: OrigConstrainedParm, Ty: OrigConstrainedParm->getType(),
1311 VK: VK_PRValue, Loc: OrigConstrainedParm->getLocation());
1312 if (!Ref)
1313 return true;
1314 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1315 S&: *this, NS: TL.getNestedNameSpecifierLoc(), NameInfo: TL.getConceptNameInfo(),
1316 NamedConcept: TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), LAngleLoc: TL.getLAngleLoc(),
1317 RAngleLoc: TL.getRAngleLoc(), ConstrainedType: BuildDecltypeType(E: Ref),
1318 ParamNameLoc: OrigConstrainedParm->getLocation(),
1319 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1320 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1321 ConstraintArgs.addArgument(Loc: TL.getArgLoc(i: I));
1322 },
1323 EllipsisLoc);
1324 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1325 !ImmediatelyDeclaredConstraint.isUsable())
1326 return true;
1327
1328 NewConstrainedParm->setPlaceholderTypeConstraint(
1329 ImmediatelyDeclaredConstraint.get());
1330 return false;
1331}
1332
1333QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1334 SourceLocation Loc) {
1335 if (TSI->getType()->isUndeducedType()) {
1336 // C++17 [temp.dep.expr]p3:
1337 // An id-expression is type-dependent if it contains
1338 // - an identifier associated by name lookup with a non-type
1339 // template-parameter declared with a type that contains a
1340 // placeholder type (7.1.7.4),
1341 TypeSourceInfo *NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSI);
1342 if (!NewTSI)
1343 return QualType();
1344 TSI = NewTSI;
1345 }
1346
1347 return CheckNonTypeTemplateParameterType(T: TSI->getType(), Loc);
1348}
1349
1350bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1351 if (T->isDependentType())
1352 return false;
1353
1354 if (RequireCompleteType(Loc, T, DiagID: diag::err_template_nontype_parm_incomplete))
1355 return true;
1356
1357 if (T->isStructuralType())
1358 return false;
1359
1360 // Structural types are required to be object types or lvalue references.
1361 if (T->isRValueReferenceType()) {
1362 Diag(Loc, DiagID: diag::err_template_nontype_parm_rvalue_ref) << T;
1363 return true;
1364 }
1365
1366 // Don't mention structural types in our diagnostic prior to C++20. Also,
1367 // there's not much more we can say about non-scalar non-class types --
1368 // because we can't see functions or arrays here, those can only be language
1369 // extensions.
1370 if (!getLangOpts().CPlusPlus20 ||
1371 (!T->isScalarType() && !T->isRecordType())) {
1372 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_type) << T;
1373 return true;
1374 }
1375
1376 // Structural types are required to be literal types.
1377 if (RequireLiteralType(Loc, T, DiagID: diag::err_template_nontype_parm_not_literal))
1378 return true;
1379
1380 Diag(Loc, DiagID: diag::err_template_nontype_parm_not_structural) << T;
1381
1382 // Drill down into the reason why the class is non-structural.
1383 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1384 // All members are required to be public and non-mutable, and can't be of
1385 // rvalue reference type. Check these conditions first to prefer a "local"
1386 // reason over a more distant one.
1387 for (const FieldDecl *FD : RD->fields()) {
1388 if (FD->getAccess() != AS_public) {
1389 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_non_public) << T << 0;
1390 return true;
1391 }
1392 if (FD->isMutable()) {
1393 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_mutable_field) << T;
1394 return true;
1395 }
1396 if (FD->getType()->isRValueReferenceType()) {
1397 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_rvalue_ref_field)
1398 << T;
1399 return true;
1400 }
1401 }
1402
1403 // All bases are required to be public.
1404 for (const auto &BaseSpec : RD->bases()) {
1405 if (BaseSpec.getAccessSpecifier() != AS_public) {
1406 Diag(Loc: BaseSpec.getBaseTypeLoc(), DiagID: diag::note_not_structural_non_public)
1407 << T << 1;
1408 return true;
1409 }
1410 }
1411
1412 // All subobjects are required to be of structural types.
1413 SourceLocation SubLoc;
1414 QualType SubType;
1415 int Kind = -1;
1416
1417 for (const FieldDecl *FD : RD->fields()) {
1418 QualType T = Context.getBaseElementType(QT: FD->getType());
1419 if (!T->isStructuralType()) {
1420 SubLoc = FD->getLocation();
1421 SubType = T;
1422 Kind = 0;
1423 break;
1424 }
1425 }
1426
1427 if (Kind == -1) {
1428 for (const auto &BaseSpec : RD->bases()) {
1429 QualType T = BaseSpec.getType();
1430 if (!T->isStructuralType()) {
1431 SubLoc = BaseSpec.getBaseTypeLoc();
1432 SubType = T;
1433 Kind = 1;
1434 break;
1435 }
1436 }
1437 }
1438
1439 assert(Kind != -1 && "couldn't find reason why type is not structural");
1440 Diag(Loc: SubLoc, DiagID: diag::note_not_structural_subobject)
1441 << T << Kind << SubType;
1442 T = SubType;
1443 RD = T->getAsCXXRecordDecl();
1444 }
1445
1446 return true;
1447}
1448
1449QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1450 SourceLocation Loc) {
1451 // We don't allow variably-modified types as the type of non-type template
1452 // parameters.
1453 if (T->isVariablyModifiedType()) {
1454 Diag(Loc, DiagID: diag::err_variably_modified_nontype_template_param)
1455 << T;
1456 return QualType();
1457 }
1458
1459 if (T->isBlockPointerType()) {
1460 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_type) << T;
1461 return QualType();
1462 }
1463
1464 // C++ [temp.param]p4:
1465 //
1466 // A non-type template-parameter shall have one of the following
1467 // (optionally cv-qualified) types:
1468 //
1469 // -- integral or enumeration type,
1470 if (T->isIntegralOrEnumerationType() ||
1471 // -- pointer to object or pointer to function,
1472 T->isPointerType() ||
1473 // -- lvalue reference to object or lvalue reference to function,
1474 T->isLValueReferenceType() ||
1475 // -- pointer to member,
1476 T->isMemberPointerType() ||
1477 // -- std::nullptr_t, or
1478 T->isNullPtrType() ||
1479 // -- a type that contains a placeholder type.
1480 T->isUndeducedType()) {
1481 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1482 // are ignored when determining its type.
1483 return T.getUnqualifiedType();
1484 }
1485
1486 // C++ [temp.param]p8:
1487 //
1488 // A non-type template-parameter of type "array of T" or
1489 // "function returning T" is adjusted to be of type "pointer to
1490 // T" or "pointer to function returning T", respectively.
1491 if (T->isArrayType() || T->isFunctionType())
1492 return Context.getDecayedType(T);
1493
1494 // If T is a dependent type, we can't do the check now, so we
1495 // assume that it is well-formed. Note that stripping off the
1496 // qualifiers here is not really correct if T turns out to be
1497 // an array type, but we'll recompute the type everywhere it's
1498 // used during instantiation, so that should be OK. (Using the
1499 // qualified type is equally wrong.)
1500 if (T->isDependentType())
1501 return T.getUnqualifiedType();
1502
1503 // C++20 [temp.param]p6:
1504 // -- a structural type
1505 if (RequireStructuralType(T, Loc))
1506 return QualType();
1507
1508 if (!getLangOpts().CPlusPlus20) {
1509 // FIXME: Consider allowing structural types as an extension in C++17. (In
1510 // earlier language modes, the template argument evaluation rules are too
1511 // inflexible.)
1512 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_structural_type) << T;
1513 return QualType();
1514 }
1515
1516 Diag(Loc, DiagID: diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1517 return T.getUnqualifiedType();
1518}
1519
1520NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1521 unsigned Depth,
1522 unsigned Position,
1523 SourceLocation EqualLoc,
1524 Expr *Default) {
1525 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1526
1527 // Check that we have valid decl-specifiers specified.
1528 auto CheckValidDeclSpecifiers = [this, &D] {
1529 // C++ [temp.param]
1530 // p1
1531 // template-parameter:
1532 // ...
1533 // parameter-declaration
1534 // p2
1535 // ... A storage class shall not be specified in a template-parameter
1536 // declaration.
1537 // [dcl.typedef]p1:
1538 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1539 // of a parameter-declaration
1540 const DeclSpec &DS = D.getDeclSpec();
1541 auto EmitDiag = [this](SourceLocation Loc) {
1542 Diag(Loc, DiagID: diag::err_invalid_decl_specifier_in_nontype_parm)
1543 << FixItHint::CreateRemoval(RemoveRange: Loc);
1544 };
1545 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1546 EmitDiag(DS.getStorageClassSpecLoc());
1547
1548 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1549 EmitDiag(DS.getThreadStorageClassSpecLoc());
1550
1551 // [dcl.inline]p1:
1552 // The inline specifier can be applied only to the declaration or
1553 // definition of a variable or function.
1554
1555 if (DS.isInlineSpecified())
1556 EmitDiag(DS.getInlineSpecLoc());
1557
1558 // [dcl.constexpr]p1:
1559 // The constexpr specifier shall be applied only to the definition of a
1560 // variable or variable template or the declaration of a function or
1561 // function template.
1562
1563 if (DS.hasConstexprSpecifier())
1564 EmitDiag(DS.getConstexprSpecLoc());
1565
1566 // [dcl.fct.spec]p1:
1567 // Function-specifiers can be used only in function declarations.
1568
1569 if (DS.isVirtualSpecified())
1570 EmitDiag(DS.getVirtualSpecLoc());
1571
1572 if (DS.hasExplicitSpecifier())
1573 EmitDiag(DS.getExplicitSpecLoc());
1574
1575 if (DS.isNoreturnSpecified())
1576 EmitDiag(DS.getNoreturnSpecLoc());
1577 };
1578
1579 CheckValidDeclSpecifiers();
1580
1581 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1582 if (isa<AutoType>(Val: T))
1583 Diag(Loc: D.getIdentifierLoc(),
1584 DiagID: diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1585 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1586
1587 assert(S->isTemplateParamScope() &&
1588 "Non-type template parameter not in template parameter scope!");
1589 bool Invalid = false;
1590
1591 QualType T = CheckNonTypeTemplateParameterType(TSI&: TInfo, Loc: D.getIdentifierLoc());
1592 if (T.isNull()) {
1593 T = Context.IntTy; // Recover with an 'int' type.
1594 Invalid = true;
1595 }
1596
1597 CheckFunctionOrTemplateParamDeclarator(S, D);
1598
1599 const IdentifierInfo *ParamName = D.getIdentifier();
1600 bool IsParameterPack = D.hasEllipsis();
1601 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1602 C: Context, DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
1603 IdLoc: D.getIdentifierLoc(), D: Depth, P: Position, Id: ParamName, T, ParameterPack: IsParameterPack,
1604 TInfo);
1605 Param->setAccess(AS_public);
1606
1607 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1608 if (TL.isConstrained()) {
1609 if (D.getEllipsisLoc().isInvalid() &&
1610 T->containsUnexpandedParameterPack()) {
1611 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1612 for (auto &Loc :
1613 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1614 Invalid |= DiagnoseUnexpandedParameterPack(
1615 Arg: Loc, UPPC: UnexpandedParameterPackContext::UPPC_TypeConstraint);
1616 }
1617 if (!Invalid &&
1618 AttachTypeConstraint(TL, NewConstrainedParm: Param, OrigConstrainedParm: Param, EllipsisLoc: D.getEllipsisLoc()))
1619 Invalid = true;
1620 }
1621
1622 if (Invalid)
1623 Param->setInvalidDecl();
1624
1625 if (Param->isParameterPack())
1626 if (auto *CSI = getEnclosingLambdaOrBlock())
1627 CSI->LocalPacks.push_back(Elt: Param);
1628
1629 if (ParamName) {
1630 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: D.getIdentifierLoc(),
1631 Name: ParamName);
1632
1633 // Add the template parameter into the current scope.
1634 S->AddDecl(D: Param);
1635 IdResolver.AddDecl(D: Param);
1636 }
1637
1638 // C++0x [temp.param]p9:
1639 // A default template-argument may be specified for any kind of
1640 // template-parameter that is not a template parameter pack.
1641 if (Default && IsParameterPack) {
1642 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1643 Default = nullptr;
1644 }
1645
1646 // Check the well-formedness of the default template argument, if provided.
1647 if (Default) {
1648 // Check for unexpanded parameter packs.
1649 if (DiagnoseUnexpandedParameterPack(E: Default, UPPC: UPPC_DefaultArgument))
1650 return Param;
1651
1652 Param->setDefaultArgument(
1653 C: Context, DefArg: getTrivialTemplateArgumentLoc(
1654 Arg: TemplateArgument(Default, /*IsCanonical=*/false),
1655 NTTPType: QualType(), Loc: SourceLocation()));
1656 }
1657
1658 return Param;
1659}
1660
1661/// ActOnTemplateTemplateParameter - Called when a C++ template template
1662/// parameter (e.g. T in template <template \<typename> class T> class array)
1663/// has been parsed. S is the current scope.
1664NamedDecl *Sema::ActOnTemplateTemplateParameter(
1665 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1666 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1667 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1668 unsigned Position, SourceLocation EqualLoc,
1669 ParsedTemplateArgument Default) {
1670 assert(S->isTemplateParamScope() &&
1671 "Template template parameter not in template parameter scope!");
1672
1673 bool IsParameterPack = EllipsisLoc.isValid();
1674
1675 SourceLocation Loc = NameLoc.isInvalid() ? TmpLoc : NameLoc;
1676 if (Params->size() == 0) {
1677 Diag(Loc, DiagID: diag::err_template_template_parm_no_parms)
1678 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1679
1680 // Recover as if there was a type template parameter pack.
1681 SmallVector<NamedDecl *, 4> ParamDecls;
1682 ParamDecls.push_back(Elt: TemplateTypeParmDecl::Create(
1683 C: Context, DC: Context.getTranslationUnitDecl(), KeyLoc: Loc, NameLoc: SourceLocation(),
1684 D: Depth + 1, P: 0, /*Id=*/nullptr,
1685 /*Typename=*/false, /*ParameterPack=*/true));
1686 Params = TemplateParameterList::Create(
1687 C: Context, TemplateLoc: Params->getTemplateLoc(), LAngleLoc: Params->getLAngleLoc(), Params: ParamDecls,
1688 RAngleLoc: Params->getRAngleLoc(), RequiresClause: Params->getRequiresClause());
1689 }
1690
1691 bool Invalid = false;
1692 if (CheckTemplateParameterList(
1693 NewParams: Params,
1694 /*OldParams=*/nullptr,
1695 TPC: IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1696 Invalid = true;
1697
1698 // Construct the parameter object.
1699 TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(
1700 C: Context, DC: Context.getTranslationUnitDecl(), L: Loc, D: Depth, P: Position,
1701 ParameterPack: IsParameterPack, Id: Name, ParameterKind: Kind, Typename, Params);
1702 Param->setAccess(AS_public);
1703
1704 if (Param->isParameterPack())
1705 if (auto *LSI = getEnclosingLambdaOrBlock())
1706 LSI->LocalPacks.push_back(Elt: Param);
1707
1708 // If the template template parameter has a name, then link the identifier
1709 // into the scope and lookup mechanisms.
1710 if (Name) {
1711 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: NameLoc, Name);
1712
1713 S->AddDecl(D: Param);
1714 IdResolver.AddDecl(D: Param);
1715 }
1716
1717 if (Invalid)
1718 Param->setInvalidDecl();
1719
1720 // C++0x [temp.param]p9:
1721 // A default template-argument may be specified for any kind of
1722 // template-parameter that is not a template parameter pack.
1723 if (IsParameterPack && !Default.isInvalid()) {
1724 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1725 Default = ParsedTemplateArgument();
1726 }
1727
1728 if (!Default.isInvalid()) {
1729 // Check only that we have a template template argument. We don't want to
1730 // try to check well-formedness now, because our template template parameter
1731 // might have dependent types in its template parameters, which we wouldn't
1732 // be able to match now.
1733 //
1734 // If none of the template template parameter's template arguments mention
1735 // other template parameters, we could actually perform more checking here.
1736 // However, it isn't worth doing.
1737 TemplateArgumentLoc DefaultArg = translateTemplateArgument(SemaRef&: *this, Arg: Default);
1738 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1739 Diag(Loc: DefaultArg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
1740 << DefaultArg.getSourceRange();
1741 return Param;
1742 }
1743
1744 TemplateName Name =
1745 DefaultArg.getArgument().getAsTemplateOrTemplatePattern();
1746 TemplateDecl *Template = Name.getAsTemplateDecl();
1747 if (Template &&
1748 !CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg: DefaultArg)) {
1749 return Param;
1750 }
1751
1752 // Check for unexpanded parameter packs.
1753 if (DiagnoseUnexpandedParameterPack(Loc: DefaultArg.getLocation(),
1754 Template: DefaultArg.getArgument().getAsTemplate(),
1755 UPPC: UPPC_DefaultArgument))
1756 return Param;
1757
1758 Param->setDefaultArgument(C: Context, DefArg: DefaultArg);
1759 }
1760
1761 return Param;
1762}
1763
1764namespace {
1765class ConstraintRefersToContainingTemplateChecker
1766 : public ConstDynamicRecursiveASTVisitor {
1767 using inherited = ConstDynamicRecursiveASTVisitor;
1768 bool Result = false;
1769 const FunctionDecl *Friend = nullptr;
1770 unsigned TemplateDepth = 0;
1771
1772 // Check a record-decl that we've seen to see if it is a lexical parent of the
1773 // Friend, likely because it was referred to without its template arguments.
1774 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1775 CheckingRD = CheckingRD->getMostRecentDecl();
1776 if (!CheckingRD->isTemplated())
1777 return true;
1778
1779 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1780 DC && !DC->isFileContext(); DC = DC->getParent())
1781 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
1782 if (CheckingRD == RD->getMostRecentDecl()) {
1783 Result = true;
1784 return false;
1785 }
1786
1787 return true;
1788 }
1789
1790 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1791 if (D->getDepth() < TemplateDepth)
1792 Result = true;
1793
1794 // Necessary because the type of the NTTP might be what refers to the parent
1795 // constriant.
1796 return TraverseType(T: D->getType());
1797 }
1798
1799public:
1800 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1801 unsigned TemplateDepth)
1802 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1803
1804 bool getResult() const { return Result; }
1805
1806 // This should be the only template parm type that we have to deal with.
1807 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1808 // FunctionParmPackExpr are all partially substituted, which cannot happen
1809 // with concepts at this point in translation.
1810 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1811 if (Type->getDecl()->getDepth() < TemplateDepth) {
1812 Result = true;
1813 return false;
1814 }
1815 return true;
1816 }
1817
1818 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1819 return TraverseDecl(D: E->getDecl());
1820 }
1821
1822 bool TraverseTypedefType(const TypedefType *TT,
1823 bool /*TraverseQualifier*/) override {
1824 return TraverseType(T: TT->desugar());
1825 }
1826
1827 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1828 // We don't care about TypeLocs. So traverse Types instead.
1829 return TraverseType(T: TL.getType(), TraverseQualifier);
1830 }
1831
1832 bool VisitTagType(const TagType *T) override {
1833 return TraverseDecl(D: T->getDecl());
1834 }
1835
1836 bool TraverseDecl(const Decl *D) override {
1837 assert(D);
1838 // FIXME : This is possibly an incomplete list, but it is unclear what other
1839 // Decl kinds could be used to refer to the template parameters. This is a
1840 // best guess so far based on examples currently available, but the
1841 // unreachable should catch future instances/cases.
1842 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
1843 return TraverseType(T: TD->getUnderlyingType());
1844 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Val: D))
1845 return CheckNonTypeTemplateParmDecl(D: NTTPD);
1846 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
1847 return TraverseType(T: VD->getType());
1848 if (isa<TemplateDecl>(Val: D))
1849 return true;
1850 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1851 return CheckIfContainingRecord(CheckingRD: RD);
1852
1853 if (isa<NamedDecl, RequiresExprBodyDecl>(Val: D)) {
1854 // No direct types to visit here I believe.
1855 } else
1856 llvm_unreachable("Don't know how to handle this declaration type yet");
1857 return true;
1858 }
1859};
1860} // namespace
1861
1862bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1863 const FunctionDecl *Friend, unsigned TemplateDepth,
1864 const Expr *Constraint) {
1865 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1866 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1867 Checker.TraverseStmt(S: Constraint);
1868 return Checker.getResult();
1869}
1870
1871TemplateParameterList *
1872Sema::ActOnTemplateParameterList(unsigned Depth,
1873 SourceLocation ExportLoc,
1874 SourceLocation TemplateLoc,
1875 SourceLocation LAngleLoc,
1876 ArrayRef<NamedDecl *> Params,
1877 SourceLocation RAngleLoc,
1878 Expr *RequiresClause) {
1879 if (ExportLoc.isValid())
1880 Diag(Loc: ExportLoc, DiagID: diag::warn_template_export_unsupported);
1881
1882 for (NamedDecl *P : Params)
1883 warnOnReservedIdentifier(D: P);
1884
1885 return TemplateParameterList::Create(C: Context, TemplateLoc, LAngleLoc,
1886 Params: llvm::ArrayRef(Params), RAngleLoc,
1887 RequiresClause);
1888}
1889
1890static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1891 const CXXScopeSpec &SS) {
1892 if (SS.isSet())
1893 T->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
1894}
1895
1896// Returns the template parameter list with all default template argument
1897// information.
1898TemplateParameterList *Sema::GetTemplateParameterList(TemplateDecl *TD) {
1899 // Make sure we get the template parameter list from the most
1900 // recent declaration, since that is the only one that is guaranteed to
1901 // have all the default template argument information.
1902 Decl *D = TD->getMostRecentDecl();
1903 // C++11 N3337 [temp.param]p12:
1904 // A default template argument shall not be specified in a friend class
1905 // template declaration.
1906 //
1907 // Skip past friend *declarations* because they are not supposed to contain
1908 // default template arguments. Moreover, these declarations may introduce
1909 // template parameters living in different template depths than the
1910 // corresponding template parameters in TD, causing unmatched constraint
1911 // substitution.
1912 //
1913 // FIXME: Diagnose such cases within a class template:
1914 // template <class T>
1915 // struct S {
1916 // template <class = void> friend struct C;
1917 // };
1918 // template struct S<int>;
1919 while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1920 D->getPreviousDecl())
1921 D = D->getPreviousDecl();
1922 return cast<TemplateDecl>(Val: D)->getTemplateParameters();
1923}
1924
1925DeclResult Sema::CheckClassTemplate(
1926 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1927 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1928 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1929 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1930 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1931 TemplateParameterList **OuterTemplateParamLists,
1932 bool IsMemberSpecialization, SkipBodyInfo *SkipBody) {
1933 assert(TemplateParams && TemplateParams->size() > 0 &&
1934 "No template parameters");
1935 assert(TUK != TagUseKind::Reference &&
1936 "Can only declare or define class templates");
1937 bool Invalid = false;
1938
1939 // Check that we can declare a template here.
1940 if (CheckTemplateDeclScope(S, TemplateParams))
1941 return true;
1942
1943 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
1944 assert(Kind != TagTypeKind::Enum &&
1945 "can't build template of enumerated type");
1946
1947 // There is no such thing as an unnamed class template.
1948 if (!Name) {
1949 Diag(Loc: KWLoc, DiagID: diag::err_template_unnamed_class);
1950 return true;
1951 }
1952
1953 // Find any previous declaration with this name. For a friend with no
1954 // scope explicitly specified, we only look for tag declarations (per
1955 // C++11 [basic.lookup.elab]p2).
1956 DeclContext *SemanticContext;
1957 LookupResult Previous(*this, Name, NameLoc,
1958 (SS.isEmpty() && TUK == TagUseKind::Friend)
1959 ? LookupTagName
1960 : LookupOrdinaryName,
1961 forRedeclarationInCurContext());
1962 if (SS.isNotEmpty() && !SS.isInvalid()) {
1963 SemanticContext = computeDeclContext(SS, EnteringContext: true);
1964 if (!SemanticContext) {
1965 // FIXME: Horrible, horrible hack! We can't currently represent this
1966 // in the AST, and historically we have just ignored such friend
1967 // class templates, so don't complain here.
1968 Diag(Loc: NameLoc, DiagID: TUK == TagUseKind::Friend
1969 ? diag::warn_template_qualified_friend_ignored
1970 : diag::err_template_qualified_declarator_no_match)
1971 << SS.getScopeRep() << SS.getRange();
1972 return TUK != TagUseKind::Friend;
1973 }
1974
1975 if (RequireCompleteDeclContext(SS, DC: SemanticContext))
1976 return true;
1977
1978 // If we're adding a template to a dependent context, we may need to
1979 // rebuilding some of the types used within the template parameter list,
1980 // now that we know what the current instantiation is.
1981 if (SemanticContext->isDependentContext()) {
1982 ContextRAII SavedContext(*this, SemanticContext);
1983 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
1984 Invalid = true;
1985 }
1986
1987 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1988 diagnoseQualifiedDeclaration(SS, DC: SemanticContext, Name, Loc: NameLoc,
1989 /*TemplateId-*/ TemplateId: nullptr,
1990 /*IsMemberSpecialization*/ false);
1991
1992 LookupQualifiedName(R&: Previous, LookupCtx: SemanticContext);
1993 } else {
1994 SemanticContext = CurContext;
1995
1996 // C++14 [class.mem]p14:
1997 // If T is the name of a class, then each of the following shall have a
1998 // name different from T:
1999 // -- every member template of class T
2000 if (TUK != TagUseKind::Friend &&
2001 DiagnoseClassNameShadow(DC: SemanticContext,
2002 Info: DeclarationNameInfo(Name, NameLoc)))
2003 return true;
2004
2005 LookupName(R&: Previous, S);
2006 }
2007
2008 if (Previous.isAmbiguous())
2009 return true;
2010
2011 // Let the template parameter scope enter the lookup chain of the current
2012 // class template. For example, given
2013 //
2014 // namespace ns {
2015 // template <class> bool Param = false;
2016 // template <class T> struct N;
2017 // }
2018 //
2019 // template <class Param> struct ns::N { void foo(Param); };
2020 //
2021 // When we reference Param inside the function parameter list, our name lookup
2022 // chain for it should be like:
2023 // FunctionScope foo
2024 // -> RecordScope N
2025 // -> TemplateParamScope (where we will find Param)
2026 // -> NamespaceScope ns
2027 //
2028 // See also CppLookupName().
2029 if (S->isTemplateParamScope())
2030 EnterTemplatedContext(S, DC: SemanticContext);
2031
2032 NamedDecl *PrevDecl = nullptr;
2033 if (Previous.begin() != Previous.end())
2034 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2035
2036 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2037 // Maybe we will complain about the shadowed template parameter.
2038 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl);
2039 // Just pretend that we didn't see the previous declaration.
2040 PrevDecl = nullptr;
2041 }
2042
2043 // If there is a previous declaration with the same name, check
2044 // whether this is a valid redeclaration.
2045 ClassTemplateDecl *PrevClassTemplate =
2046 dyn_cast_or_null<ClassTemplateDecl>(Val: PrevDecl);
2047
2048 // We may have found the injected-class-name of a class template,
2049 // class template partial specialization, or class template specialization.
2050 // In these cases, grab the template that is being defined or specialized.
2051 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(Val: PrevDecl) &&
2052 cast<CXXRecordDecl>(Val: PrevDecl)->isInjectedClassName()) {
2053 PrevDecl = cast<CXXRecordDecl>(Val: PrevDecl->getDeclContext());
2054 PrevClassTemplate
2055 = cast<CXXRecordDecl>(Val: PrevDecl)->getDescribedClassTemplate();
2056 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(Val: PrevDecl)) {
2057 PrevClassTemplate
2058 = cast<ClassTemplateSpecializationDecl>(Val: PrevDecl)
2059 ->getSpecializedTemplate();
2060 }
2061 }
2062
2063 if (TUK == TagUseKind::Friend) {
2064 // C++ [namespace.memdef]p3:
2065 // [...] When looking for a prior declaration of a class or a function
2066 // declared as a friend, and when the name of the friend class or
2067 // function is neither a qualified name nor a template-id, scopes outside
2068 // the innermost enclosing namespace scope are not considered.
2069 if (!SS.isSet()) {
2070 DeclContext *OutermostContext = CurContext;
2071 while (!OutermostContext->isFileContext())
2072 OutermostContext = OutermostContext->getLookupParent();
2073
2074 if (PrevDecl &&
2075 (OutermostContext->Equals(DC: PrevDecl->getDeclContext()) ||
2076 OutermostContext->Encloses(DC: PrevDecl->getDeclContext()))) {
2077 SemanticContext = PrevDecl->getDeclContext();
2078 } else {
2079 // Declarations in outer scopes don't matter. However, the outermost
2080 // context we computed is the semantic context for our new
2081 // declaration.
2082 PrevDecl = PrevClassTemplate = nullptr;
2083 SemanticContext = OutermostContext;
2084
2085 // Check that the chosen semantic context doesn't already contain a
2086 // declaration of this name as a non-tag type.
2087 Previous.clear(Kind: LookupOrdinaryName);
2088 DeclContext *LookupContext = SemanticContext;
2089 while (LookupContext->isTransparentContext())
2090 LookupContext = LookupContext->getLookupParent();
2091 LookupQualifiedName(R&: Previous, LookupCtx: LookupContext);
2092
2093 if (Previous.isAmbiguous())
2094 return true;
2095
2096 if (Previous.begin() != Previous.end())
2097 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2098 }
2099 }
2100 } else if (PrevDecl && !isDeclInScope(D: Previous.getRepresentativeDecl(),
2101 Ctx: SemanticContext, S, AllowInlineNamespace: SS.isValid()))
2102 PrevDecl = PrevClassTemplate = nullptr;
2103
2104 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2105 Val: PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2106 if (SS.isEmpty() &&
2107 !(PrevClassTemplate &&
2108 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2109 DC: SemanticContext->getRedeclContext()))) {
2110 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
2111 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
2112 DiagID: diag::note_using_decl_target);
2113 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
2114 // Recover by ignoring the old declaration.
2115 PrevDecl = PrevClassTemplate = nullptr;
2116 }
2117 }
2118
2119 if (PrevClassTemplate) {
2120 // Ensure that the template parameter lists are compatible. Skip this check
2121 // for a friend in a dependent context: the template parameter list itself
2122 // could be dependent.
2123 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2124 !TemplateParameterListsAreEqual(
2125 NewInstFrom: TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2126 : CurContext,
2127 CurContext, KWLoc),
2128 New: TemplateParams, OldInstFrom: PrevClassTemplate,
2129 Old: PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2130 Kind: TPL_TemplateMatch))
2131 return true;
2132
2133 // C++ [temp.class]p4:
2134 // In a redeclaration, partial specialization, explicit
2135 // specialization or explicit instantiation of a class template,
2136 // the class-key shall agree in kind with the original class
2137 // template declaration (7.1.5.3).
2138 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2139 if (!isAcceptableTagRedeclaration(
2140 Previous: PrevRecordDecl, NewTag: Kind, isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc, Name)) {
2141 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
2142 << Name
2143 << FixItHint::CreateReplacement(RemoveRange: KWLoc, Code: PrevRecordDecl->getKindName());
2144 Diag(Loc: PrevRecordDecl->getLocation(), DiagID: diag::note_previous_use);
2145 Kind = PrevRecordDecl->getTagKind();
2146 }
2147
2148 // Check for redefinition of this class template.
2149 if (TUK == TagUseKind::Definition) {
2150 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2151 // If we have a prior definition that is not visible, treat this as
2152 // simply making that previous definition visible.
2153 NamedDecl *Hidden = nullptr;
2154 bool HiddenDefVisible = false;
2155 if (SkipBody &&
2156 isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible)) {
2157 SkipBody->ShouldSkip = true;
2158 SkipBody->Previous = Def;
2159 if (!HiddenDefVisible && Hidden) {
2160 auto *Tmpl =
2161 cast<CXXRecordDecl>(Val: Hidden)->getDescribedClassTemplate();
2162 assert(Tmpl && "original definition of a class template is not a "
2163 "class template?");
2164 makeMergedDefinitionVisible(ND: Hidden);
2165 makeMergedDefinitionVisible(ND: Tmpl);
2166 }
2167 } else {
2168 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
2169 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
2170 // FIXME: Would it make sense to try to "forget" the previous
2171 // definition, as part of error recovery?
2172 return true;
2173 }
2174 }
2175 }
2176 } else if (PrevDecl) {
2177 // C++ [temp]p5:
2178 // A class template shall not have the same name as any other
2179 // template, class, function, object, enumeration, enumerator,
2180 // namespace, or type in the same scope (3.3), except as specified
2181 // in (14.5.4).
2182 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
2183 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
2184 return true;
2185 }
2186
2187 // Check the template parameter list of this declaration, possibly
2188 // merging in the template parameter list from the previous class
2189 // template declaration. Skip this check for a friend in a dependent
2190 // context, because the template parameter list might be dependent.
2191 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2192 CheckTemplateParameterList(
2193 NewParams: TemplateParams,
2194 OldParams: PrevClassTemplate ? GetTemplateParameterList(TD: PrevClassTemplate)
2195 : nullptr,
2196 TPC: (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2197 SemanticContext->isDependentContext())
2198 ? TPC_ClassTemplateMember
2199 : TUK == TagUseKind::Friend ? TPC_FriendClassTemplate
2200 : TPC_Other,
2201 SkipBody))
2202 Invalid = true;
2203
2204 if (SS.isSet()) {
2205 // If the name of the template was qualified, we must be defining the
2206 // template out-of-line.
2207 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2208 Diag(Loc: NameLoc, DiagID: TUK == TagUseKind::Friend
2209 ? diag::err_friend_decl_does_not_match
2210 : diag::err_member_decl_does_not_match)
2211 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2212 Invalid = true;
2213 }
2214 }
2215
2216 // If this is a templated friend in a dependent context we should not put it
2217 // on the redecl chain. In some cases, the templated friend can be the most
2218 // recent declaration tricking the template instantiator to make substitutions
2219 // there.
2220 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2221 bool ShouldAddRedecl =
2222 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2223
2224 CXXRecordDecl *NewClass = CXXRecordDecl::Create(
2225 C: Context, TK: Kind, DC: SemanticContext, StartLoc: KWLoc, IdLoc: NameLoc, Id: Name,
2226 PrevDecl: PrevClassTemplate && ShouldAddRedecl
2227 ? PrevClassTemplate->getTemplatedDecl()
2228 : nullptr);
2229 SetNestedNameSpecifier(S&: *this, T: NewClass, SS);
2230 if (NumOuterTemplateParamLists > 0)
2231 NewClass->setTemplateParameterListsInfo(
2232 Context,
2233 TPLists: llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2234
2235 // Add alignment attributes if necessary; these attributes are checked when
2236 // the ASTContext lays out the structure.
2237 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2238 if (LangOpts.HLSL)
2239 NewClass->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
2240 AddAlignmentAttributesForRecord(RD: NewClass);
2241 AddMsStructLayoutForRecord(RD: NewClass);
2242 }
2243
2244 ClassTemplateDecl *NewTemplate
2245 = ClassTemplateDecl::Create(C&: Context, DC: SemanticContext, L: NameLoc,
2246 Name: DeclarationName(Name), Params: TemplateParams,
2247 Decl: NewClass);
2248
2249 if (ShouldAddRedecl)
2250 NewTemplate->setPreviousDecl(PrevClassTemplate);
2251
2252 NewClass->setDescribedClassTemplate(NewTemplate);
2253
2254 if (ModulePrivateLoc.isValid())
2255 NewTemplate->setModulePrivate();
2256
2257 if (!Invalid && IsMemberSpecialization) {
2258 assert(PrevClassTemplate &&
2259 "Member specialization without a primary template?");
2260 NewTemplate->setMemberSpecialization();
2261 }
2262
2263 // Set the access specifier.
2264 if (!Invalid && TUK != TagUseKind::Friend &&
2265 NewTemplate->getDeclContext()->isRecord())
2266 SetMemberAccessSpecifier(MemberDecl: NewTemplate, PrevMemberDecl: PrevClassTemplate, LexicalAS: AS);
2267
2268 // Set the lexical context of these templates
2269 NewClass->setLexicalDeclContext(CurContext);
2270 NewTemplate->setLexicalDeclContext(CurContext);
2271
2272 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2273 NewClass->startDefinition();
2274
2275 ProcessDeclAttributeList(S, D: NewClass, AttrList: Attr);
2276
2277 if (PrevClassTemplate)
2278 mergeDeclAttributes(New: NewClass, Old: PrevClassTemplate->getTemplatedDecl());
2279
2280 AddPushedVisibilityAttribute(RD: NewClass);
2281 inferGslOwnerPointerAttribute(Record: NewClass);
2282 inferNullableClassAttribute(CRD: NewClass);
2283
2284 if (TUK != TagUseKind::Friend) {
2285 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2286 Scope *Outer = S;
2287 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2288 Outer = Outer->getParent();
2289 PushOnScopeChains(D: NewTemplate, S: Outer);
2290 } else {
2291 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2292 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2293 NewClass->setAccess(PrevClassTemplate->getAccess());
2294 }
2295
2296 NewTemplate->setObjectOfFriendDecl();
2297
2298 // Friend templates are visible in fairly strange ways.
2299 if (!CurContext->isDependentContext()) {
2300 DeclContext *DC = SemanticContext->getRedeclContext();
2301 DC->makeDeclVisibleInContext(D: NewTemplate);
2302 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2303 PushOnScopeChains(D: NewTemplate, S: EnclosingScope,
2304 /* AddToContext = */ false);
2305 }
2306
2307 FriendDecl *Friend = FriendDecl::Create(
2308 C&: Context, DC: CurContext, L: NewClass->getLocation(), Friend_: NewTemplate, FriendL: FriendLoc);
2309 Friend->setAccess(AS_public);
2310 CurContext->addDecl(D: Friend);
2311 }
2312
2313 if (PrevClassTemplate)
2314 CheckRedeclarationInModule(New: NewTemplate, Old: PrevClassTemplate);
2315
2316 if (Invalid) {
2317 NewTemplate->setInvalidDecl();
2318 NewClass->setInvalidDecl();
2319 }
2320
2321 ActOnDocumentableDecl(D: NewTemplate);
2322
2323 if (SkipBody && SkipBody->ShouldSkip)
2324 return SkipBody->Previous;
2325
2326 return NewTemplate;
2327}
2328
2329/// Diagnose the presence of a default template argument on a
2330/// template parameter, which is ill-formed in certain contexts.
2331///
2332/// \returns true if the default template argument should be dropped.
2333static bool DiagnoseDefaultTemplateArgument(Sema &S,
2334 Sema::TemplateParamListContext TPC,
2335 SourceLocation ParamLoc,
2336 SourceRange DefArgRange) {
2337 switch (TPC) {
2338 case Sema::TPC_Other:
2339 case Sema::TPC_TemplateTemplateParameterPack:
2340 return false;
2341
2342 case Sema::TPC_FunctionTemplate:
2343 case Sema::TPC_FriendFunctionTemplateDefinition:
2344 // C++ [temp.param]p9:
2345 // A default template-argument shall not be specified in a
2346 // function template declaration or a function template
2347 // definition [...]
2348 // If a friend function template declaration specifies a default
2349 // template-argument, that declaration shall be a definition and shall be
2350 // the only declaration of the function template in the translation unit.
2351 // (C++98/03 doesn't have this wording; see DR226).
2352 S.DiagCompat(Loc: ParamLoc, CompatDiagId: diag_compat::templ_default_in_function_templ)
2353 << DefArgRange;
2354 return false;
2355
2356 case Sema::TPC_ClassTemplateMember:
2357 // C++0x [temp.param]p9:
2358 // A default template-argument shall not be specified in the
2359 // template-parameter-lists of the definition of a member of a
2360 // class template that appears outside of the member's class.
2361 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_template_member)
2362 << DefArgRange;
2363 return true;
2364
2365 case Sema::TPC_FriendClassTemplate:
2366 case Sema::TPC_FriendFunctionTemplate:
2367 // C++ [temp.param]p9:
2368 // A default template-argument shall not be specified in a
2369 // friend template declaration.
2370 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_friend_template)
2371 << DefArgRange;
2372 return true;
2373
2374 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2375 // for friend function templates if there is only a single
2376 // declaration (and it is a definition). Strange!
2377 }
2378
2379 llvm_unreachable("Invalid TemplateParamListContext!");
2380}
2381
2382/// Check for unexpanded parameter packs within the template parameters
2383/// of a template template parameter, recursively.
2384static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2385 TemplateTemplateParmDecl *TTP) {
2386 // A template template parameter which is a parameter pack is also a pack
2387 // expansion.
2388 if (TTP->isParameterPack())
2389 return false;
2390
2391 TemplateParameterList *Params = TTP->getTemplateParameters();
2392 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2393 NamedDecl *P = Params->getParam(Idx: I);
2394 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: P)) {
2395 if (!TTP->isParameterPack())
2396 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2397 if (TC->hasExplicitTemplateArgs())
2398 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2399 if (S.DiagnoseUnexpandedParameterPack(Arg: ArgLoc,
2400 UPPC: Sema::UPPC_TypeConstraint))
2401 return true;
2402 continue;
2403 }
2404
2405 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) {
2406 if (!NTTP->isParameterPack() &&
2407 S.DiagnoseUnexpandedParameterPack(Loc: NTTP->getLocation(),
2408 T: NTTP->getTypeSourceInfo(),
2409 UPPC: Sema::UPPC_NonTypeTemplateParameterType))
2410 return true;
2411
2412 continue;
2413 }
2414
2415 if (TemplateTemplateParmDecl *InnerTTP
2416 = dyn_cast<TemplateTemplateParmDecl>(Val: P))
2417 if (DiagnoseUnexpandedParameterPacks(S, TTP: InnerTTP))
2418 return true;
2419 }
2420
2421 return false;
2422}
2423
2424bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2425 TemplateParameterList *OldParams,
2426 TemplateParamListContext TPC,
2427 SkipBodyInfo *SkipBody) {
2428 bool Invalid = false;
2429
2430 // C++ [temp.param]p10:
2431 // The set of default template-arguments available for use with a
2432 // template declaration or definition is obtained by merging the
2433 // default arguments from the definition (if in scope) and all
2434 // declarations in scope in the same way default function
2435 // arguments are (8.3.6).
2436 bool SawDefaultArgument = false;
2437 SourceLocation PreviousDefaultArgLoc;
2438
2439 // Dummy initialization to avoid warnings.
2440 TemplateParameterList::iterator OldParam = NewParams->end();
2441 if (OldParams)
2442 OldParam = OldParams->begin();
2443
2444 bool RemoveDefaultArguments = false;
2445 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2446 NewParamEnd = NewParams->end();
2447 NewParam != NewParamEnd; ++NewParam) {
2448 // Whether we've seen a duplicate default argument in the same translation
2449 // unit.
2450 bool RedundantDefaultArg = false;
2451 // Whether we've found inconsis inconsitent default arguments in different
2452 // translation unit.
2453 bool InconsistentDefaultArg = false;
2454 // The name of the module which contains the inconsistent default argument.
2455 std::string PrevModuleName;
2456
2457 SourceLocation OldDefaultLoc;
2458 SourceLocation NewDefaultLoc;
2459
2460 // Variable used to diagnose missing default arguments
2461 bool MissingDefaultArg = false;
2462
2463 // Variable used to diagnose non-final parameter packs
2464 bool SawParameterPack = false;
2465
2466 if (TemplateTypeParmDecl *NewTypeParm
2467 = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam)) {
2468 // Check the presence of a default argument here.
2469 if (NewTypeParm->hasDefaultArgument() &&
2470 DiagnoseDefaultTemplateArgument(
2471 S&: *this, TPC, ParamLoc: NewTypeParm->getLocation(),
2472 DefArgRange: NewTypeParm->getDefaultArgument().getSourceRange()))
2473 NewTypeParm->removeDefaultArgument();
2474
2475 // Merge default arguments for template type parameters.
2476 TemplateTypeParmDecl *OldTypeParm
2477 = OldParams? cast<TemplateTypeParmDecl>(Val: *OldParam) : nullptr;
2478 if (NewTypeParm->isParameterPack()) {
2479 assert(!NewTypeParm->hasDefaultArgument() &&
2480 "Parameter packs can't have a default argument!");
2481 SawParameterPack = true;
2482 } else if (OldTypeParm && hasVisibleDefaultArgument(D: OldTypeParm) &&
2483 NewTypeParm->hasDefaultArgument() &&
2484 (!SkipBody || !SkipBody->ShouldSkip)) {
2485 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2486 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2487 SawDefaultArgument = true;
2488
2489 if (!OldTypeParm->getOwningModule())
2490 RedundantDefaultArg = true;
2491 else if (!getASTContext().isSameDefaultTemplateArgument(X: OldTypeParm,
2492 Y: NewTypeParm)) {
2493 InconsistentDefaultArg = true;
2494 PrevModuleName =
2495 OldTypeParm->getImportedOwningModule()->getFullModuleName();
2496 }
2497 PreviousDefaultArgLoc = NewDefaultLoc;
2498 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2499 // Merge the default argument from the old declaration to the
2500 // new declaration.
2501 NewTypeParm->setInheritedDefaultArgument(C: Context, Prev: OldTypeParm);
2502 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2503 } else if (NewTypeParm->hasDefaultArgument()) {
2504 SawDefaultArgument = true;
2505 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2506 } else if (SawDefaultArgument)
2507 MissingDefaultArg = true;
2508 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2509 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam)) {
2510 // Check for unexpanded parameter packs, except in a template template
2511 // parameter pack, as in those any unexpanded packs should be expanded
2512 // along with the parameter itself.
2513 if (TPC != TPC_TemplateTemplateParameterPack &&
2514 !NewNonTypeParm->isParameterPack() &&
2515 DiagnoseUnexpandedParameterPack(Loc: NewNonTypeParm->getLocation(),
2516 T: NewNonTypeParm->getTypeSourceInfo(),
2517 UPPC: UPPC_NonTypeTemplateParameterType)) {
2518 Invalid = true;
2519 continue;
2520 }
2521
2522 // Check the presence of a default argument here.
2523 if (NewNonTypeParm->hasDefaultArgument() &&
2524 DiagnoseDefaultTemplateArgument(
2525 S&: *this, TPC, ParamLoc: NewNonTypeParm->getLocation(),
2526 DefArgRange: NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2527 NewNonTypeParm->removeDefaultArgument();
2528 }
2529
2530 // Merge default arguments for non-type template parameters
2531 NonTypeTemplateParmDecl *OldNonTypeParm
2532 = OldParams? cast<NonTypeTemplateParmDecl>(Val: *OldParam) : nullptr;
2533 if (NewNonTypeParm->isParameterPack()) {
2534 assert(!NewNonTypeParm->hasDefaultArgument() &&
2535 "Parameter packs can't have a default argument!");
2536 if (!NewNonTypeParm->isPackExpansion())
2537 SawParameterPack = true;
2538 } else if (OldNonTypeParm && hasVisibleDefaultArgument(D: OldNonTypeParm) &&
2539 NewNonTypeParm->hasDefaultArgument() &&
2540 (!SkipBody || !SkipBody->ShouldSkip)) {
2541 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2542 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2543 SawDefaultArgument = true;
2544 if (!OldNonTypeParm->getOwningModule())
2545 RedundantDefaultArg = true;
2546 else if (!getASTContext().isSameDefaultTemplateArgument(
2547 X: OldNonTypeParm, Y: NewNonTypeParm)) {
2548 InconsistentDefaultArg = true;
2549 PrevModuleName =
2550 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2551 }
2552 PreviousDefaultArgLoc = NewDefaultLoc;
2553 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2554 // Merge the default argument from the old declaration to the
2555 // new declaration.
2556 NewNonTypeParm->setInheritedDefaultArgument(C: Context, Parm: OldNonTypeParm);
2557 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2558 } else if (NewNonTypeParm->hasDefaultArgument()) {
2559 SawDefaultArgument = true;
2560 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2561 } else if (SawDefaultArgument)
2562 MissingDefaultArg = true;
2563 } else {
2564 TemplateTemplateParmDecl *NewTemplateParm
2565 = cast<TemplateTemplateParmDecl>(Val: *NewParam);
2566
2567 // Check for unexpanded parameter packs, recursively.
2568 if (::DiagnoseUnexpandedParameterPacks(S&: *this, TTP: NewTemplateParm)) {
2569 Invalid = true;
2570 continue;
2571 }
2572
2573 // Check the presence of a default argument here.
2574 if (NewTemplateParm->hasDefaultArgument() &&
2575 DiagnoseDefaultTemplateArgument(S&: *this, TPC,
2576 ParamLoc: NewTemplateParm->getLocation(),
2577 DefArgRange: NewTemplateParm->getDefaultArgument().getSourceRange()))
2578 NewTemplateParm->removeDefaultArgument();
2579
2580 // Merge default arguments for template template parameters
2581 TemplateTemplateParmDecl *OldTemplateParm
2582 = OldParams? cast<TemplateTemplateParmDecl>(Val: *OldParam) : nullptr;
2583 if (NewTemplateParm->isParameterPack()) {
2584 assert(!NewTemplateParm->hasDefaultArgument() &&
2585 "Parameter packs can't have a default argument!");
2586 if (!NewTemplateParm->isPackExpansion())
2587 SawParameterPack = true;
2588 } else if (OldTemplateParm &&
2589 hasVisibleDefaultArgument(D: OldTemplateParm) &&
2590 NewTemplateParm->hasDefaultArgument() &&
2591 (!SkipBody || !SkipBody->ShouldSkip)) {
2592 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2593 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2594 SawDefaultArgument = true;
2595 if (!OldTemplateParm->getOwningModule())
2596 RedundantDefaultArg = true;
2597 else if (!getASTContext().isSameDefaultTemplateArgument(
2598 X: OldTemplateParm, Y: NewTemplateParm)) {
2599 InconsistentDefaultArg = true;
2600 PrevModuleName =
2601 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2602 }
2603 PreviousDefaultArgLoc = NewDefaultLoc;
2604 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2605 // Merge the default argument from the old declaration to the
2606 // new declaration.
2607 NewTemplateParm->setInheritedDefaultArgument(C: Context, Prev: OldTemplateParm);
2608 PreviousDefaultArgLoc
2609 = OldTemplateParm->getDefaultArgument().getLocation();
2610 } else if (NewTemplateParm->hasDefaultArgument()) {
2611 SawDefaultArgument = true;
2612 PreviousDefaultArgLoc
2613 = NewTemplateParm->getDefaultArgument().getLocation();
2614 } else if (SawDefaultArgument)
2615 MissingDefaultArg = true;
2616 }
2617
2618 // C++11 [temp.param]p11:
2619 // If a template parameter of a primary class template or alias template
2620 // is a template parameter pack, it shall be the last template parameter.
2621 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2622 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2623 Diag(Loc: (*NewParam)->getLocation(),
2624 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
2625 Invalid = true;
2626 }
2627
2628 // [basic.def.odr]/13:
2629 // There can be more than one definition of a
2630 // ...
2631 // default template argument
2632 // ...
2633 // in a program provided that each definition appears in a different
2634 // translation unit and the definitions satisfy the [same-meaning
2635 // criteria of the ODR].
2636 //
2637 // Simply, the design of modules allows the definition of template default
2638 // argument to be repeated across translation unit. Note that the ODR is
2639 // checked elsewhere. But it is still not allowed to repeat template default
2640 // argument in the same translation unit.
2641 if (RedundantDefaultArg) {
2642 Diag(Loc: NewDefaultLoc, DiagID: diag::err_template_param_default_arg_redefinition);
2643 Diag(Loc: OldDefaultLoc, DiagID: diag::note_template_param_prev_default_arg);
2644 Invalid = true;
2645 } else if (InconsistentDefaultArg) {
2646 // We could only diagnose about the case that the OldParam is imported.
2647 // The case NewParam is imported should be handled in ASTReader.
2648 Diag(Loc: NewDefaultLoc,
2649 DiagID: diag::err_template_param_default_arg_inconsistent_redefinition);
2650 Diag(Loc: OldDefaultLoc,
2651 DiagID: diag::note_template_param_prev_default_arg_in_other_module)
2652 << PrevModuleName;
2653 Invalid = true;
2654 } else if (MissingDefaultArg &&
2655 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2656 TPC == TPC_FriendClassTemplate)) {
2657 // C++ 23[temp.param]p14:
2658 // If a template-parameter of a class template, variable template, or
2659 // alias template has a default template argument, each subsequent
2660 // template-parameter shall either have a default template argument
2661 // supplied or be a template parameter pack.
2662 Diag(Loc: (*NewParam)->getLocation(),
2663 DiagID: diag::err_template_param_default_arg_missing);
2664 Diag(Loc: PreviousDefaultArgLoc, DiagID: diag::note_template_param_prev_default_arg);
2665 Invalid = true;
2666 RemoveDefaultArguments = true;
2667 }
2668
2669 // If we have an old template parameter list that we're merging
2670 // in, move on to the next parameter.
2671 if (OldParams)
2672 ++OldParam;
2673 }
2674
2675 // We were missing some default arguments at the end of the list, so remove
2676 // all of the default arguments.
2677 if (RemoveDefaultArguments) {
2678 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2679 NewParamEnd = NewParams->end();
2680 NewParam != NewParamEnd; ++NewParam) {
2681 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam))
2682 TTP->removeDefaultArgument();
2683 else if (NonTypeTemplateParmDecl *NTTP
2684 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam))
2685 NTTP->removeDefaultArgument();
2686 else
2687 cast<TemplateTemplateParmDecl>(Val: *NewParam)->removeDefaultArgument();
2688 }
2689 }
2690
2691 return Invalid;
2692}
2693
2694namespace {
2695
2696/// A class which looks for a use of a certain level of template
2697/// parameter.
2698struct DependencyChecker : DynamicRecursiveASTVisitor {
2699 unsigned Depth;
2700
2701 // Whether we're looking for a use of a template parameter that makes the
2702 // overall construct type-dependent / a dependent type. This is strictly
2703 // best-effort for now; we may fail to match at all for a dependent type
2704 // in some cases if this is set.
2705 bool IgnoreNonTypeDependent;
2706
2707 bool Match;
2708 SourceLocation MatchLoc;
2709
2710 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2711 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2712 Match(false) {}
2713
2714 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2715 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2716 NamedDecl *ND = Params->getParam(Idx: 0);
2717 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(Val: ND)) {
2718 Depth = PD->getDepth();
2719 } else if (NonTypeTemplateParmDecl *PD =
2720 dyn_cast<NonTypeTemplateParmDecl>(Val: ND)) {
2721 Depth = PD->getDepth();
2722 } else {
2723 Depth = cast<TemplateTemplateParmDecl>(Val: ND)->getDepth();
2724 }
2725 }
2726
2727 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2728 if (ParmDepth >= Depth) {
2729 Match = true;
2730 MatchLoc = Loc;
2731 return true;
2732 }
2733 return false;
2734 }
2735
2736 bool TraverseStmt(Stmt *S) override {
2737 // Prune out non-type-dependent expressions if requested. This can
2738 // sometimes result in us failing to find a template parameter reference
2739 // (if a value-dependent expression creates a dependent type), but this
2740 // mode is best-effort only.
2741 if (auto *E = dyn_cast_or_null<Expr>(Val: S))
2742 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2743 return true;
2744 return DynamicRecursiveASTVisitor::TraverseStmt(S);
2745 }
2746
2747 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2748 if (IgnoreNonTypeDependent && !TL.isNull() &&
2749 !TL.getType()->isDependentType())
2750 return true;
2751 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2752 }
2753
2754 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2755 return !Matches(ParmDepth: TL.getTypePtr()->getDepth(), Loc: TL.getNameLoc());
2756 }
2757
2758 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2759 // For a best-effort search, keep looking until we find a location.
2760 return IgnoreNonTypeDependent || !Matches(ParmDepth: T->getDepth());
2761 }
2762
2763 bool TraverseTemplateName(TemplateName N) override {
2764 if (TemplateTemplateParmDecl *PD =
2765 dyn_cast_or_null<TemplateTemplateParmDecl>(Val: N.getAsTemplateDecl()))
2766 if (Matches(ParmDepth: PD->getDepth()))
2767 return false;
2768 return DynamicRecursiveASTVisitor::TraverseTemplateName(Template: N);
2769 }
2770
2771 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2772 if (NonTypeTemplateParmDecl *PD =
2773 dyn_cast<NonTypeTemplateParmDecl>(Val: E->getDecl()))
2774 if (Matches(ParmDepth: PD->getDepth(), Loc: E->getExprLoc()))
2775 return false;
2776 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(S: E);
2777 }
2778
2779 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2780 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2781 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2782 if (Matches(ParmDepth: TTP->getDepth(), Loc: ULE->getExprLoc()))
2783 return false;
2784 }
2785 for (auto &TLoc : ULE->template_arguments())
2786 DynamicRecursiveASTVisitor::TraverseTemplateArgumentLoc(ArgLoc: TLoc);
2787 }
2788 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(S: ULE);
2789 }
2790
2791 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2792 return TraverseType(T: T->getReplacementType());
2793 }
2794
2795 bool VisitSubstTemplateTypeParmPackType(
2796 SubstTemplateTypeParmPackType *T) override {
2797 return TraverseTemplateArgument(Arg: T->getArgumentPack());
2798 }
2799
2800 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2801 bool TraverseQualifier) override {
2802 // An InjectedClassNameType will never have a dependent template name,
2803 // so no need to traverse it.
2804 return TraverseTemplateArguments(
2805 Args: T->getTemplateArgs(Ctx: T->getDecl()->getASTContext()));
2806 }
2807};
2808} // end anonymous namespace
2809
2810/// Determines whether a given type depends on the given parameter
2811/// list.
2812static bool
2813DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2814 if (!Params->size())
2815 return false;
2816
2817 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2818 Checker.TraverseType(T);
2819 return Checker.Match;
2820}
2821
2822// Find the source range corresponding to the named type in the given
2823// nested-name-specifier, if any.
2824static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2825 QualType T,
2826 const CXXScopeSpec &SS) {
2827 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2828 for (;;) {
2829 NestedNameSpecifier NNS = NNSLoc.getNestedNameSpecifier();
2830 if (NNS.getKind() != NestedNameSpecifier::Kind::Type)
2831 break;
2832 if (Context.hasSameUnqualifiedType(T1: T, T2: QualType(NNS.getAsType(), 0)))
2833 return NNSLoc.castAsTypeLoc().getSourceRange();
2834 // FIXME: This will always be empty.
2835 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2836 }
2837
2838 return SourceRange();
2839}
2840
2841TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2842 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2843 TemplateIdAnnotation *TemplateId,
2844 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2845 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2846 IsMemberSpecialization = false;
2847 Invalid = false;
2848
2849 // The sequence of nested types to which we will match up the template
2850 // parameter lists. We first build this list by starting with the type named
2851 // by the nested-name-specifier and walking out until we run out of types.
2852 SmallVector<QualType, 4> NestedTypes;
2853 QualType T;
2854 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2855 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2856 if (CXXRecordDecl *Record =
2857 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: true)))
2858 T = Context.getCanonicalTagType(TD: Record);
2859 else
2860 T = QualType(Qualifier.getAsType(), 0);
2861 }
2862
2863 // If we found an explicit specialization that prevents us from needing
2864 // 'template<>' headers, this will be set to the location of that
2865 // explicit specialization.
2866 SourceLocation ExplicitSpecLoc;
2867
2868 while (!T.isNull()) {
2869 NestedTypes.push_back(Elt: T);
2870
2871 // Retrieve the parent of a record type.
2872 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2873 // If this type is an explicit specialization, we're done.
2874 if (ClassTemplateSpecializationDecl *Spec
2875 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
2876 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Spec) &&
2877 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2878 ExplicitSpecLoc = Spec->getLocation();
2879 break;
2880 }
2881 } else if (Record->getTemplateSpecializationKind()
2882 == TSK_ExplicitSpecialization) {
2883 ExplicitSpecLoc = Record->getLocation();
2884 break;
2885 }
2886
2887 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Record->getParent()))
2888 T = Context.getTypeDeclType(Decl: Parent);
2889 else
2890 T = QualType();
2891 continue;
2892 }
2893
2894 if (const TemplateSpecializationType *TST
2895 = T->getAs<TemplateSpecializationType>()) {
2896 TemplateName Name = TST->getTemplateName();
2897 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2898 // Look one step prior in a dependent template specialization type.
2899 if (NestedNameSpecifier NNS = DTS->getQualifier();
2900 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2901 T = QualType(NNS.getAsType(), 0);
2902 else
2903 T = QualType();
2904 continue;
2905 }
2906 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2907 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Template->getDeclContext()))
2908 T = Context.getTypeDeclType(Decl: Parent);
2909 else
2910 T = QualType();
2911 continue;
2912 }
2913 }
2914
2915 // Look one step prior in a dependent name type.
2916 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2917 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2918 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2919 T = QualType(NNS.getAsType(), 0);
2920 else
2921 T = QualType();
2922 continue;
2923 }
2924
2925 // Retrieve the parent of an enumeration type.
2926 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2927 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2928 // check here.
2929 EnumDecl *Enum = EnumT->getDecl();
2930
2931 // Get to the parent type.
2932 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Enum->getParent()))
2933 T = Context.getCanonicalTypeDeclType(TD: Parent);
2934 else
2935 T = QualType();
2936 continue;
2937 }
2938
2939 T = QualType();
2940 }
2941 // Reverse the nested types list, since we want to traverse from the outermost
2942 // to the innermost while checking template-parameter-lists.
2943 std::reverse(first: NestedTypes.begin(), last: NestedTypes.end());
2944
2945 // C++0x [temp.expl.spec]p17:
2946 // A member or a member template may be nested within many
2947 // enclosing class templates. In an explicit specialization for
2948 // such a member, the member declaration shall be preceded by a
2949 // template<> for each enclosing class template that is
2950 // explicitly specialized.
2951 bool SawNonEmptyTemplateParameterList = false;
2952
2953 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2954 if (SawNonEmptyTemplateParameterList) {
2955 if (!SuppressDiagnostic)
2956 Diag(Loc: DeclLoc, DiagID: diag::err_specialize_member_of_template)
2957 << !Recovery << Range;
2958 Invalid = true;
2959 IsMemberSpecialization = false;
2960 return true;
2961 }
2962
2963 return false;
2964 };
2965
2966 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2967 // Check that we can have an explicit specialization here.
2968 if (CheckExplicitSpecialization(Range, true))
2969 return true;
2970
2971 // We don't have a template header, but we should.
2972 SourceLocation ExpectedTemplateLoc;
2973 if (!ParamLists.empty())
2974 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2975 else
2976 ExpectedTemplateLoc = DeclStartLoc;
2977
2978 if (!SuppressDiagnostic)
2979 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_header)
2980 << Range
2981 << FixItHint::CreateInsertion(InsertionLoc: ExpectedTemplateLoc, Code: "template<> ");
2982 return false;
2983 };
2984
2985 unsigned ParamIdx = 0;
2986 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2987 ++TypeIdx) {
2988 T = NestedTypes[TypeIdx];
2989
2990 // Whether we expect a 'template<>' header.
2991 bool NeedEmptyTemplateHeader = false;
2992
2993 // Whether we expect a template header with parameters.
2994 bool NeedNonemptyTemplateHeader = false;
2995
2996 // For a dependent type, the set of template parameters that we
2997 // expect to see.
2998 TemplateParameterList *ExpectedTemplateParams = nullptr;
2999
3000 // C++0x [temp.expl.spec]p15:
3001 // A member or a member template may be nested within many enclosing
3002 // class templates. In an explicit specialization for such a member, the
3003 // member declaration shall be preceded by a template<> for each
3004 // enclosing class template that is explicitly specialized.
3005 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3006 if (ClassTemplatePartialSpecializationDecl *Partial
3007 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Record)) {
3008 ExpectedTemplateParams = Partial->getTemplateParameters();
3009 NeedNonemptyTemplateHeader = true;
3010 } else if (Record->isDependentType()) {
3011 if (Record->getDescribedClassTemplate()) {
3012 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3013 ->getTemplateParameters();
3014 NeedNonemptyTemplateHeader = true;
3015 }
3016 } else if (ClassTemplateSpecializationDecl *Spec
3017 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
3018 // C++0x [temp.expl.spec]p4:
3019 // Members of an explicitly specialized class template are defined
3020 // in the same manner as members of normal classes, and not using
3021 // the template<> syntax.
3022 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3023 NeedEmptyTemplateHeader = true;
3024 else
3025 continue;
3026 } else if (Record->getTemplateSpecializationKind()) {
3027 if (Record->getTemplateSpecializationKind()
3028 != TSK_ExplicitSpecialization &&
3029 TypeIdx == NumTypes - 1)
3030 IsMemberSpecialization = true;
3031
3032 continue;
3033 }
3034 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3035 TemplateName Name = TST->getTemplateName();
3036 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3037 ExpectedTemplateParams = Template->getTemplateParameters();
3038 NeedNonemptyTemplateHeader = true;
3039 } else if (Name.getAsDeducedTemplateName()) {
3040 // FIXME: We actually could/should check the template arguments here
3041 // against the corresponding template parameter list.
3042 NeedNonemptyTemplateHeader = false;
3043 }
3044 }
3045
3046 // C++ [temp.expl.spec]p16:
3047 // In an explicit specialization declaration for a member of a class
3048 // template or a member template that appears in namespace scope, the
3049 // member template and some of its enclosing class templates may remain
3050 // unspecialized, except that the declaration shall not explicitly
3051 // specialize a class member template if its enclosing class templates
3052 // are not explicitly specialized as well.
3053 if (ParamIdx < ParamLists.size()) {
3054 if (ParamLists[ParamIdx]->size() == 0) {
3055 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3056 false))
3057 return nullptr;
3058 } else
3059 SawNonEmptyTemplateParameterList = true;
3060 }
3061
3062 if (NeedEmptyTemplateHeader) {
3063 // If we're on the last of the types, and we need a 'template<>' header
3064 // here, then it's a member specialization.
3065 if (TypeIdx == NumTypes - 1)
3066 IsMemberSpecialization = true;
3067
3068 if (ParamIdx < ParamLists.size()) {
3069 if (ParamLists[ParamIdx]->size() > 0) {
3070 // The header has template parameters when it shouldn't. Complain.
3071 if (!SuppressDiagnostic)
3072 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3073 DiagID: diag::err_template_param_list_matches_nontemplate)
3074 << T
3075 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3076 ParamLists[ParamIdx]->getRAngleLoc())
3077 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3078 Invalid = true;
3079 return nullptr;
3080 }
3081
3082 // Consume this template header.
3083 ++ParamIdx;
3084 continue;
3085 }
3086
3087 if (!IsFriend)
3088 if (DiagnoseMissingExplicitSpecialization(
3089 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3090 return nullptr;
3091
3092 continue;
3093 }
3094
3095 if (NeedNonemptyTemplateHeader) {
3096 // In friend declarations we can have template-ids which don't
3097 // depend on the corresponding template parameter lists. But
3098 // assume that empty parameter lists are supposed to match this
3099 // template-id.
3100 if (IsFriend && T->isDependentType()) {
3101 if (ParamIdx < ParamLists.size() &&
3102 DependsOnTemplateParameters(T, Params: ParamLists[ParamIdx]))
3103 ExpectedTemplateParams = nullptr;
3104 else
3105 continue;
3106 }
3107
3108 if (ParamIdx < ParamLists.size()) {
3109 // Check the template parameter list, if we can.
3110 if (ExpectedTemplateParams &&
3111 !TemplateParameterListsAreEqual(New: ParamLists[ParamIdx],
3112 Old: ExpectedTemplateParams,
3113 Complain: !SuppressDiagnostic, Kind: TPL_TemplateMatch))
3114 Invalid = true;
3115
3116 if (!Invalid &&
3117 CheckTemplateParameterList(NewParams: ParamLists[ParamIdx], OldParams: nullptr,
3118 TPC: TPC_ClassTemplateMember))
3119 Invalid = true;
3120
3121 ++ParamIdx;
3122 continue;
3123 }
3124
3125 if (!SuppressDiagnostic)
3126 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_template_parameters)
3127 << T
3128 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3129 Invalid = true;
3130 continue;
3131 }
3132 }
3133
3134 // If there were at least as many template-ids as there were template
3135 // parameter lists, then there are no template parameter lists remaining for
3136 // the declaration itself.
3137 if (ParamIdx >= ParamLists.size()) {
3138 if (TemplateId && !IsFriend) {
3139 // We don't have a template header for the declaration itself, but we
3140 // should.
3141 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3142 TemplateId->RAngleLoc));
3143
3144 // Fabricate an empty template parameter list for the invented header.
3145 return TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(),
3146 LAngleLoc: SourceLocation(), Params: {},
3147 RAngleLoc: SourceLocation(), RequiresClause: nullptr);
3148 }
3149
3150 return nullptr;
3151 }
3152
3153 // If there were too many template parameter lists, complain about that now.
3154 if (ParamIdx < ParamLists.size() - 1) {
3155 bool HasAnyExplicitSpecHeader = false;
3156 bool AllExplicitSpecHeaders = true;
3157 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3158 if (ParamLists[I]->size() == 0)
3159 HasAnyExplicitSpecHeader = true;
3160 else
3161 AllExplicitSpecHeaders = false;
3162 }
3163
3164 if (!SuppressDiagnostic)
3165 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3166 DiagID: AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3167 : diag::err_template_spec_extra_headers)
3168 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3169 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3170
3171 // If there was a specialization somewhere, such that 'template<>' is
3172 // not required, and there were any 'template<>' headers, note where the
3173 // specialization occurred.
3174 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3175 !SuppressDiagnostic)
3176 Diag(Loc: ExplicitSpecLoc,
3177 DiagID: diag::note_explicit_template_spec_does_not_need_header)
3178 << NestedTypes.back();
3179
3180 // We have a template parameter list with no corresponding scope, which
3181 // means that the resulting template declaration can't be instantiated
3182 // properly (we'll end up with dependent nodes when we shouldn't).
3183 if (!AllExplicitSpecHeaders)
3184 Invalid = true;
3185 }
3186
3187 // C++ [temp.expl.spec]p16:
3188 // In an explicit specialization declaration for a member of a class
3189 // template or a member template that ap- pears in namespace scope, the
3190 // member template and some of its enclosing class templates may remain
3191 // unspecialized, except that the declaration shall not explicitly
3192 // specialize a class member template if its en- closing class templates
3193 // are not explicitly specialized as well.
3194 if (ParamLists.back()->size() == 0 &&
3195 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3196 false))
3197 return nullptr;
3198
3199 // Return the last template parameter list, which corresponds to the
3200 // entity being declared.
3201 return ParamLists.back();
3202}
3203
3204void Sema::NoteAllFoundTemplates(TemplateName Name) {
3205 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3206 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_declared_here)
3207 << (isa<FunctionTemplateDecl>(Val: Template)
3208 ? 0
3209 : isa<ClassTemplateDecl>(Val: Template)
3210 ? 1
3211 : isa<VarTemplateDecl>(Val: Template)
3212 ? 2
3213 : isa<TypeAliasTemplateDecl>(Val: Template) ? 3 : 4)
3214 << Template->getDeclName();
3215 return;
3216 }
3217
3218 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3219 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3220 IEnd = OST->end();
3221 I != IEnd; ++I)
3222 Diag(Loc: (*I)->getLocation(), DiagID: diag::note_template_declared_here)
3223 << 0 << (*I)->getDeclName();
3224
3225 return;
3226 }
3227}
3228
3229static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword,
3230 TemplateName BaseTemplate,
3231 SourceLocation TemplateLoc,
3232 ArrayRef<TemplateArgument> Ts) {
3233 auto lookUpCommonType = [&](TemplateArgument T1,
3234 TemplateArgument T2) -> QualType {
3235 // Don't bother looking for other specializations if both types are
3236 // builtins - users aren't allowed to specialize for them
3237 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3238 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3239 Ts: {T1, T2});
3240
3241 TemplateArgumentListInfo Args;
3242 Args.addArgument(Loc: TemplateArgumentLoc(
3243 T1, S.Context.getTrivialTypeSourceInfo(T: T1.getAsType())));
3244 Args.addArgument(Loc: TemplateArgumentLoc(
3245 T2, S.Context.getTrivialTypeSourceInfo(T: T2.getAsType())));
3246
3247 EnterExpressionEvaluationContext UnevaluatedContext(
3248 S, Sema::ExpressionEvaluationContext::Unevaluated);
3249 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3250 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3251
3252 QualType BaseTemplateInst = S.CheckTemplateIdType(
3253 Keyword, Template: BaseTemplate, TemplateLoc, TemplateArgs&: Args,
3254 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3255
3256 if (SFINAE.hasErrorOccurred())
3257 return QualType();
3258
3259 return BaseTemplateInst;
3260 };
3261
3262 // Note A: For the common_type trait applied to a template parameter pack T of
3263 // types, the member type shall be either defined or not present as follows:
3264 switch (Ts.size()) {
3265
3266 // If sizeof...(T) is zero, there shall be no member type.
3267 case 0:
3268 return QualType();
3269
3270 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3271 // pack T. The member typedef-name type shall denote the same type, if any, as
3272 // common_type_t<T0, T0>; otherwise there shall be no member type.
3273 case 1:
3274 return lookUpCommonType(Ts[0], Ts[0]);
3275
3276 // If sizeof...(T) is two, let the first and second types constituting T be
3277 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3278 // as decay_t<T1> and decay_t<T2>, respectively.
3279 case 2: {
3280 QualType T1 = Ts[0].getAsType();
3281 QualType T2 = Ts[1].getAsType();
3282 QualType D1 = S.BuiltinDecay(BaseType: T1, Loc: {});
3283 QualType D2 = S.BuiltinDecay(BaseType: T2, Loc: {});
3284
3285 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3286 // the same type, if any, as common_type_t<D1, D2>.
3287 if (!S.Context.hasSameType(T1, T2: D1) || !S.Context.hasSameType(T1: T2, T2: D2))
3288 return lookUpCommonType(D1, D2);
3289
3290 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3291 // denotes a valid type, let C denote that type.
3292 {
3293 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3294 EnterExpressionEvaluationContext UnevaluatedContext(
3295 S, Sema::ExpressionEvaluationContext::Unevaluated);
3296 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3297 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3298
3299 // false
3300 OpaqueValueExpr CondExpr(SourceLocation(), S.Context.BoolTy,
3301 VK_PRValue);
3302 ExprResult Cond = &CondExpr;
3303
3304 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3305 if (ConstRefQual) {
3306 D1.addConst();
3307 D2.addConst();
3308 }
3309
3310 // declval<D1>()
3311 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3312 ExprResult LHS = &LHSExpr;
3313
3314 // declval<D2>()
3315 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3316 ExprResult RHS = &RHSExpr;
3317
3318 ExprValueKind VK = VK_PRValue;
3319 ExprObjectKind OK = OK_Ordinary;
3320
3321 // decltype(false ? declval<D1>() : declval<D2>())
3322 QualType Result =
3323 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc: TemplateLoc);
3324
3325 if (Result.isNull() || SFINAE.hasErrorOccurred())
3326 return QualType();
3327
3328 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3329 return S.BuiltinDecay(BaseType: Result, Loc: TemplateLoc);
3330 };
3331
3332 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3333 return Res;
3334
3335 // Let:
3336 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3337 // COND-RES(X, Y) be
3338 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3339
3340 // C++20 only
3341 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3342 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3343 if (!S.Context.getLangOpts().CPlusPlus20)
3344 return QualType();
3345 return CheckConditionalOperands(true);
3346 }
3347 }
3348
3349 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3350 // denote the first, second, and (pack of) remaining types constituting T. Let
3351 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3352 // a type C, the member typedef-name type shall denote the same type, if any,
3353 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3354 default: {
3355 QualType Result = Ts.front().getAsType();
3356 for (auto T : llvm::drop_begin(RangeOrContainer&: Ts)) {
3357 Result = lookUpCommonType(Result, T.getAsType());
3358 if (Result.isNull())
3359 return QualType();
3360 }
3361 return Result;
3362 }
3363 }
3364}
3365
3366static bool isInVkNamespace(const RecordType *RT) {
3367 DeclContext *DC = RT->getDecl()->getDeclContext();
3368 if (!DC)
3369 return false;
3370
3371 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: DC);
3372 if (!ND)
3373 return false;
3374
3375 return ND->getQualifiedNameAsString() == "hlsl::vk";
3376}
3377
3378static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3379 QualType OperandArg,
3380 SourceLocation Loc) {
3381 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3382 bool Literal = false;
3383 SourceLocation LiteralLoc;
3384 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3385 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3386 assert(SpecDecl);
3387
3388 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3389 QualType ConstantType = LiteralArgs[0].getAsType();
3390 RT = ConstantType->getAsCanonical<RecordType>();
3391 Literal = true;
3392 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3393 }
3394
3395 if (RT && isInVkNamespace(RT) &&
3396 RT->getDecl()->getName() == "integral_constant") {
3397 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3398 assert(SpecDecl);
3399
3400 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3401
3402 QualType ConstantType = ConstantArgs[0].getAsType();
3403 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3404
3405 if (Literal)
3406 return SpirvOperand::createLiteral(Val: Value);
3407 return SpirvOperand::createConstant(ResultType: ConstantType, Val: Value);
3408 } else if (Literal) {
3409 SemaRef.Diag(Loc: LiteralLoc, DiagID: diag::err_hlsl_vk_literal_must_contain_constant);
3410 return SpirvOperand();
3411 }
3412 }
3413 if (SemaRef.RequireCompleteType(Loc, T: OperandArg,
3414 DiagID: diag::err_call_incomplete_argument))
3415 return SpirvOperand();
3416 return SpirvOperand::createType(T: OperandArg);
3417}
3418
3419static QualType checkBuiltinTemplateIdType(
3420 Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD,
3421 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3422 TemplateArgumentListInfo &TemplateArgs) {
3423 ASTContext &Context = SemaRef.getASTContext();
3424
3425 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3426 "Builtin template arguments do not match its parameters");
3427
3428 switch (BTD->getBuiltinTemplateKind()) {
3429 case BTK__make_integer_seq: {
3430 // Specializations of __make_integer_seq<S, T, N> are treated like
3431 // S<T, 0, ..., N-1>.
3432
3433 QualType OrigType = Converted[1].getAsType();
3434 // C++14 [inteseq.intseq]p1:
3435 // T shall be an integer type.
3436 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Ctx: Context)) {
3437 SemaRef.Diag(Loc: TemplateArgs[1].getLocation(),
3438 DiagID: diag::err_integer_sequence_integral_element_type);
3439 return QualType();
3440 }
3441
3442 TemplateArgument NumArgsArg = Converted[2];
3443 if (NumArgsArg.isDependent())
3444 return QualType();
3445
3446 TemplateArgumentListInfo SyntheticTemplateArgs;
3447 // The type argument, wrapped in substitution sugar, gets reused as the
3448 // first template argument in the synthetic template argument list.
3449 SyntheticTemplateArgs.addArgument(
3450 Loc: TemplateArgumentLoc(TemplateArgument(OrigType),
3451 SemaRef.Context.getTrivialTypeSourceInfo(
3452 T: OrigType, Loc: TemplateArgs[1].getLocation())));
3453
3454 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3455 // Expand N into 0 ... N-1.
3456 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3457 I < NumArgs; ++I) {
3458 TemplateArgument TA(Context, I, OrigType);
3459 SyntheticTemplateArgs.addArgument(Loc: SemaRef.getTrivialTemplateArgumentLoc(
3460 Arg: TA, NTTPType: OrigType, Loc: TemplateArgs[2].getLocation()));
3461 }
3462 } else {
3463 // C++14 [inteseq.make]p1:
3464 // If N is negative the program is ill-formed.
3465 SemaRef.Diag(Loc: TemplateArgs[2].getLocation(),
3466 DiagID: diag::err_integer_sequence_negative_length);
3467 return QualType();
3468 }
3469
3470 // The first template argument will be reused as the template decl that
3471 // our synthetic template arguments will be applied to.
3472 return SemaRef.CheckTemplateIdType(Keyword, Template: Converted[0].getAsTemplate(),
3473 TemplateLoc, TemplateArgs&: SyntheticTemplateArgs,
3474 /*Scope=*/nullptr,
3475 /*ForNestedNameSpecifier=*/false);
3476 }
3477
3478 case BTK__type_pack_element: {
3479 // Specializations of
3480 // __type_pack_element<Index, T_1, ..., T_N>
3481 // are treated like T_Index.
3482 assert(Converted.size() == 2 &&
3483 "__type_pack_element should be given an index and a parameter pack");
3484
3485 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3486 if (IndexArg.isDependent() || Ts.isDependent())
3487 return QualType();
3488
3489 llvm::APSInt Index = IndexArg.getAsIntegral();
3490 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3491 "type std::size_t, and hence be non-negative");
3492 // If the Index is out of bounds, the program is ill-formed.
3493 if (Index >= Ts.pack_size()) {
3494 SemaRef.Diag(Loc: TemplateArgs[0].getLocation(),
3495 DiagID: diag::err_type_pack_element_out_of_bounds);
3496 return QualType();
3497 }
3498
3499 // We simply return the type at index `Index`.
3500 int64_t N = Index.getExtValue();
3501 return Ts.getPackAsArray()[N].getAsType();
3502 }
3503
3504 case BTK__builtin_common_type: {
3505 assert(Converted.size() == 4);
3506 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3507 return QualType();
3508
3509 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3510 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3511 if (auto CT = builtinCommonTypeImpl(S&: SemaRef, Keyword, BaseTemplate,
3512 TemplateLoc, Ts);
3513 !CT.isNull()) {
3514 TemplateArgumentListInfo TAs;
3515 TAs.addArgument(Loc: TemplateArgumentLoc(
3516 TemplateArgument(CT), SemaRef.Context.getTrivialTypeSourceInfo(
3517 T: CT, Loc: TemplateArgs[1].getLocation())));
3518 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3519 return SemaRef.CheckTemplateIdType(Keyword, Template: HasTypeMember, TemplateLoc,
3520 TemplateArgs&: TAs, /*Scope=*/nullptr,
3521 /*ForNestedNameSpecifier=*/false);
3522 }
3523 QualType HasNoTypeMember = Converted[2].getAsType();
3524 return HasNoTypeMember;
3525 }
3526
3527 case BTK__hlsl_spirv_type: {
3528 assert(Converted.size() == 4);
3529
3530 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3531 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_hlsl_spirv_only) << BTD;
3532 }
3533
3534 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3535 return QualType();
3536
3537 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3538 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3539 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3540
3541 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3542
3543 llvm::SmallVector<SpirvOperand> Operands;
3544
3545 for (auto &OperandTA : OperandArgs) {
3546 QualType OperandArg = OperandTA.getAsType();
3547 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3548 Loc: TemplateArgs[3].getLocation());
3549 if (!Operand.isValid())
3550 return QualType();
3551 Operands.push_back(Elt: Operand);
3552 }
3553
3554 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3555 }
3556 case BTK__builtin_dedup_pack: {
3557 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3558 "a parameter pack");
3559 TemplateArgument Ts = Converted[0];
3560 // Delay the computation until we can compute the final result. We choose
3561 // not to remove the duplicates upfront before substitution to keep the code
3562 // simple.
3563 if (Ts.isDependent())
3564 return QualType();
3565 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3566 llvm::SmallVector<TemplateArgument> OutArgs;
3567 llvm::SmallDenseSet<QualType> Seen;
3568 // Synthesize a new template argument list, removing duplicates.
3569 for (auto T : Ts.getPackAsArray()) {
3570 assert(T.getKind() == clang::TemplateArgument::Type);
3571 if (!Seen.insert(V: T.getAsType().getCanonicalType()).second)
3572 continue;
3573 OutArgs.push_back(Elt: T);
3574 }
3575 return Context.getSubstBuiltinTemplatePack(
3576 ArgPack: TemplateArgument::CreatePackCopy(Context, Args: OutArgs));
3577 }
3578 }
3579 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3580}
3581
3582/// Determine whether this alias template is "enable_if_t".
3583/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3584static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3585 return AliasTemplate->getName() == "enable_if_t" ||
3586 AliasTemplate->getName() == "__enable_if_t";
3587}
3588
3589/// Collect all of the separable terms in the given condition, which
3590/// might be a conjunction.
3591///
3592/// FIXME: The right answer is to convert the logical expression into
3593/// disjunctive normal form, so we can find the first failed term
3594/// within each possible clause.
3595static void collectConjunctionTerms(Expr *Clause,
3596 SmallVectorImpl<Expr *> &Terms) {
3597 if (auto BinOp = dyn_cast<BinaryOperator>(Val: Clause->IgnoreParenImpCasts())) {
3598 if (BinOp->getOpcode() == BO_LAnd) {
3599 collectConjunctionTerms(Clause: BinOp->getLHS(), Terms);
3600 collectConjunctionTerms(Clause: BinOp->getRHS(), Terms);
3601 return;
3602 }
3603 }
3604
3605 Terms.push_back(Elt: Clause);
3606}
3607
3608// The ranges-v3 library uses an odd pattern of a top-level "||" with
3609// a left-hand side that is value-dependent but never true. Identify
3610// the idiom and ignore that term.
3611static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3612 // Top-level '||'.
3613 auto *BinOp = dyn_cast<BinaryOperator>(Val: Cond->IgnoreParenImpCasts());
3614 if (!BinOp) return Cond;
3615
3616 if (BinOp->getOpcode() != BO_LOr) return Cond;
3617
3618 // With an inner '==' that has a literal on the right-hand side.
3619 Expr *LHS = BinOp->getLHS();
3620 auto *InnerBinOp = dyn_cast<BinaryOperator>(Val: LHS->IgnoreParenImpCasts());
3621 if (!InnerBinOp) return Cond;
3622
3623 if (InnerBinOp->getOpcode() != BO_EQ ||
3624 !isa<IntegerLiteral>(Val: InnerBinOp->getRHS()))
3625 return Cond;
3626
3627 // If the inner binary operation came from a macro expansion named
3628 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3629 // of the '||', which is the real, user-provided condition.
3630 SourceLocation Loc = InnerBinOp->getExprLoc();
3631 if (!Loc.isMacroID()) return Cond;
3632
3633 StringRef MacroName = PP.getImmediateMacroName(Loc);
3634 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3635 return BinOp->getRHS();
3636
3637 return Cond;
3638}
3639
3640namespace {
3641
3642// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3643// within failing boolean expression, such as substituting template parameters
3644// for actual types.
3645class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3646public:
3647 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3648 : Policy(P) {}
3649
3650 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3651 const auto *DR = dyn_cast<DeclRefExpr>(Val: E);
3652 if (DR && DR->getQualifier()) {
3653 // If this is a qualified name, expand the template arguments in nested
3654 // qualifiers.
3655 DR->getQualifier().print(OS, Policy, ResolveTemplateArguments: true);
3656 // Then print the decl itself.
3657 const ValueDecl *VD = DR->getDecl();
3658 OS << VD->getName();
3659 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) {
3660 // This is a template variable, print the expanded template arguments.
3661 printTemplateArgumentList(
3662 OS, Args: IV->getTemplateArgs().asArray(), Policy,
3663 TPL: IV->getSpecializedTemplate()->getTemplateParameters());
3664 }
3665 return true;
3666 }
3667 return false;
3668 }
3669
3670private:
3671 const PrintingPolicy Policy;
3672};
3673
3674} // end anonymous namespace
3675
3676std::pair<Expr *, std::string>
3677Sema::findFailedBooleanCondition(Expr *Cond) {
3678 Cond = lookThroughRangesV3Condition(PP, Cond);
3679
3680 // Separate out all of the terms in a conjunction.
3681 SmallVector<Expr *, 4> Terms;
3682 collectConjunctionTerms(Clause: Cond, Terms);
3683
3684 // Determine which term failed.
3685 Expr *FailedCond = nullptr;
3686 for (Expr *Term : Terms) {
3687 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3688
3689 // Literals are uninteresting.
3690 if (isa<CXXBoolLiteralExpr>(Val: TermAsWritten) ||
3691 isa<IntegerLiteral>(Val: TermAsWritten))
3692 continue;
3693
3694 // The initialization of the parameter from the argument is
3695 // a constant-evaluated context.
3696 EnterExpressionEvaluationContext ConstantEvaluated(
3697 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3698
3699 bool Succeeded;
3700 if (Term->EvaluateAsBooleanCondition(Result&: Succeeded, Ctx: Context) &&
3701 !Succeeded) {
3702 FailedCond = TermAsWritten;
3703 break;
3704 }
3705 }
3706 if (!FailedCond)
3707 FailedCond = Cond->IgnoreParenImpCasts();
3708
3709 std::string Description;
3710 {
3711 llvm::raw_string_ostream Out(Description);
3712 PrintingPolicy Policy = getPrintingPolicy();
3713 Policy.PrintAsCanonical = true;
3714 FailedBooleanConditionPrinterHelper Helper(Policy);
3715 FailedCond->printPretty(OS&: Out, Helper: &Helper, Policy, Indentation: 0, NewlineSymbol: "\n", Context: nullptr);
3716 }
3717 return { FailedCond, Description };
3718}
3719
3720static TemplateName
3721resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope,
3722 const AssumedTemplateStorage *ATN,
3723 SourceLocation NameLoc) {
3724 // We assumed this undeclared identifier to be an (ADL-only) function
3725 // template name, but it was used in a context where a type was required.
3726 // Try to typo-correct it now.
3727 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3728 struct CandidateCallback : CorrectionCandidateCallback {
3729 bool ValidateCandidate(const TypoCorrection &TC) override {
3730 return TC.getCorrectionDecl() &&
3731 getAsTypeTemplateDecl(D: TC.getCorrectionDecl());
3732 }
3733 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3734 return std::make_unique<CandidateCallback>(args&: *this);
3735 }
3736 } FilterCCC;
3737
3738 TypoCorrection Corrected =
3739 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Scope,
3740 /*SS=*/nullptr, CCC&: FilterCCC, Mode: CorrectTypoKind::ErrorRecovery);
3741 if (Corrected && Corrected.getFoundDecl()) {
3742 S.diagnoseTypo(Correction: Corrected, TypoDiag: S.PDiag(DiagID: diag::err_no_template_suggest)
3743 << ATN->getDeclName());
3744 return S.Context.getQualifiedTemplateName(
3745 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3746 Template: TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()));
3747 }
3748
3749 return TemplateName();
3750}
3751
3752QualType Sema::CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
3753 TemplateName Name,
3754 SourceLocation TemplateLoc,
3755 TemplateArgumentListInfo &TemplateArgs,
3756 Scope *Scope, bool ForNestedNameSpecifier) {
3757 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3758
3759 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3760 if (!Template) {
3761 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3762 Template = S->getParameterPack();
3763 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3764 if (DTN->getName().getIdentifier())
3765 // When building a template-id where the template-name is dependent,
3766 // assume the template is a type template. Either our assumption is
3767 // correct, or the code is ill-formed and will be diagnosed when the
3768 // dependent name is substituted.
3769 return Context.getTemplateSpecializationType(Keyword, T: Name,
3770 SpecifiedArgs: TemplateArgs.arguments(),
3771 /*CanonicalArgs=*/{});
3772 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3773 if (TemplateName CorrectedName = ::resolveAssumedTemplateNameAsType(
3774 S&: *this, Scope, ATN, NameLoc: TemplateLoc);
3775 CorrectedName.isNull()) {
3776 Diag(Loc: TemplateLoc, DiagID: diag::err_no_template) << ATN->getDeclName();
3777 return QualType();
3778 } else {
3779 Name = CorrectedName;
3780 Template = Name.getAsTemplateDecl();
3781 }
3782 }
3783 }
3784 if (!Template ||
3785 isa<FunctionTemplateDecl, VarTemplateDecl, ConceptDecl>(Val: Template)) {
3786 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3787 if (ForNestedNameSpecifier)
3788 Diag(Loc: TemplateLoc, DiagID: diag::err_non_type_template_in_nested_name_specifier)
3789 << isa_and_nonnull<VarTemplateDecl>(Val: Template) << Name << R;
3790 else
3791 Diag(Loc: TemplateLoc, DiagID: diag::err_template_id_not_a_type) << Name << R;
3792 NoteAllFoundTemplates(Name);
3793 return QualType();
3794 }
3795
3796 // Check that the template argument list is well-formed for this
3797 // template.
3798 CheckTemplateArgumentInfo CTAI;
3799 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3800 DefaultArgs, /*PartialTemplateArgs=*/false,
3801 CTAI,
3802 /*UpdateArgsWithConversions=*/true))
3803 return QualType();
3804
3805 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3806 // and there are no diagnsotics currently implemented for TemplateDecls,
3807 // so avoid doing it for now.
3808 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Template, /*OdrUse=*/MightBeOdrUse: false);
3809
3810 QualType CanonType;
3811
3812 if (isa<TemplateTemplateParmDecl>(Val: Template)) {
3813 // We might have a substituted template template parameter pack. If so,
3814 // build a template specialization type for it.
3815 } else if (TypeAliasTemplateDecl *AliasTemplate =
3816 dyn_cast<TypeAliasTemplateDecl>(Val: Template)) {
3817
3818 // C++0x [dcl.type.elab]p2:
3819 // If the identifier resolves to a typedef-name or the simple-template-id
3820 // resolves to an alias template specialization, the
3821 // elaborated-type-specifier is ill-formed.
3822 if (Keyword != ElaboratedTypeKeyword::None &&
3823 Keyword != ElaboratedTypeKeyword::Typename) {
3824 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_tag_reference_non_tag)
3825 << AliasTemplate << NonTagKind::TypeAliasTemplate
3826 << KeywordHelpers::getTagTypeKindForKeyword(Keyword);
3827 SemaRef.Diag(Loc: AliasTemplate->getLocation(), DiagID: diag::note_declared_at);
3828 }
3829
3830 // Find the canonical type for this type alias template specialization.
3831 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3832
3833 // Diagnose uses of the pattern of this template.
3834 (void)DiagnoseUseOfDecl(D: Pattern, Locs: TemplateLoc);
3835 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Pattern, /*OdrUse=*/MightBeOdrUse: false);
3836
3837 if (Pattern->isInvalidDecl())
3838 return QualType();
3839
3840 // Only substitute for the innermost template argument list.
3841 MultiLevelTemplateArgumentList TemplateArgLists;
3842 TemplateArgLists.addOuterTemplateArguments(AssociatedDecl: Template, Args: CTAI.SugaredConverted,
3843 /*Final=*/true);
3844 TemplateArgLists.addOuterRetainedLevels(
3845 Num: AliasTemplate->getTemplateParameters()->getDepth());
3846
3847 LocalInstantiationScope Scope(*this);
3848
3849 // FIXME: The TemplateArgs passed here are not used for the context note,
3850 // nor they should, because this note will be pointing to the specialization
3851 // anyway. These arguments are needed for a hack for instantiating lambdas
3852 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3853 // arguments will be used for collating the template arguments needed to
3854 // instantiate the lambda.
3855 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3856 /*Entity=*/AliasTemplate,
3857 /*TemplateArgs=*/CTAI.SugaredConverted);
3858 if (Inst.isInvalid())
3859 return QualType();
3860
3861 std::optional<ContextRAII> SavedContext;
3862 if (!AliasTemplate->getDeclContext()->isFileContext())
3863 SavedContext.emplace(args&: *this, args: AliasTemplate->getDeclContext());
3864
3865 CanonType =
3866 SubstType(T: Pattern->getUnderlyingType(), TemplateArgs: TemplateArgLists,
3867 Loc: AliasTemplate->getLocation(), Entity: AliasTemplate->getDeclName());
3868 if (CanonType.isNull()) {
3869 // If this was enable_if and we failed to find the nested type
3870 // within enable_if in a SFINAE context, dig out the specific
3871 // enable_if condition that failed and present that instead.
3872 if (isEnableIfAliasTemplate(AliasTemplate)) {
3873 if (SFINAETrap *Trap = getSFINAEContext();
3874 TemplateDeductionInfo *DeductionInfo =
3875 Trap ? Trap->getDeductionInfo() : nullptr) {
3876 if (DeductionInfo->hasSFINAEDiagnostic() &&
3877 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3878 diag::err_typename_nested_not_found_enable_if &&
3879 TemplateArgs[0].getArgument().getKind() ==
3880 TemplateArgument::Expression) {
3881 Expr *FailedCond;
3882 std::string FailedDescription;
3883 std::tie(args&: FailedCond, args&: FailedDescription) =
3884 findFailedBooleanCondition(Cond: TemplateArgs[0].getSourceExpression());
3885
3886 // Remove the old SFINAE diagnostic.
3887 PartialDiagnosticAt OldDiag =
3888 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3889 DeductionInfo->takeSFINAEDiagnostic(PD&: OldDiag);
3890
3891 // Add a new SFINAE diagnostic specifying which condition
3892 // failed.
3893 DeductionInfo->addSFINAEDiagnostic(
3894 Loc: OldDiag.first,
3895 PD: PDiag(DiagID: diag::err_typename_nested_not_found_requirement)
3896 << FailedDescription << FailedCond->getSourceRange());
3897 }
3898 }
3899 }
3900
3901 return QualType();
3902 }
3903 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Val: Template)) {
3904 CanonType = checkBuiltinTemplateIdType(
3905 SemaRef&: *this, Keyword, BTD, Converted: CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3906 } else if (Name.isDependent() ||
3907 TemplateSpecializationType::anyDependentTemplateArguments(
3908 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
3909 // This class template specialization is a dependent
3910 // type. Therefore, its canonical type is another class template
3911 // specialization type that contains all of the converted
3912 // arguments in canonical form. This ensures that, e.g., A<T> and
3913 // A<T, T> have identical types when A is declared as:
3914 //
3915 // template<typename T, typename U = T> struct A;
3916 CanonType = Context.getCanonicalTemplateSpecializationType(
3917 Keyword: ElaboratedTypeKeyword::None,
3918 T: Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3919 CanonicalArgs: CTAI.CanonicalConverted);
3920 assert(CanonType->isCanonicalUnqualified());
3921
3922 // This might work out to be a current instantiation, in which
3923 // case the canonical type needs to be the InjectedClassNameType.
3924 //
3925 // TODO: in theory this could be a simple hashtable lookup; most
3926 // changes to CurContext don't change the set of current
3927 // instantiations.
3928 if (isa<ClassTemplateDecl>(Val: Template)) {
3929 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3930 // If we get out to a namespace, we're done.
3931 if (Ctx->isFileContext()) break;
3932
3933 // If this isn't a record, keep looking.
3934 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Ctx);
3935 if (!Record) continue;
3936
3937 // Look for one of the two cases with InjectedClassNameTypes
3938 // and check whether it's the same template.
3939 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Record) &&
3940 !Record->getDescribedClassTemplate())
3941 continue;
3942
3943 // Fetch the injected class name type and check whether its
3944 // injected type is equal to the type we just built.
3945 CanQualType ICNT = Context.getCanonicalTagType(TD: Record);
3946 CanQualType Injected =
3947 Record->getCanonicalTemplateSpecializationType(Ctx: Context);
3948
3949 if (CanonType != Injected)
3950 continue;
3951
3952 (void)DiagnoseUseOfDecl(D: Record, Locs: TemplateLoc);
3953 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Record, /*OdrUse=*/MightBeOdrUse: false);
3954
3955 // If so, the canonical type of this TST is the injected
3956 // class name type of the record we just found.
3957 CanonType = ICNT;
3958 break;
3959 }
3960 }
3961 } else if (ClassTemplateDecl *ClassTemplate =
3962 dyn_cast<ClassTemplateDecl>(Val: Template)) {
3963 // Find the class template specialization declaration that
3964 // corresponds to these arguments.
3965 void *InsertPos = nullptr;
3966 ClassTemplateSpecializationDecl *Decl =
3967 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
3968 if (!Decl) {
3969 // This is the first time we have referenced this class template
3970 // specialization. Create the canonical declaration and add it to
3971 // the set of specializations.
3972 Decl = ClassTemplateSpecializationDecl::Create(
3973 Context, TK: ClassTemplate->getTemplatedDecl()->getTagKind(),
3974 DC: ClassTemplate->getDeclContext(),
3975 StartLoc: ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3976 IdLoc: ClassTemplate->getLocation(), SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted,
3977 StrictPackMatch: CTAI.StrictPackMatch, PrevDecl: nullptr);
3978 ClassTemplate->AddSpecialization(D: Decl, InsertPos);
3979 if (ClassTemplate->isOutOfLine())
3980 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3981 }
3982
3983 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3984 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3985 NonSFINAEContext _(*this);
3986 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3987 if (!Inst.isInvalid()) {
3988 MultiLevelTemplateArgumentList TemplateArgLists(Template,
3989 CTAI.CanonicalConverted,
3990 /*Final=*/false);
3991 InstantiateAttrsForDecl(TemplateArgs: TemplateArgLists,
3992 Pattern: ClassTemplate->getTemplatedDecl(), Inst: Decl);
3993 }
3994 }
3995
3996 // Diagnose uses of this specialization.
3997 (void)DiagnoseUseOfDecl(D: Decl, Locs: TemplateLoc);
3998 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Decl, /*OdrUse=*/MightBeOdrUse: false);
3999
4000 CanonType = Context.getCanonicalTagType(TD: Decl);
4001 assert(isa<RecordType>(CanonType) &&
4002 "type of non-dependent specialization is not a RecordType");
4003 } else {
4004 llvm_unreachable("Unhandled template kind");
4005 }
4006
4007 // Build the fully-sugared type for this class template
4008 // specialization, which refers back to the class template
4009 // specialization we created or found.
4010 return Context.getTemplateSpecializationType(
4011 Keyword, T: Name, SpecifiedArgs: TemplateArgs.arguments(), CanonicalArgs: CTAI.CanonicalConverted,
4012 Canon: CanonType);
4013}
4014
4015void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
4016 TemplateNameKind &TNK,
4017 SourceLocation NameLoc,
4018 IdentifierInfo *&II) {
4019 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4020
4021 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4022 assert(ATN && "not an assumed template name");
4023 II = ATN->getDeclName().getAsIdentifierInfo();
4024
4025 if (TemplateName Name =
4026 ::resolveAssumedTemplateNameAsType(S&: *this, Scope: S, ATN, NameLoc);
4027 !Name.isNull()) {
4028 // Resolved to a type template name.
4029 ParsedName = TemplateTy::make(P: Name);
4030 TNK = TNK_Type_template;
4031 }
4032}
4033
4034TypeResult Sema::ActOnTemplateIdType(
4035 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4036 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4037 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4038 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4039 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4040 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4041 ImplicitTypenameContext AllowImplicitTypename) {
4042 if (SS.isInvalid())
4043 return true;
4044
4045 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4046 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4047
4048 // C++ [temp.res]p3:
4049 // A qualified-id that refers to a type and in which the
4050 // nested-name-specifier depends on a template-parameter (14.6.2)
4051 // shall be prefixed by the keyword typename to indicate that the
4052 // qualified-id denotes a type, forming an
4053 // elaborated-type-specifier (7.1.5.3).
4054 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4055 // C++2a relaxes some of those restrictions in [temp.res]p5.
4056 QualType DNT = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
4057 NNS: SS.getScopeRep(), Name: TemplateII);
4058 NestedNameSpecifier NNS(DNT.getTypePtr());
4059 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4060 auto DB = DiagCompat(Loc: SS.getBeginLoc(), CompatDiagId: diag_compat::implicit_typename)
4061 << NNS;
4062 if (!getLangOpts().CPlusPlus20)
4063 DB << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "typename ");
4064 } else
4065 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_typename_missing_template) << NNS;
4066
4067 // FIXME: This is not quite correct recovery as we don't transform SS
4068 // into the corresponding dependent form (and we don't diagnose missing
4069 // 'template' keywords within SS as a result).
4070 return ActOnTypenameType(S: nullptr, TypenameLoc: SourceLocation(), SS, TemplateLoc: TemplateKWLoc,
4071 TemplateName: TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4072 TemplateArgs: TemplateArgsIn, RAngleLoc);
4073 }
4074
4075 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4076 // it's not actually allowed to be used as a type in most cases. Because
4077 // we annotate it before we know whether it's valid, we have to check for
4078 // this case here.
4079 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
4080 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4081 Diag(Loc: TemplateIILoc,
4082 DiagID: TemplateKWLoc.isInvalid()
4083 ? diag::err_out_of_line_qualified_id_type_names_constructor
4084 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4085 << TemplateII << 0 /*injected-class-name used as template name*/
4086 << 1 /*if any keyword was present, it was 'template'*/;
4087 }
4088 }
4089
4090 // Translate the parser's template argument list in our AST format.
4091 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4092 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4093
4094 QualType SpecTy = CheckTemplateIdType(
4095 Keyword: ElaboratedKeyword, Name: TemplateD.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
4096 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4097 if (SpecTy.isNull())
4098 return true;
4099
4100 // Build type-source information.
4101 TypeLocBuilder TLB;
4102 TLB.push<TemplateSpecializationTypeLoc>(T: SpecTy).set(
4103 ElaboratedKeywordLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
4104 NameLoc: TemplateIILoc, TAL: TemplateArgs);
4105 return CreateParsedType(T: SpecTy, TInfo: TLB.getTypeSourceInfo(Context, T: SpecTy));
4106}
4107
4108TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4109 TypeSpecifierType TagSpec,
4110 SourceLocation TagLoc,
4111 CXXScopeSpec &SS,
4112 SourceLocation TemplateKWLoc,
4113 TemplateTy TemplateD,
4114 SourceLocation TemplateLoc,
4115 SourceLocation LAngleLoc,
4116 ASTTemplateArgsPtr TemplateArgsIn,
4117 SourceLocation RAngleLoc) {
4118 if (SS.isInvalid())
4119 return TypeResult(true);
4120
4121 // Translate the parser's template argument list in our AST format.
4122 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4123 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4124
4125 // Determine the tag kind
4126 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
4127 ElaboratedTypeKeyword Keyword
4128 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
4129
4130 QualType Result =
4131 CheckTemplateIdType(Keyword, Name: TemplateD.get(), TemplateLoc, TemplateArgs,
4132 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4133 if (Result.isNull())
4134 return TypeResult(true);
4135
4136 // Check the tag kind
4137 if (const RecordType *RT = Result->getAs<RecordType>()) {
4138 RecordDecl *D = RT->getDecl();
4139
4140 IdentifierInfo *Id = D->getIdentifier();
4141 assert(Id && "templated class must have an identifier");
4142
4143 if (!isAcceptableTagRedeclaration(Previous: D, NewTag: TagKind, isDefinition: TUK == TagUseKind::Definition,
4144 NewTagLoc: TagLoc, Name: Id)) {
4145 Diag(Loc: TagLoc, DiagID: diag::err_use_with_wrong_tag)
4146 << Result
4147 << FixItHint::CreateReplacement(RemoveRange: SourceRange(TagLoc), Code: D->getKindName());
4148 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_use);
4149 }
4150 }
4151
4152 // Provide source-location information for the template specialization.
4153 TypeLocBuilder TLB;
4154 TLB.push<TemplateSpecializationTypeLoc>(T: Result).set(
4155 ElaboratedKeywordLoc: TagLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc, NameLoc: TemplateLoc,
4156 TAL: TemplateArgs);
4157 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
4158}
4159
4160static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4161 NamedDecl *PrevDecl,
4162 SourceLocation Loc,
4163 bool IsPartialSpecialization);
4164
4165static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4166
4167static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg,
4168 unsigned Depth,
4169 unsigned Index) {
4170 switch (Arg.getKind()) {
4171 case TemplateArgument::Null:
4172 case TemplateArgument::NullPtr:
4173 case TemplateArgument::Integral:
4174 case TemplateArgument::Declaration:
4175 case TemplateArgument::StructuralValue:
4176 case TemplateArgument::Pack:
4177 case TemplateArgument::TemplateExpansion:
4178 return false;
4179
4180 case TemplateArgument::Type: {
4181 QualType Type = Arg.getAsType();
4182 const TemplateTypeParmType *TPT =
4183 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4184 return TPT && !Type.hasQualifiers() &&
4185 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4186 }
4187
4188 case TemplateArgument::Expression: {
4189 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg.getAsExpr());
4190 if (!DRE || !DRE->getDecl())
4191 return false;
4192 const NonTypeTemplateParmDecl *NTTP =
4193 dyn_cast<NonTypeTemplateParmDecl>(Val: DRE->getDecl());
4194 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4195 }
4196
4197 case TemplateArgument::Template:
4198 const TemplateTemplateParmDecl *TTP =
4199 dyn_cast_or_null<TemplateTemplateParmDecl>(
4200 Val: Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4201 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4202 }
4203 llvm_unreachable("unexpected kind of template argument");
4204}
4205
4206static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4207 TemplateParameterList *SpecParams,
4208 ArrayRef<TemplateArgument> Args) {
4209 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4210 return false;
4211
4212 unsigned Depth = Params->getDepth();
4213
4214 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4215 TemplateArgument Arg = Args[I];
4216
4217 // If the parameter is a pack expansion, the argument must be a pack
4218 // whose only element is a pack expansion.
4219 if (Params->getParam(Idx: I)->isParameterPack()) {
4220 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4221 !Arg.pack_begin()->isPackExpansion())
4222 return false;
4223 Arg = Arg.pack_begin()->getPackExpansionPattern();
4224 }
4225
4226 if (!isTemplateArgumentTemplateParameter(Arg, Depth, Index: I))
4227 return false;
4228
4229 // For NTTPs further specialization is allowed via deduced types, so
4230 // we need to make sure to only reject here if primary template and
4231 // specialization use the same type for the NTTP.
4232 if (auto *SpecNTTP =
4233 dyn_cast<NonTypeTemplateParmDecl>(Val: SpecParams->getParam(Idx: I))) {
4234 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: I));
4235 if (!NTTP || NTTP->getType().getCanonicalType() !=
4236 SpecNTTP->getType().getCanonicalType())
4237 return false;
4238 }
4239 }
4240
4241 return true;
4242}
4243
4244template<typename PartialSpecDecl>
4245static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4246 if (Partial->getDeclContext()->isDependentContext())
4247 return;
4248
4249 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4250 // for non-substitution-failure issues?
4251 TemplateDeductionInfo Info(Partial->getLocation());
4252 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4253 return;
4254
4255 auto *Template = Partial->getSpecializedTemplate();
4256 S.Diag(Partial->getLocation(),
4257 diag::ext_partial_spec_not_more_specialized_than_primary)
4258 << isa<VarTemplateDecl>(Template);
4259
4260 if (Info.hasSFINAEDiagnostic()) {
4261 PartialDiagnosticAt Diag = {SourceLocation(),
4262 PartialDiagnostic::NullDiagnostic()};
4263 Info.takeSFINAEDiagnostic(PD&: Diag);
4264 SmallString<128> SFINAEArgString;
4265 Diag.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
4266 S.Diag(Loc: Diag.first,
4267 DiagID: diag::note_partial_spec_not_more_specialized_than_primary)
4268 << SFINAEArgString;
4269 }
4270
4271 S.NoteTemplateLocation(Decl: *Template);
4272 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4273 Template->getAssociatedConstraints(TemplateAC);
4274 Partial->getAssociatedConstraints(PartialAC);
4275 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Partial, AC1: PartialAC, D2: Template,
4276 AC2: TemplateAC);
4277}
4278
4279static void
4280noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4281 const llvm::SmallBitVector &DeducibleParams) {
4282 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4283 if (!DeducibleParams[I]) {
4284 NamedDecl *Param = TemplateParams->getParam(Idx: I);
4285 if (Param->getDeclName())
4286 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4287 << Param->getDeclName();
4288 else
4289 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4290 << "(anonymous)";
4291 }
4292 }
4293}
4294
4295
4296template<typename PartialSpecDecl>
4297static void checkTemplatePartialSpecialization(Sema &S,
4298 PartialSpecDecl *Partial) {
4299 // C++1z [temp.class.spec]p8: (DR1495)
4300 // - The specialization shall be more specialized than the primary
4301 // template (14.5.5.2).
4302 checkMoreSpecializedThanPrimary(S, Partial);
4303
4304 // C++ [temp.class.spec]p8: (DR1315)
4305 // - Each template-parameter shall appear at least once in the
4306 // template-id outside a non-deduced context.
4307 // C++1z [temp.class.spec.match]p3 (P0127R2)
4308 // If the template arguments of a partial specialization cannot be
4309 // deduced because of the structure of its template-parameter-list
4310 // and the template-id, the program is ill-formed.
4311 auto *TemplateParams = Partial->getTemplateParameters();
4312 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4313 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4314 TemplateParams->getDepth(), DeducibleParams);
4315
4316 if (!DeducibleParams.all()) {
4317 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4318 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4319 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4320 << (NumNonDeducible > 1)
4321 << SourceRange(Partial->getLocation(),
4322 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4323 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4324 }
4325}
4326
4327void Sema::CheckTemplatePartialSpecialization(
4328 ClassTemplatePartialSpecializationDecl *Partial) {
4329 checkTemplatePartialSpecialization(S&: *this, Partial);
4330}
4331
4332void Sema::CheckTemplatePartialSpecialization(
4333 VarTemplatePartialSpecializationDecl *Partial) {
4334 checkTemplatePartialSpecialization(S&: *this, Partial);
4335}
4336
4337void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4338 // C++1z [temp.param]p11:
4339 // A template parameter of a deduction guide template that does not have a
4340 // default-argument shall be deducible from the parameter-type-list of the
4341 // deduction guide template.
4342 auto *TemplateParams = TD->getTemplateParameters();
4343 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4344 MarkDeducedTemplateParameters(FunctionTemplate: TD, Deduced&: DeducibleParams);
4345 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4346 // A parameter pack is deducible (to an empty pack).
4347 auto *Param = TemplateParams->getParam(Idx: I);
4348 if (Param->isParameterPack() || hasVisibleDefaultArgument(D: Param))
4349 DeducibleParams[I] = true;
4350 }
4351
4352 if (!DeducibleParams.all()) {
4353 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4354 Diag(Loc: TD->getLocation(), DiagID: diag::err_deduction_guide_template_not_deducible)
4355 << (NumNonDeducible > 1);
4356 noteNonDeducibleParameters(S&: *this, TemplateParams, DeducibleParams);
4357 }
4358}
4359
4360DeclResult Sema::ActOnVarTemplateSpecialization(
4361 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
4362 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4363 StorageClass SC, bool IsPartialSpecialization) {
4364 // D must be variable template id.
4365 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4366 "Variable template specialization is declared with a template id.");
4367
4368 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4369 TemplateArgumentListInfo TemplateArgs =
4370 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TemplateId);
4371 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4372 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4373 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4374
4375 TemplateName Name = TemplateId->Template.get();
4376
4377 // The template-id must name a variable template.
4378 VarTemplateDecl *VarTemplate =
4379 dyn_cast_or_null<VarTemplateDecl>(Val: Name.getAsTemplateDecl());
4380 if (!VarTemplate) {
4381 NamedDecl *FnTemplate;
4382 if (auto *OTS = Name.getAsOverloadedTemplate())
4383 FnTemplate = *OTS->begin();
4384 else
4385 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Val: Name.getAsTemplateDecl());
4386 if (FnTemplate)
4387 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template_but_method)
4388 << FnTemplate->getDeclName();
4389 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template)
4390 << IsPartialSpecialization;
4391 }
4392
4393 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4394 auto Message = DSA->getMessage();
4395 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
4396 << VarTemplate << !Message.empty() << Message;
4397 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
4398 }
4399
4400 // Check for unexpanded parameter packs in any of the template arguments.
4401 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4402 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
4403 UPPC: IsPartialSpecialization
4404 ? UPPC_PartialSpecialization
4405 : UPPC_ExplicitSpecialization))
4406 return true;
4407
4408 // Check that the template argument list is well-formed for this
4409 // template.
4410 CheckTemplateArgumentInfo CTAI;
4411 if (CheckTemplateArgumentList(Template: VarTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
4412 /*DefaultArgs=*/{},
4413 /*PartialTemplateArgs=*/false, CTAI,
4414 /*UpdateArgsWithConversions=*/true))
4415 return true;
4416
4417 // Find the variable template (partial) specialization declaration that
4418 // corresponds to these arguments.
4419 if (IsPartialSpecialization) {
4420 if (CheckTemplatePartialSpecializationArgs(Loc: TemplateNameLoc, PrimaryTemplate: VarTemplate,
4421 NumExplicitArgs: TemplateArgs.size(),
4422 Args: CTAI.CanonicalConverted))
4423 return true;
4424
4425 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4426 // we also do them during instantiation.
4427 if (!Name.isDependent() &&
4428 !TemplateSpecializationType::anyDependentTemplateArguments(
4429 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4430 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
4431 << VarTemplate->getDeclName();
4432 IsPartialSpecialization = false;
4433 }
4434
4435 if (isSameAsPrimaryTemplate(Params: VarTemplate->getTemplateParameters(),
4436 SpecParams: TemplateParams, Args: CTAI.CanonicalConverted) &&
4437 (!Context.getLangOpts().CPlusPlus20 ||
4438 !TemplateParams->hasAssociatedConstraints())) {
4439 // C++ [temp.class.spec]p9b3:
4440 //
4441 // -- The argument list of the specialization shall not be identical
4442 // to the implicit argument list of the primary template.
4443 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
4444 << /*variable template*/ 1
4445 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4446 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
4447 // FIXME: Recover from this by treating the declaration as a
4448 // redeclaration of the primary template.
4449 return true;
4450 }
4451 }
4452
4453 void *InsertPos = nullptr;
4454 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4455
4456 if (IsPartialSpecialization)
4457 PrevDecl = VarTemplate->findPartialSpecialization(
4458 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
4459 else
4460 PrevDecl =
4461 VarTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
4462
4463 VarTemplateSpecializationDecl *Specialization = nullptr;
4464
4465 // Check whether we can declare a variable template specialization in
4466 // the current scope.
4467 if (CheckTemplateSpecializationScope(S&: *this, Specialized: VarTemplate, PrevDecl,
4468 Loc: TemplateNameLoc,
4469 IsPartialSpecialization))
4470 return true;
4471
4472 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4473 // Since the only prior variable template specialization with these
4474 // arguments was referenced but not declared, reuse that
4475 // declaration node as our own, updating its source location and
4476 // the list of outer template parameters to reflect our new declaration.
4477 Specialization = PrevDecl;
4478 Specialization->setLocation(TemplateNameLoc);
4479 PrevDecl = nullptr;
4480 } else if (IsPartialSpecialization) {
4481 // Create a new class template partial specialization declaration node.
4482 VarTemplatePartialSpecializationDecl *PrevPartial =
4483 cast_or_null<VarTemplatePartialSpecializationDecl>(Val: PrevDecl);
4484 VarTemplatePartialSpecializationDecl *Partial =
4485 VarTemplatePartialSpecializationDecl::Create(
4486 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc,
4487 IdLoc: TemplateNameLoc, Params: TemplateParams, SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI,
4488 S: SC, Args: CTAI.CanonicalConverted);
4489 Partial->setTemplateArgsAsWritten(TemplateArgs);
4490
4491 if (!PrevPartial)
4492 VarTemplate->AddPartialSpecialization(D: Partial, InsertPos);
4493 Specialization = Partial;
4494
4495 CheckTemplatePartialSpecialization(Partial);
4496 } else {
4497 // Create a new class template specialization declaration node for
4498 // this explicit specialization or friend declaration.
4499 Specialization = VarTemplateSpecializationDecl::Create(
4500 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc, IdLoc: TemplateNameLoc,
4501 SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI, S: SC, Args: CTAI.CanonicalConverted);
4502 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4503
4504 if (!PrevDecl)
4505 VarTemplate->AddSpecialization(D: Specialization, InsertPos);
4506 }
4507
4508 // C++ [temp.expl.spec]p6:
4509 // If a template, a member template or the member of a class template is
4510 // explicitly specialized then that specialization shall be declared
4511 // before the first use of that specialization that would cause an implicit
4512 // instantiation to take place, in every translation unit in which such a
4513 // use occurs; no diagnostic is required.
4514 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4515 bool Okay = false;
4516 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4517 // Is there any previous explicit specialization declaration?
4518 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
4519 Okay = true;
4520 break;
4521 }
4522 }
4523
4524 if (!Okay) {
4525 SourceRange Range(TemplateNameLoc, RAngleLoc);
4526 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
4527 << Name << Range;
4528
4529 Diag(Loc: PrevDecl->getPointOfInstantiation(),
4530 DiagID: diag::note_instantiation_required_here)
4531 << (PrevDecl->getTemplateSpecializationKind() !=
4532 TSK_ImplicitInstantiation);
4533 return true;
4534 }
4535 }
4536
4537 Specialization->setLexicalDeclContext(CurContext);
4538
4539 // Add the specialization into its lexical context, so that it can
4540 // be seen when iterating through the list of declarations in that
4541 // context. However, specializations are not found by name lookup.
4542 CurContext->addDecl(D: Specialization);
4543
4544 // Note that this is an explicit specialization.
4545 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4546
4547 Previous.clear();
4548 if (PrevDecl)
4549 Previous.addDecl(D: PrevDecl);
4550 else if (Specialization->isStaticDataMember() &&
4551 Specialization->isOutOfLine())
4552 Specialization->setAccess(VarTemplate->getAccess());
4553
4554 return Specialization;
4555}
4556
4557namespace {
4558/// A partial specialization whose template arguments have matched
4559/// a given template-id.
4560struct PartialSpecMatchResult {
4561 VarTemplatePartialSpecializationDecl *Partial;
4562 TemplateArgumentList *Args;
4563};
4564
4565// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4566// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4567static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4568 if (Var->getName() != "format_kind" ||
4569 !Var->getDeclContext()->isStdNamespace())
4570 return false;
4571
4572 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4573 // release in which users can access std::format_kind.
4574 // We can use 20250520 as the final date, see the following commits.
4575 // GCC releases/gcc-15 branch:
4576 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4577 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4578 // GCC master branch:
4579 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4580 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4581 return PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2025'05'20);
4582}
4583} // end anonymous namespace
4584
4585DeclResult
4586Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4587 SourceLocation TemplateNameLoc,
4588 const TemplateArgumentListInfo &TemplateArgs,
4589 bool SetWrittenArgs) {
4590 assert(Template && "A variable template id without template?");
4591
4592 // Check that the template argument list is well-formed for this template.
4593 CheckTemplateArgumentInfo CTAI;
4594 if (CheckTemplateArgumentList(
4595 Template, TemplateLoc: TemplateNameLoc,
4596 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4597 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4598 /*UpdateArgsWithConversions=*/true))
4599 return true;
4600
4601 // Produce a placeholder value if the specialization is dependent.
4602 if (Template->getDeclContext()->isDependentContext() ||
4603 TemplateSpecializationType::anyDependentTemplateArguments(
4604 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4605 if (ParsingInitForAutoVars.empty())
4606 return DeclResult();
4607
4608 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4609 const TemplateArgument &Arg2) {
4610 return Context.isSameTemplateArgument(Arg1, Arg2);
4611 };
4612
4613 if (VarDecl *Var = Template->getTemplatedDecl();
4614 ParsingInitForAutoVars.count(Ptr: Var) &&
4615 // See comments on this function definition
4616 !IsLibstdcxxStdFormatKind(PP, Var) &&
4617 llvm::equal(
4618 LRange&: CTAI.CanonicalConverted,
4619 RRange: Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4620 P: IsSameTemplateArg)) {
4621 Diag(Loc: TemplateNameLoc,
4622 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4623 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4624 return true;
4625 }
4626
4627 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4628 Template->getPartialSpecializations(PS&: PartialSpecs);
4629 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4630 if (ParsingInitForAutoVars.count(Ptr: Partial) &&
4631 llvm::equal(LRange&: CTAI.CanonicalConverted,
4632 RRange: Partial->getTemplateArgs().asArray(),
4633 P: IsSameTemplateArg)) {
4634 Diag(Loc: TemplateNameLoc,
4635 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4636 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4637 << Partial->getType();
4638 return true;
4639 }
4640
4641 return DeclResult();
4642 }
4643
4644 // Find the variable template specialization declaration that
4645 // corresponds to these arguments.
4646 void *InsertPos = nullptr;
4647 if (VarTemplateSpecializationDecl *Spec =
4648 Template->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos)) {
4649 checkSpecializationReachability(Loc: TemplateNameLoc, Spec);
4650 if (Spec->getType()->isUndeducedType()) {
4651 if (ParsingInitForAutoVars.count(Ptr: Spec))
4652 Diag(Loc: TemplateNameLoc,
4653 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4654 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4655 << Spec->getType();
4656 else
4657 // We are substituting the initializer of this variable template
4658 // specialization.
4659 Diag(Loc: TemplateNameLoc, DiagID: diag::err_var_template_spec_type_depends_on_self)
4660 << Spec << Spec->getType();
4661
4662 return true;
4663 }
4664 // If we already have a variable template specialization, return it.
4665 return Spec;
4666 }
4667
4668 // This is the first time we have referenced this variable template
4669 // specialization. Create the canonical declaration and add it to
4670 // the set of specializations, based on the closest partial specialization
4671 // that it represents. That is,
4672 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4673 const TemplateArgumentList *PartialSpecArgs = nullptr;
4674 bool AmbiguousPartialSpec = false;
4675 typedef PartialSpecMatchResult MatchResult;
4676 SmallVector<MatchResult, 4> Matched;
4677 SourceLocation PointOfInstantiation = TemplateNameLoc;
4678 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4679 /*ForTakingAddress=*/false);
4680
4681 // 1. Attempt to find the closest partial specialization that this
4682 // specializes, if any.
4683 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4684 // Perhaps better after unification of DeduceTemplateArguments() and
4685 // getMoreSpecializedPartialSpecialization().
4686 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4687 Template->getPartialSpecializations(PS&: PartialSpecs);
4688
4689 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4690 // C++ [temp.spec.partial.member]p2:
4691 // If the primary member template is explicitly specialized for a given
4692 // (implicit) specialization of the enclosing class template, the partial
4693 // specializations of the member template are ignored for this
4694 // specialization of the enclosing class template. If a partial
4695 // specialization of the member template is explicitly specialized for a
4696 // given (implicit) specialization of the enclosing class template, the
4697 // primary member template and its other partial specializations are still
4698 // considered for this specialization of the enclosing class template.
4699 if (Template->isMemberSpecialization() &&
4700 !Partial->isMemberSpecialization())
4701 continue;
4702
4703 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4704
4705 if (TemplateDeductionResult Result =
4706 DeduceTemplateArguments(Partial, TemplateArgs: CTAI.SugaredConverted, Info);
4707 Result != TemplateDeductionResult::Success) {
4708 // Store the failed-deduction information for use in diagnostics, later.
4709 // TODO: Actually use the failed-deduction info?
4710 FailedCandidates.addCandidate().set(
4711 Found: DeclAccessPair::make(D: Template, AS: AS_public), Spec: Partial,
4712 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
4713 (void)Result;
4714 } else {
4715 Matched.push_back(Elt: PartialSpecMatchResult());
4716 Matched.back().Partial = Partial;
4717 Matched.back().Args = Info.takeSugared();
4718 }
4719 }
4720
4721 if (Matched.size() >= 1) {
4722 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4723 if (Matched.size() == 1) {
4724 // -- If exactly one matching specialization is found, the
4725 // instantiation is generated from that specialization.
4726 // We don't need to do anything for this.
4727 } else {
4728 // -- If more than one matching specialization is found, the
4729 // partial order rules (14.5.4.2) are used to determine
4730 // whether one of the specializations is more specialized
4731 // than the others. If none of the specializations is more
4732 // specialized than all of the other matching
4733 // specializations, then the use of the variable template is
4734 // ambiguous and the program is ill-formed.
4735 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4736 PEnd = Matched.end();
4737 P != PEnd; ++P) {
4738 if (getMoreSpecializedPartialSpecialization(PS1: P->Partial, PS2: Best->Partial,
4739 Loc: PointOfInstantiation) ==
4740 P->Partial)
4741 Best = P;
4742 }
4743
4744 // Determine if the best partial specialization is more specialized than
4745 // the others.
4746 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4747 PEnd = Matched.end();
4748 P != PEnd; ++P) {
4749 if (P != Best && getMoreSpecializedPartialSpecialization(
4750 PS1: P->Partial, PS2: Best->Partial,
4751 Loc: PointOfInstantiation) != Best->Partial) {
4752 AmbiguousPartialSpec = true;
4753 break;
4754 }
4755 }
4756 }
4757
4758 // Instantiate using the best variable template partial specialization.
4759 InstantiationPattern = Best->Partial;
4760 PartialSpecArgs = Best->Args;
4761 } else {
4762 // -- If no match is found, the instantiation is generated
4763 // from the primary template.
4764 // InstantiationPattern = Template->getTemplatedDecl();
4765 }
4766
4767 // 2. Create the canonical declaration.
4768 // Note that we do not instantiate a definition until we see an odr-use
4769 // in DoMarkVarDeclReferenced().
4770 // FIXME: LateAttrs et al.?
4771 if (AmbiguousPartialSpec) {
4772 // Partial ordering did not produce a clear winner. Complain.
4773 Diag(Loc: PointOfInstantiation, DiagID: diag::err_partial_spec_ordering_ambiguous)
4774 << Template;
4775 // Print the matching partial specializations.
4776 for (MatchResult P : Matched)
4777 Diag(Loc: P.Partial->getLocation(), DiagID: diag::note_partial_spec_match)
4778 << getTemplateArgumentBindingsText(Params: P.Partial->getTemplateParameters(),
4779 Args: *P.Args);
4780 return true;
4781 }
4782
4783 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4784 VarTemplate: Template, FromVar: InstantiationPattern, PartialSpecArgs, Converted&: CTAI.CanonicalConverted,
4785 PointOfInstantiation: TemplateNameLoc /*, LateAttrs, StartingScope*/);
4786 if (!Decl)
4787 return true;
4788 if (SetWrittenArgs)
4789 Decl->setTemplateArgsAsWritten(TemplateArgs);
4790
4791 if (VarTemplatePartialSpecializationDecl *D =
4792 dyn_cast<VarTemplatePartialSpecializationDecl>(Val: InstantiationPattern))
4793 Decl->setInstantiationOf(PartialSpec: D, TemplateArgs: PartialSpecArgs);
4794
4795 checkSpecializationReachability(Loc: TemplateNameLoc, Spec: Decl);
4796
4797 assert(Decl && "No variable template specialization?");
4798 return Decl;
4799}
4800
4801ExprResult Sema::CheckVarTemplateId(
4802 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4803 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4804 const TemplateArgumentListInfo *TemplateArgs) {
4805
4806 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, TemplateNameLoc: NameInfo.getLoc(),
4807 TemplateArgs: *TemplateArgs, /*SetWrittenArgs=*/false);
4808 if (Decl.isInvalid())
4809 return ExprError();
4810
4811 if (!Decl.get())
4812 return ExprResult();
4813
4814 VarDecl *Var = cast<VarDecl>(Val: Decl.get());
4815 if (!Var->getTemplateSpecializationKind())
4816 Var->setTemplateSpecializationKind(TSK: TSK_ImplicitInstantiation,
4817 PointOfInstantiation: NameInfo.getLoc());
4818
4819 // Build an ordinary singleton decl ref.
4820 return BuildDeclarationNameExpr(SS, NameInfo, D: Var, FoundD, TemplateArgs);
4821}
4822
4823ExprResult Sema::CheckVarOrConceptTemplateTemplateId(
4824 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4825 TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc,
4826 const TemplateArgumentListInfo *TemplateArgs) {
4827 assert(Template && "A variable template id without template?");
4828
4829 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4830 Template->templateParameterKind() !=
4831 TemplateNameKind::TNK_Concept_template)
4832 return ExprResult();
4833
4834 // Check that the template argument list is well-formed for this template.
4835 CheckTemplateArgumentInfo CTAI;
4836 if (CheckTemplateArgumentList(
4837 Template, TemplateLoc,
4838 // FIXME: TemplateArgs will not be modified because
4839 // UpdateArgsWithConversions is false, however, we should
4840 // CheckTemplateArgumentList to be const-correct.
4841 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4842 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4843 /*UpdateArgsWithConversions=*/false))
4844 return true;
4845
4846 UnresolvedSet<1> R;
4847 R.addDecl(D: Template);
4848
4849 // FIXME: We model references to variable template and concept parameters
4850 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4851 // data, can generally be used in the same places and work the same way.
4852 // However, it might be cleaner to use a dedicated AST node in the long run.
4853 return UnresolvedLookupExpr::Create(
4854 Context: getASTContext(), NamingClass: nullptr, QualifierLoc: SS.getWithLocInContext(Context&: getASTContext()),
4855 TemplateKWLoc: SourceLocation(), NameInfo, RequiresADL: false, Args: TemplateArgs, Begin: R.begin(), End: R.end(),
4856 /*KnownDependent=*/false,
4857 /*KnownInstantiationDependent=*/false);
4858}
4859
4860void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4861 SourceLocation Loc) {
4862 Diag(Loc, DiagID: diag::err_template_missing_args)
4863 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4864 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4865 NoteTemplateLocation(Decl: *TD, ParamRange: TD->getTemplateParameters()->getSourceRange());
4866 }
4867}
4868
4869void Sema::diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
4870 bool TemplateKeyword,
4871 TemplateDecl *TD,
4872 SourceLocation Loc) {
4873 TemplateName Name = Context.getQualifiedTemplateName(
4874 Qualifier: SS.getScopeRep(), TemplateKeyword, Template: TemplateName(TD));
4875 diagnoseMissingTemplateArguments(Name, Loc);
4876}
4877
4878ExprResult Sema::CheckConceptTemplateId(
4879 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4880 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4881 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4882 bool DoCheckConstraintSatisfaction) {
4883 assert(NamedConcept && "A concept template id without a template?");
4884
4885 if (NamedConcept->isInvalidDecl())
4886 return ExprError();
4887
4888 CheckTemplateArgumentInfo CTAI;
4889 if (CheckTemplateArgumentList(
4890 Template: NamedConcept, TemplateLoc: ConceptNameInfo.getLoc(),
4891 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4892 /*DefaultArgs=*/{},
4893 /*PartialTemplateArgs=*/false, CTAI,
4894 /*UpdateArgsWithConversions=*/false))
4895 return ExprError();
4896
4897 DiagnoseUseOfDecl(D: NamedConcept, Locs: ConceptNameInfo.getLoc());
4898
4899 // There's a bug with CTAI.CanonicalConverted.
4900 // If the template argument contains a DependentDecltypeType that includes a
4901 // TypeAliasType, and the same written type had occurred previously in the
4902 // source, then the DependentDecltypeType would be canonicalized to that
4903 // previous type which would mess up the substitution.
4904 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4905 auto *CSD = ImplicitConceptSpecializationDecl::Create(
4906 C: Context, DC: NamedConcept->getDeclContext(), SL: NamedConcept->getLocation(),
4907 ConvertedArgs: CTAI.SugaredConverted);
4908 ConstraintSatisfaction Satisfaction;
4909 bool AreArgsDependent =
4910 TemplateSpecializationType::anyDependentTemplateArguments(
4911 *TemplateArgs, Converted: CTAI.SugaredConverted);
4912 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4913 /*Final=*/false);
4914 auto *CL = ConceptReference::Create(
4915 C: Context,
4916 NNS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4917 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4918 ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: *TemplateArgs));
4919
4920 bool Error = false;
4921 if (const auto *Concept = dyn_cast<ConceptDecl>(Val: NamedConcept);
4922 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4923 DoCheckConstraintSatisfaction) {
4924
4925 LocalInstantiationScope Scope(*this);
4926
4927 EnterExpressionEvaluationContext EECtx{
4928 *this, ExpressionEvaluationContext::Unevaluated, CSD};
4929
4930 Error = CheckConstraintSatisfaction(
4931 Entity: NamedConcept, AssociatedConstraints: AssociatedConstraint(Concept->getConstraintExpr()), TemplateArgLists: MLTAL,
4932 TemplateIDRange: SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4933 TemplateArgs->getRAngleLoc()),
4934 Satisfaction, TopLevelConceptId: CL);
4935 Satisfaction.ContainsErrors = Error;
4936 }
4937
4938 if (Error)
4939 return ExprError();
4940
4941 return ConceptSpecializationExpr::Create(
4942 C: Context, ConceptRef: CL, SpecDecl: CSD, Satisfaction: AreArgsDependent ? nullptr : &Satisfaction);
4943}
4944
4945ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4946 SourceLocation TemplateKWLoc,
4947 LookupResult &R,
4948 bool RequiresADL,
4949 const TemplateArgumentListInfo *TemplateArgs) {
4950 // FIXME: Can we do any checking at this point? I guess we could check the
4951 // template arguments that we have against the template name, if the template
4952 // name refers to a single template. That's not a terribly common case,
4953 // though.
4954 // foo<int> could identify a single function unambiguously
4955 // This approach does NOT work, since f<int>(1);
4956 // gets resolved prior to resorting to overload resolution
4957 // i.e., template<class T> void f(double);
4958 // vs template<class T, class U> void f(U);
4959
4960 // These should be filtered out by our callers.
4961 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4962
4963 // Non-function templates require a template argument list.
4964 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4965 if (!TemplateArgs && !isa<FunctionTemplateDecl>(Val: TD)) {
4966 diagnoseMissingTemplateArguments(
4967 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, Loc: R.getNameLoc());
4968 return ExprError();
4969 }
4970 }
4971 bool KnownDependent = false;
4972 // In C++1y, check variable template ids.
4973 if (R.getAsSingle<VarTemplateDecl>()) {
4974 ExprResult Res = CheckVarTemplateId(
4975 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<VarTemplateDecl>(),
4976 FoundD: R.getRepresentativeDecl(), TemplateLoc: TemplateKWLoc, TemplateArgs);
4977 if (Res.isInvalid() || Res.isUsable())
4978 return Res;
4979 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4980 KnownDependent = true;
4981 }
4982
4983 // We don't want lookup warnings at this point.
4984 R.suppressDiagnostics();
4985
4986 if (R.getAsSingle<ConceptDecl>()) {
4987 return CheckConceptTemplateId(SS, TemplateKWLoc, ConceptNameInfo: R.getLookupNameInfo(),
4988 FoundDecl: R.getRepresentativeDecl(),
4989 NamedConcept: R.getAsSingle<ConceptDecl>(), TemplateArgs);
4990 }
4991
4992 // Check variable template ids (C++17) and concept template parameters
4993 // (C++26).
4994 UnresolvedLookupExpr *ULE;
4995 if (R.getAsSingle<TemplateTemplateParmDecl>())
4996 return CheckVarOrConceptTemplateTemplateId(
4997 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<TemplateTemplateParmDecl>(),
4998 TemplateLoc: TemplateKWLoc, TemplateArgs);
4999
5000 // Function templates
5001 ULE = UnresolvedLookupExpr::Create(
5002 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
5003 TemplateKWLoc, NameInfo: R.getLookupNameInfo(), RequiresADL, Args: TemplateArgs,
5004 Begin: R.begin(), End: R.end(), KnownDependent,
5005 /*KnownInstantiationDependent=*/false);
5006 // Model the templates with UnresolvedTemplateTy. The expression should then
5007 // either be transformed in an instantiation or be diagnosed in
5008 // CheckPlaceholderExpr.
5009 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5010 !R.getFoundDecl()->getAsFunction())
5011 ULE->setType(Context.UnresolvedTemplateTy);
5012
5013 return ULE;
5014}
5015
5016ExprResult Sema::BuildQualifiedTemplateIdExpr(
5017 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5018 const DeclarationNameInfo &NameInfo,
5019 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5020 assert(TemplateArgs || TemplateKWLoc.isValid());
5021
5022 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5023 if (LookupTemplateName(Found&: R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5024 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc))
5025 return ExprError();
5026
5027 if (R.isAmbiguous())
5028 return ExprError();
5029
5030 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5031 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5032
5033 if (R.empty()) {
5034 DeclContext *DC = computeDeclContext(SS);
5035 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
5036 << NameInfo.getName() << DC << SS.getRange();
5037 return ExprError();
5038 }
5039
5040 // If necessary, build an implicit class member access.
5041 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5042 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5043 /*S=*/nullptr);
5044
5045 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/RequiresADL: false, TemplateArgs);
5046}
5047
5048TemplateNameKind Sema::ActOnTemplateName(Scope *S,
5049 CXXScopeSpec &SS,
5050 SourceLocation TemplateKWLoc,
5051 const UnqualifiedId &Name,
5052 ParsedType ObjectType,
5053 bool EnteringContext,
5054 TemplateTy &Result,
5055 bool AllowInjectedClassName) {
5056 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5057 Diag(Loc: TemplateKWLoc,
5058 DiagID: getLangOpts().CPlusPlus11 ?
5059 diag::warn_cxx98_compat_template_outside_of_template :
5060 diag::ext_template_outside_of_template)
5061 << FixItHint::CreateRemoval(RemoveRange: TemplateKWLoc);
5062
5063 if (SS.isInvalid())
5064 return TNK_Non_template;
5065
5066 // Figure out where isTemplateName is going to look.
5067 DeclContext *LookupCtx = nullptr;
5068 if (SS.isNotEmpty())
5069 LookupCtx = computeDeclContext(SS, EnteringContext);
5070 else if (ObjectType)
5071 LookupCtx = computeDeclContext(T: GetTypeFromParser(Ty: ObjectType));
5072
5073 // C++0x [temp.names]p5:
5074 // If a name prefixed by the keyword template is not the name of
5075 // a template, the program is ill-formed. [Note: the keyword
5076 // template may not be applied to non-template members of class
5077 // templates. -end note ] [ Note: as is the case with the
5078 // typename prefix, the template prefix is allowed in cases
5079 // where it is not strictly necessary; i.e., when the
5080 // nested-name-specifier or the expression on the left of the ->
5081 // or . is not dependent on a template-parameter, or the use
5082 // does not appear in the scope of a template. -end note]
5083 //
5084 // Note: C++03 was more strict here, because it banned the use of
5085 // the "template" keyword prior to a template-name that was not a
5086 // dependent name. C++ DR468 relaxed this requirement (the
5087 // "template" keyword is now permitted). We follow the C++0x
5088 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5089 bool MemberOfUnknownSpecialization;
5090 TemplateNameKind TNK = isTemplateName(S, SS, hasTemplateKeyword: TemplateKWLoc.isValid(), Name,
5091 ObjectTypePtr: ObjectType, EnteringContext, TemplateResult&: Result,
5092 MemberOfUnknownSpecialization);
5093 if (TNK != TNK_Non_template) {
5094 // We resolved this to a (non-dependent) template name. Return it.
5095 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
5096 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5097 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5098 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5099 // C++14 [class.qual]p2:
5100 // In a lookup in which function names are not ignored and the
5101 // nested-name-specifier nominates a class C, if the name specified
5102 // [...] is the injected-class-name of C, [...] the name is instead
5103 // considered to name the constructor
5104 //
5105 // We don't get here if naming the constructor would be valid, so we
5106 // just reject immediately and recover by treating the
5107 // injected-class-name as naming the template.
5108 Diag(Loc: Name.getBeginLoc(),
5109 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
5110 << Name.Identifier
5111 << 0 /*injected-class-name used as template name*/
5112 << TemplateKWLoc.isValid();
5113 }
5114 return TNK;
5115 }
5116
5117 if (!MemberOfUnknownSpecialization) {
5118 // Didn't find a template name, and the lookup wasn't dependent.
5119 // Do the lookup again to determine if this is a "nothing found" case or
5120 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5121 // need to do this.
5122 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
5123 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5124 LookupOrdinaryName);
5125 // Tell LookupTemplateName that we require a template so that it diagnoses
5126 // cases where it finds a non-template.
5127 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5128 ? RequiredTemplateKind(TemplateKWLoc)
5129 : TemplateNameIsRequired;
5130 if (!LookupTemplateName(Found&: R, S, SS, ObjectType: ObjectType.get(), EnteringContext, RequiredTemplate: RTK,
5131 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5132 !R.isAmbiguous()) {
5133 if (LookupCtx)
5134 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_no_member)
5135 << DNI.getName() << LookupCtx << SS.getRange();
5136 else
5137 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_undeclared_use)
5138 << DNI.getName() << SS.getRange();
5139 }
5140 return TNK_Non_template;
5141 }
5142
5143 NestedNameSpecifier Qualifier = SS.getScopeRep();
5144
5145 switch (Name.getKind()) {
5146 case UnqualifiedIdKind::IK_Identifier:
5147 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5148 Name: {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5149 return TNK_Dependent_template_name;
5150
5151 case UnqualifiedIdKind::IK_OperatorFunctionId:
5152 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5153 Name: {Qualifier, Name.OperatorFunctionId.Operator,
5154 TemplateKWLoc.isValid()}));
5155 return TNK_Function_template;
5156
5157 case UnqualifiedIdKind::IK_LiteralOperatorId:
5158 // This is a kind of template name, but can never occur in a dependent
5159 // scope (literal operators can only be declared at namespace scope).
5160 break;
5161
5162 default:
5163 break;
5164 }
5165
5166 // This name cannot possibly name a dependent template. Diagnose this now
5167 // rather than building a dependent template name that can never be valid.
5168 Diag(Loc: Name.getBeginLoc(),
5169 DiagID: diag::err_template_kw_refers_to_dependent_non_template)
5170 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5171 << TemplateKWLoc.isValid() << TemplateKWLoc;
5172 return TNK_Non_template;
5173}
5174
5175bool Sema::CheckTemplateTypeArgument(
5176 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
5177 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5178 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5179 const TemplateArgument &Arg = AL.getArgument();
5180 QualType ArgType;
5181 TypeSourceInfo *TSI = nullptr;
5182
5183 // Check template type parameter.
5184 switch(Arg.getKind()) {
5185 case TemplateArgument::Type:
5186 // C++ [temp.arg.type]p1:
5187 // A template-argument for a template-parameter which is a
5188 // type shall be a type-id.
5189 ArgType = Arg.getAsType();
5190 TSI = AL.getTypeSourceInfo();
5191 break;
5192 case TemplateArgument::Template:
5193 case TemplateArgument::TemplateExpansion: {
5194 // We have a template type parameter but the template argument
5195 // is a template without any arguments.
5196 SourceRange SR = AL.getSourceRange();
5197 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5198 diagnoseMissingTemplateArguments(Name, Loc: SR.getEnd());
5199 return true;
5200 }
5201 case TemplateArgument::Expression: {
5202 // We have a template type parameter but the template argument is an
5203 // expression; see if maybe it is missing the "typename" keyword.
5204 CXXScopeSpec SS;
5205 DeclarationNameInfo NameInfo;
5206
5207 if (DependentScopeDeclRefExpr *ArgExpr =
5208 dyn_cast<DependentScopeDeclRefExpr>(Val: Arg.getAsExpr())) {
5209 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5210 NameInfo = ArgExpr->getNameInfo();
5211 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5212 dyn_cast<CXXDependentScopeMemberExpr>(Val: Arg.getAsExpr())) {
5213 if (ArgExpr->isImplicitAccess()) {
5214 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5215 NameInfo = ArgExpr->getMemberNameInfo();
5216 }
5217 }
5218
5219 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5220 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5221 LookupParsedName(R&: Result, S: CurScope, SS: &SS, /*ObjectType=*/QualType());
5222
5223 if (Result.getAsSingle<TypeDecl>() ||
5224 Result.wasNotFoundInCurrentInstantiation()) {
5225 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5226 // Suggest that the user add 'typename' before the NNS.
5227 SourceLocation Loc = AL.getSourceRange().getBegin();
5228 Diag(Loc, DiagID: getLangOpts().MSVCCompat
5229 ? diag::ext_ms_template_type_arg_missing_typename
5230 : diag::err_template_arg_must_be_type_suggest)
5231 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
5232 NoteTemplateParameterLocation(Decl: *Param);
5233
5234 // Recover by synthesizing a type using the location information that we
5235 // already have.
5236 ArgType = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
5237 NNS: SS.getScopeRep(), Name: II);
5238 TypeLocBuilder TLB;
5239 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: ArgType);
5240 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5241 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5242 TL.setNameLoc(NameInfo.getLoc());
5243 TSI = TLB.getTypeSourceInfo(Context, T: ArgType);
5244
5245 // Overwrite our input TemplateArgumentLoc so that we can recover
5246 // properly.
5247 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5248 TemplateArgumentLocInfo(TSI));
5249
5250 break;
5251 }
5252 }
5253 // fallthrough
5254 [[fallthrough]];
5255 }
5256 default: {
5257 // We allow instantiating a template with template argument packs when
5258 // building deduction guides or mapping constraint template parameters.
5259 if (Arg.getKind() == TemplateArgument::Pack &&
5260 (CodeSynthesisContexts.back().Kind ==
5261 Sema::CodeSynthesisContext::BuildingDeductionGuides ||
5262 inParameterMappingSubstitution())) {
5263 SugaredConverted.push_back(Elt: Arg);
5264 CanonicalConverted.push_back(Elt: Arg);
5265 return false;
5266 }
5267 // We have a template type parameter but the template argument
5268 // is not a type.
5269 SourceRange SR = AL.getSourceRange();
5270 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_type) << SR;
5271 NoteTemplateParameterLocation(Decl: *Param);
5272
5273 return true;
5274 }
5275 }
5276
5277 if (CheckTemplateArgument(Arg: TSI))
5278 return true;
5279
5280 // Objective-C ARC:
5281 // If an explicitly-specified template argument type is a lifetime type
5282 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5283 if (getLangOpts().ObjCAutoRefCount &&
5284 ArgType->isObjCLifetimeType() &&
5285 !ArgType.getObjCLifetime()) {
5286 Qualifiers Qs;
5287 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5288 ArgType = Context.getQualifiedType(T: ArgType, Qs);
5289 }
5290
5291 SugaredConverted.push_back(Elt: TemplateArgument(ArgType));
5292 CanonicalConverted.push_back(
5293 Elt: TemplateArgument(Context.getCanonicalType(T: ArgType)));
5294 return false;
5295}
5296
5297/// Substitute template arguments into the default template argument for
5298/// the given template type parameter.
5299///
5300/// \param SemaRef the semantic analysis object for which we are performing
5301/// the substitution.
5302///
5303/// \param Template the template that we are synthesizing template arguments
5304/// for.
5305///
5306/// \param TemplateLoc the location of the template name that started the
5307/// template-id we are checking.
5308///
5309/// \param RAngleLoc the location of the right angle bracket ('>') that
5310/// terminates the template-id.
5311///
5312/// \param Param the template template parameter whose default we are
5313/// substituting into.
5314///
5315/// \param Converted the list of template arguments provided for template
5316/// parameters that precede \p Param in the template parameter list.
5317///
5318/// \param Output the resulting substituted template argument.
5319///
5320/// \returns true if an error occurred.
5321static bool SubstDefaultTemplateArgument(
5322 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5323 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5324 ArrayRef<TemplateArgument> SugaredConverted,
5325 ArrayRef<TemplateArgument> CanonicalConverted,
5326 TemplateArgumentLoc &Output) {
5327 Output = Param->getDefaultArgument();
5328
5329 // If the argument type is dependent, instantiate it now based
5330 // on the previously-computed template arguments.
5331 if (Output.getArgument().isInstantiationDependent()) {
5332 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5333 SugaredConverted,
5334 SourceRange(TemplateLoc, RAngleLoc));
5335 if (Inst.isInvalid())
5336 return true;
5337
5338 // Only substitute for the innermost template argument list.
5339 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5340 /*Final=*/true);
5341 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5342 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5343
5344 bool ForLambdaCallOperator = false;
5345 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Val: Template->getDeclContext()))
5346 ForLambdaCallOperator = Rec->isLambda();
5347 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5348 !ForLambdaCallOperator);
5349
5350 if (SemaRef.SubstTemplateArgument(Input: Output, TemplateArgs: TemplateArgLists, Output,
5351 Loc: Param->getDefaultArgumentLoc(),
5352 Entity: Param->getDeclName()))
5353 return true;
5354 }
5355
5356 return false;
5357}
5358
5359/// Substitute template arguments into the default template argument for
5360/// the given non-type template parameter.
5361///
5362/// \param SemaRef the semantic analysis object for which we are performing
5363/// the substitution.
5364///
5365/// \param Template the template that we are synthesizing template arguments
5366/// for.
5367///
5368/// \param TemplateLoc the location of the template name that started the
5369/// template-id we are checking.
5370///
5371/// \param RAngleLoc the location of the right angle bracket ('>') that
5372/// terminates the template-id.
5373///
5374/// \param Param the non-type template parameter whose default we are
5375/// substituting into.
5376///
5377/// \param Converted the list of template arguments provided for template
5378/// parameters that precede \p Param in the template parameter list.
5379///
5380/// \returns the substituted template argument, or NULL if an error occurred.
5381static bool SubstDefaultTemplateArgument(
5382 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5383 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5384 ArrayRef<TemplateArgument> SugaredConverted,
5385 ArrayRef<TemplateArgument> CanonicalConverted,
5386 TemplateArgumentLoc &Output) {
5387 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5388 SugaredConverted,
5389 SourceRange(TemplateLoc, RAngleLoc));
5390 if (Inst.isInvalid())
5391 return true;
5392
5393 // Only substitute for the innermost template argument list.
5394 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5395 /*Final=*/true);
5396 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5397 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5398
5399 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5400 EnterExpressionEvaluationContext ConstantEvaluated(
5401 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5402 return SemaRef.SubstTemplateArgument(Input: Param->getDefaultArgument(),
5403 TemplateArgs: TemplateArgLists, Output);
5404}
5405
5406/// Substitute template arguments into the default template argument for
5407/// the given template template parameter.
5408///
5409/// \param SemaRef the semantic analysis object for which we are performing
5410/// the substitution.
5411///
5412/// \param Template the template that we are synthesizing template arguments
5413/// for.
5414///
5415/// \param TemplateLoc the location of the template name that started the
5416/// template-id we are checking.
5417///
5418/// \param RAngleLoc the location of the right angle bracket ('>') that
5419/// terminates the template-id.
5420///
5421/// \param Param the template template parameter whose default we are
5422/// substituting into.
5423///
5424/// \param Converted the list of template arguments provided for template
5425/// parameters that precede \p Param in the template parameter list.
5426///
5427/// \param QualifierLoc Will be set to the nested-name-specifier (with
5428/// source-location information) that precedes the template name.
5429///
5430/// \returns the substituted template argument, or NULL if an error occurred.
5431static TemplateName SubstDefaultTemplateArgument(
5432 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5433 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5434 TemplateTemplateParmDecl *Param,
5435 ArrayRef<TemplateArgument> SugaredConverted,
5436 ArrayRef<TemplateArgument> CanonicalConverted,
5437 NestedNameSpecifierLoc &QualifierLoc) {
5438 Sema::InstantiatingTemplate Inst(
5439 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5440 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5441 if (Inst.isInvalid())
5442 return TemplateName();
5443
5444 // Only substitute for the innermost template argument list.
5445 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5446 /*Final=*/true);
5447 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5448 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5449
5450 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5451
5452 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5453 QualifierLoc = A.getTemplateQualifierLoc();
5454 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5455 Name: A.getArgument().getAsTemplate(),
5456 NameLoc: A.getTemplateNameLoc(), TemplateArgs: TemplateArgLists);
5457}
5458
5459TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5460 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5461 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5462 ArrayRef<TemplateArgument> SugaredConverted,
5463 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5464 HasDefaultArg = false;
5465
5466 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
5467 if (!hasReachableDefaultArgument(D: TypeParm))
5468 return TemplateArgumentLoc();
5469
5470 HasDefaultArg = true;
5471 TemplateArgumentLoc Output;
5472 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5473 RAngleLoc, Param: TypeParm, SugaredConverted,
5474 CanonicalConverted, Output))
5475 return TemplateArgumentLoc();
5476 return Output;
5477 }
5478
5479 if (NonTypeTemplateParmDecl *NonTypeParm
5480 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5481 if (!hasReachableDefaultArgument(D: NonTypeParm))
5482 return TemplateArgumentLoc();
5483
5484 HasDefaultArg = true;
5485 TemplateArgumentLoc Output;
5486 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5487 RAngleLoc, Param: NonTypeParm, SugaredConverted,
5488 CanonicalConverted, Output))
5489 return TemplateArgumentLoc();
5490 return Output;
5491 }
5492
5493 TemplateTemplateParmDecl *TempTempParm
5494 = cast<TemplateTemplateParmDecl>(Val: Param);
5495 if (!hasReachableDefaultArgument(D: TempTempParm))
5496 return TemplateArgumentLoc();
5497
5498 HasDefaultArg = true;
5499 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5500 NestedNameSpecifierLoc QualifierLoc;
5501 TemplateName TName = SubstDefaultTemplateArgument(
5502 SemaRef&: *this, Template, TemplateKWLoc, TemplateLoc: TemplateNameLoc, RAngleLoc, Param: TempTempParm,
5503 SugaredConverted, CanonicalConverted, QualifierLoc);
5504 if (TName.isNull())
5505 return TemplateArgumentLoc();
5506
5507 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5508 QualifierLoc, A.getTemplateNameLoc());
5509}
5510
5511/// Convert a template-argument that we parsed as a type into a template, if
5512/// possible. C++ permits injected-class-names to perform dual service as
5513/// template template arguments and as template type arguments.
5514static TemplateArgumentLoc
5515convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5516 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5517 if (!TagLoc)
5518 return TemplateArgumentLoc();
5519
5520 // If this type was written as an injected-class-name, it can be used as a
5521 // template template argument.
5522 // If this type was written as an injected-class-name, it may have been
5523 // converted to a RecordType during instantiation. If the RecordType is
5524 // *not* wrapped in a TemplateSpecializationType and denotes a class
5525 // template specialization, it must have come from an injected-class-name.
5526
5527 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Ctx: Context);
5528 if (Name.isNull())
5529 return TemplateArgumentLoc();
5530
5531 return TemplateArgumentLoc(Context, Name,
5532 /*TemplateKWLoc=*/SourceLocation(),
5533 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5534}
5535
5536bool Sema::CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &ArgLoc,
5537 NamedDecl *Template,
5538 SourceLocation TemplateLoc,
5539 SourceLocation RAngleLoc,
5540 unsigned ArgumentPackIndex,
5541 CheckTemplateArgumentInfo &CTAI,
5542 CheckTemplateArgumentKind CTAK) {
5543 // Check template type parameters.
5544 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param))
5545 return CheckTemplateTypeArgument(Param: TTP, AL&: ArgLoc, SugaredConverted&: CTAI.SugaredConverted,
5546 CanonicalConverted&: CTAI.CanonicalConverted);
5547
5548 const TemplateArgument &Arg = ArgLoc.getArgument();
5549 // Check non-type template parameters.
5550 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5551 // Do substitution on the type of the non-type template parameter
5552 // with the template arguments we've seen thus far. But if the
5553 // template has a dependent context then we cannot substitute yet.
5554 QualType NTTPType = NTTP->getType();
5555 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5556 NTTPType = NTTP->getExpansionType(I: ArgumentPackIndex);
5557
5558 if (NTTPType->isInstantiationDependentType()) {
5559 // Do substitution on the type of the non-type template parameter.
5560 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5561 CTAI.SugaredConverted,
5562 SourceRange(TemplateLoc, RAngleLoc));
5563 if (Inst.isInvalid())
5564 return true;
5565
5566 MultiLevelTemplateArgumentList MLTAL(Template, CTAI.SugaredConverted,
5567 /*Final=*/true);
5568 MLTAL.addOuterRetainedLevels(Num: NTTP->getDepth());
5569 // If the parameter is a pack expansion, expand this slice of the pack.
5570 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5571 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5572 NTTPType = SubstType(T: PET->getPattern(), TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5573 Entity: NTTP->getDeclName());
5574 } else {
5575 NTTPType = SubstType(T: NTTPType, TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5576 Entity: NTTP->getDeclName());
5577 }
5578
5579 // If that worked, check the non-type template parameter type
5580 // for validity.
5581 if (!NTTPType.isNull())
5582 NTTPType = CheckNonTypeTemplateParameterType(T: NTTPType,
5583 Loc: NTTP->getLocation());
5584 if (NTTPType.isNull())
5585 return true;
5586 }
5587
5588 auto checkExpr = [&](Expr *E) -> Expr * {
5589 TemplateArgument SugaredResult, CanonicalResult;
5590 ExprResult Res = CheckTemplateArgument(
5591 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E, SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5592 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5593 // If the current template argument causes an error, give up now.
5594 if (Res.isInvalid())
5595 return nullptr;
5596 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5597 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5598 return Res.get();
5599 };
5600
5601 switch (Arg.getKind()) {
5602 case TemplateArgument::Null:
5603 llvm_unreachable("Should never see a NULL template argument here");
5604
5605 case TemplateArgument::Expression: {
5606 Expr *E = Arg.getAsExpr();
5607 Expr *R = checkExpr(E);
5608 if (!R)
5609 return true;
5610 // If the resulting expression is new, then use it in place of the
5611 // old expression in the template argument.
5612 if (R != E) {
5613 TemplateArgument TA(R, /*IsCanonical=*/false);
5614 ArgLoc = TemplateArgumentLoc(TA, R);
5615 }
5616 break;
5617 }
5618
5619 // As for the converted NTTP kinds, they still might need another
5620 // conversion, as the new corresponding parameter might be different.
5621 // Ideally, we would always perform substitution starting with sugared types
5622 // and never need these, as we would still have expressions. Since these are
5623 // needed so rarely, it's probably a better tradeoff to just convert them
5624 // back to expressions.
5625 case TemplateArgument::Integral:
5626 case TemplateArgument::Declaration:
5627 case TemplateArgument::NullPtr:
5628 case TemplateArgument::StructuralValue: {
5629 // FIXME: StructuralValue is untested here.
5630 ExprResult R =
5631 BuildExpressionFromNonTypeTemplateArgument(Arg, Loc: SourceLocation());
5632 assert(R.isUsable());
5633 if (!checkExpr(R.get()))
5634 return true;
5635 break;
5636 }
5637
5638 case TemplateArgument::Template:
5639 case TemplateArgument::TemplateExpansion:
5640 // We were given a template template argument. It may not be ill-formed;
5641 // see below.
5642 if (DependentTemplateName *DTN = Arg.getAsTemplateOrTemplatePattern()
5643 .getAsDependentTemplateName()) {
5644 // We have a template argument such as \c T::template X, which we
5645 // parsed as a template template argument. However, since we now
5646 // know that we need a non-type template argument, convert this
5647 // template name into an expression.
5648
5649 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5650 ArgLoc.getTemplateNameLoc());
5651
5652 CXXScopeSpec SS;
5653 SS.Adopt(Other: ArgLoc.getTemplateQualifierLoc());
5654 // FIXME: the template-template arg was a DependentTemplateName,
5655 // so it was provided with a template keyword. However, its source
5656 // location is not stored in the template argument structure.
5657 SourceLocation TemplateKWLoc;
5658 ExprResult E = DependentScopeDeclRefExpr::Create(
5659 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5660 TemplateArgs: nullptr);
5661
5662 // If we parsed the template argument as a pack expansion, create a
5663 // pack expansion expression.
5664 if (Arg.getKind() == TemplateArgument::TemplateExpansion) {
5665 E = ActOnPackExpansion(Pattern: E.get(), EllipsisLoc: ArgLoc.getTemplateEllipsisLoc());
5666 if (E.isInvalid())
5667 return true;
5668 }
5669
5670 TemplateArgument SugaredResult, CanonicalResult;
5671 E = CheckTemplateArgument(
5672 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E.get(), SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5673 /*StrictCheck=*/CTAI.PartialOrdering, CTAK: CTAK_Specified);
5674 if (E.isInvalid())
5675 return true;
5676
5677 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5678 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5679 break;
5680 }
5681
5682 // We have a template argument that actually does refer to a class
5683 // template, alias template, or template template parameter, and
5684 // therefore cannot be a non-type template argument.
5685 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_expr)
5686 << ArgLoc.getSourceRange();
5687 NoteTemplateParameterLocation(Decl: *Param);
5688
5689 return true;
5690
5691 case TemplateArgument::Type: {
5692 // We have a non-type template parameter but the template
5693 // argument is a type.
5694
5695 // C++ [temp.arg]p2:
5696 // In a template-argument, an ambiguity between a type-id and
5697 // an expression is resolved to a type-id, regardless of the
5698 // form of the corresponding template-parameter.
5699 //
5700 // We warn specifically about this case, since it can be rather
5701 // confusing for users.
5702 QualType T = Arg.getAsType();
5703 SourceRange SR = ArgLoc.getSourceRange();
5704 if (T->isFunctionType())
5705 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_nontype_ambig) << SR << T;
5706 else
5707 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_expr) << SR;
5708 NoteTemplateParameterLocation(Decl: *Param);
5709 return true;
5710 }
5711
5712 case TemplateArgument::Pack:
5713 llvm_unreachable("Caller must expand template argument packs");
5714 }
5715
5716 return false;
5717 }
5718
5719
5720 // Check template template parameters.
5721 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Val: Param);
5722
5723 TemplateParameterList *Params = TempParm->getTemplateParameters();
5724 if (TempParm->isExpandedParameterPack())
5725 Params = TempParm->getExpansionTemplateParameters(I: ArgumentPackIndex);
5726
5727 // Substitute into the template parameter list of the template
5728 // template parameter, since previously-supplied template arguments
5729 // may appear within the template template parameter.
5730 //
5731 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5732 {
5733 // Set up a template instantiation context.
5734 LocalInstantiationScope Scope(*this);
5735 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5736 CTAI.SugaredConverted,
5737 SourceRange(TemplateLoc, RAngleLoc));
5738 if (Inst.isInvalid())
5739 return true;
5740
5741 Params = SubstTemplateParams(
5742 Params, Owner: CurContext,
5743 TemplateArgs: MultiLevelTemplateArgumentList(Template, CTAI.SugaredConverted,
5744 /*Final=*/true),
5745 /*EvaluateConstraints=*/false);
5746 if (!Params)
5747 return true;
5748 }
5749
5750 // C++1z [temp.local]p1: (DR1004)
5751 // When [the injected-class-name] is used [...] as a template-argument for
5752 // a template template-parameter [...] it refers to the class template
5753 // itself.
5754 if (Arg.getKind() == TemplateArgument::Type) {
5755 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5756 Context, TLoc: ArgLoc.getTypeSourceInfo()->getTypeLoc());
5757 if (!ConvertedArg.getArgument().isNull())
5758 ArgLoc = ConvertedArg;
5759 }
5760
5761 switch (Arg.getKind()) {
5762 case TemplateArgument::Null:
5763 llvm_unreachable("Should never see a NULL template argument here");
5764
5765 case TemplateArgument::Template:
5766 case TemplateArgument::TemplateExpansion:
5767 if (CheckTemplateTemplateArgument(Param: TempParm, Params, Arg&: ArgLoc,
5768 PartialOrdering: CTAI.PartialOrdering,
5769 StrictPackMatch: &CTAI.StrictPackMatch))
5770 return true;
5771
5772 CTAI.SugaredConverted.push_back(Elt: Arg);
5773 CTAI.CanonicalConverted.push_back(
5774 Elt: Context.getCanonicalTemplateArgument(Arg));
5775 break;
5776
5777 case TemplateArgument::Expression:
5778 case TemplateArgument::Type: {
5779 auto Kind = 0;
5780 switch (TempParm->templateParameterKind()) {
5781 case TemplateNameKind::TNK_Var_template:
5782 Kind = 1;
5783 break;
5784 case TemplateNameKind::TNK_Concept_template:
5785 Kind = 2;
5786 break;
5787 default:
5788 break;
5789 }
5790
5791 // We have a template template parameter but the template
5792 // argument does not refer to a template.
5793 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_template)
5794 << Kind << getLangOpts().CPlusPlus11;
5795 return true;
5796 }
5797
5798 case TemplateArgument::Declaration:
5799 case TemplateArgument::Integral:
5800 case TemplateArgument::StructuralValue:
5801 case TemplateArgument::NullPtr:
5802 llvm_unreachable("non-type argument with template template parameter");
5803
5804 case TemplateArgument::Pack:
5805 llvm_unreachable("Caller must expand template argument packs");
5806 }
5807
5808 return false;
5809}
5810
5811/// Diagnose a missing template argument.
5812template<typename TemplateParmDecl>
5813static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5814 TemplateDecl *TD,
5815 const TemplateParmDecl *D,
5816 TemplateArgumentListInfo &Args) {
5817 // Dig out the most recent declaration of the template parameter; there may be
5818 // declarations of the template that are more recent than TD.
5819 D = cast<TemplateParmDecl>(cast<TemplateDecl>(Val: TD->getMostRecentDecl())
5820 ->getTemplateParameters()
5821 ->getParam(D->getIndex()));
5822
5823 // If there's a default argument that's not reachable, diagnose that we're
5824 // missing a module import.
5825 llvm::SmallVector<Module*, 8> Modules;
5826 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, Modules: &Modules)) {
5827 S.diagnoseMissingImport(Loc, cast<NamedDecl>(Val: TD),
5828 D->getDefaultArgumentLoc(), Modules,
5829 Sema::MissingImportKind::DefaultArgument,
5830 /*Recover*/true);
5831 return true;
5832 }
5833
5834 // FIXME: If there's a more recent default argument that *is* visible,
5835 // diagnose that it was declared too late.
5836
5837 TemplateParameterList *Params = TD->getTemplateParameters();
5838
5839 S.Diag(Loc, DiagID: diag::err_template_arg_list_different_arity)
5840 << /*not enough args*/0
5841 << (int)S.getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
5842 << TD;
5843 S.NoteTemplateLocation(Decl: *TD, ParamRange: Params->getSourceRange());
5844 return true;
5845}
5846
5847/// Check that the given template argument list is well-formed
5848/// for specializing the given template.
5849bool Sema::CheckTemplateArgumentList(
5850 TemplateDecl *Template, SourceLocation TemplateLoc,
5851 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5852 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5853 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5854 return CheckTemplateArgumentList(
5855 Template, Params: GetTemplateParameterList(TD: Template), TemplateLoc, TemplateArgs,
5856 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5857 ConstraintsNotSatisfied);
5858}
5859
5860/// Check that the given template argument list is well-formed
5861/// for specializing the given template.
5862bool Sema::CheckTemplateArgumentList(
5863 TemplateDecl *Template, TemplateParameterList *Params,
5864 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5865 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5866 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5867 bool *ConstraintsNotSatisfied) {
5868
5869 if (ConstraintsNotSatisfied)
5870 *ConstraintsNotSatisfied = false;
5871
5872 // Make a copy of the template arguments for processing. Only make the
5873 // changes at the end when successful in matching the arguments to the
5874 // template.
5875 TemplateArgumentListInfo NewArgs = TemplateArgs;
5876
5877 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5878
5879 // C++23 [temp.arg.general]p1:
5880 // [...] The type and form of each template-argument specified in
5881 // a template-id shall match the type and form specified for the
5882 // corresponding parameter declared by the template in its
5883 // template-parameter-list.
5884 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Val: Template);
5885 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5886 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5887 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5888 LocalInstantiationScope InstScope(*this, true);
5889 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5890 ParamEnd = Params->end(),
5891 Param = ParamBegin;
5892 Param != ParamEnd;
5893 /* increment in loop */) {
5894 if (size_t ParamIdx = Param - ParamBegin;
5895 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5896 // All written arguments should have been consumed by this point.
5897 assert(ArgIdx == NumArgs && "bad default argument deduction");
5898 if (ParamIdx == DefaultArgs.StartPos) {
5899 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5900 // Default arguments from a DeducedTemplateName are already converted.
5901 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5902 CTAI.SugaredConverted.push_back(Elt: DefArg);
5903 CTAI.CanonicalConverted.push_back(
5904 Elt: Context.getCanonicalTemplateArgument(Arg: DefArg));
5905 ++Param;
5906 }
5907 continue;
5908 }
5909 }
5910
5911 // If we have an expanded parameter pack, make sure we don't have too
5912 // many arguments.
5913 if (UnsignedOrNone Expansions = getExpandedPackSize(Param: *Param)) {
5914 if (*Expansions == SugaredArgumentPack.size()) {
5915 // We're done with this parameter pack. Pack up its arguments and add
5916 // them to the list.
5917 CTAI.SugaredConverted.push_back(
5918 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
5919 SugaredArgumentPack.clear();
5920
5921 CTAI.CanonicalConverted.push_back(
5922 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
5923 CanonicalArgumentPack.clear();
5924
5925 // This argument is assigned to the next parameter.
5926 ++Param;
5927 continue;
5928 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5929 // Not enough arguments for this parameter pack.
5930 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
5931 << /*not enough args*/0
5932 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
5933 << Template;
5934 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
5935 return true;
5936 }
5937 }
5938
5939 // Check for builtins producing template packs in this context, we do not
5940 // support them yet.
5941 if (const NonTypeTemplateParmDecl *NTTP =
5942 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param);
5943 NTTP && NTTP->isPackExpansion()) {
5944 auto TL = NTTP->getTypeSourceInfo()
5945 ->getTypeLoc()
5946 .castAs<PackExpansionTypeLoc>();
5947 llvm::SmallVector<UnexpandedParameterPack> Unexpanded;
5948 collectUnexpandedParameterPacks(TL: TL.getPatternLoc(), Unexpanded);
5949 for (const auto &UPP : Unexpanded) {
5950 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5951 if (!TST)
5952 continue;
5953 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5954 // Expanding a built-in pack in this context is not yet supported.
5955 Diag(Loc: TL.getEllipsisLoc(),
5956 DiagID: diag::err_unsupported_builtin_template_pack_expansion)
5957 << TST->getTemplateName();
5958 return true;
5959 }
5960 }
5961
5962 if (ArgIdx < NumArgs) {
5963 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5964 bool NonPackParameter =
5965 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(Param: *Param);
5966 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5967
5968 if (ArgIsExpansion && CTAI.MatchingTTP) {
5969 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5970 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5971 ++Param) {
5972 TemplateArgument &Arg = Args[Param - First];
5973 Arg = ArgLoc.getArgument();
5974 if (!(*Param)->isTemplateParameterPack() ||
5975 getExpandedPackSize(Param: *Param))
5976 Arg = Arg.getPackExpansionPattern();
5977 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5978 SaveAndRestore _1(CTAI.PartialOrdering, false);
5979 SaveAndRestore _2(CTAI.MatchingTTP, true);
5980 if (CheckTemplateArgument(Param: *Param, ArgLoc&: NewArgLoc, Template, TemplateLoc,
5981 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
5982 CTAK: CTAK_Specified))
5983 return true;
5984 Arg = NewArgLoc.getArgument();
5985 CTAI.CanonicalConverted.back().setIsDefaulted(
5986 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg, Param: *Param,
5987 Args: CTAI.CanonicalConverted,
5988 Depth: Params->getDepth()));
5989 }
5990 ArgLoc = TemplateArgumentLoc(
5991 TemplateArgument::CreatePackCopy(Context, Args),
5992 TemplateArgumentLocInfo(Context, ArgLoc.getLocation()));
5993 } else {
5994 SaveAndRestore _1(CTAI.PartialOrdering, false);
5995 if (CheckTemplateArgument(Param: *Param, ArgLoc, Template, TemplateLoc,
5996 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
5997 CTAK: CTAK_Specified))
5998 return true;
5999 CTAI.CanonicalConverted.back().setIsDefaulted(
6000 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg: ArgLoc.getArgument(),
6001 Param: *Param, Args: CTAI.CanonicalConverted,
6002 Depth: Params->getDepth()));
6003 if (ArgIsExpansion && NonPackParameter) {
6004 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6005 // alias template, builtin template, or concept, and it's not part of
6006 // a parameter pack. This can't be canonicalized, so reject it now.
6007 if (isa<TypeAliasTemplateDecl, ConceptDecl, BuiltinTemplateDecl>(
6008 Val: Template)) {
6009 unsigned DiagSelect = isa<ConceptDecl>(Val: Template) ? 1
6010 : isa<BuiltinTemplateDecl>(Val: Template) ? 2
6011 : 0;
6012 Diag(Loc: ArgLoc.getLocation(),
6013 DiagID: diag::err_template_expansion_into_fixed_list)
6014 << DiagSelect << ArgLoc.getSourceRange();
6015 NoteTemplateParameterLocation(Decl: **Param);
6016 return true;
6017 }
6018 }
6019 }
6020
6021 // We're now done with this argument.
6022 ++ArgIdx;
6023
6024 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6025 // Directly convert the remaining arguments, because we don't know what
6026 // parameters they'll match up with.
6027
6028 if (!SugaredArgumentPack.empty()) {
6029 // If we were part way through filling in an expanded parameter pack,
6030 // fall back to just producing individual arguments.
6031 CTAI.SugaredConverted.insert(I: CTAI.SugaredConverted.end(),
6032 From: SugaredArgumentPack.begin(),
6033 To: SugaredArgumentPack.end());
6034 SugaredArgumentPack.clear();
6035
6036 CTAI.CanonicalConverted.insert(I: CTAI.CanonicalConverted.end(),
6037 From: CanonicalArgumentPack.begin(),
6038 To: CanonicalArgumentPack.end());
6039 CanonicalArgumentPack.clear();
6040 }
6041
6042 while (ArgIdx < NumArgs) {
6043 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6044 CTAI.SugaredConverted.push_back(Elt: Arg);
6045 CTAI.CanonicalConverted.push_back(
6046 Elt: Context.getCanonicalTemplateArgument(Arg));
6047 ++ArgIdx;
6048 }
6049
6050 return false;
6051 }
6052
6053 if ((*Param)->isTemplateParameterPack()) {
6054 // The template parameter was a template parameter pack, so take the
6055 // deduced argument and place it on the argument pack. Note that we
6056 // stay on the same template parameter so that we can deduce more
6057 // arguments.
6058 SugaredArgumentPack.push_back(Elt: CTAI.SugaredConverted.pop_back_val());
6059 CanonicalArgumentPack.push_back(Elt: CTAI.CanonicalConverted.pop_back_val());
6060 } else {
6061 // Move to the next template parameter.
6062 ++Param;
6063 }
6064 continue;
6065 }
6066
6067 // If we're checking a partial template argument list, we're done.
6068 if (PartialTemplateArgs) {
6069 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6070 CTAI.SugaredConverted.push_back(
6071 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6072 CTAI.CanonicalConverted.push_back(
6073 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6074 }
6075 return false;
6076 }
6077
6078 // If we have a template parameter pack with no more corresponding
6079 // arguments, just break out now and we'll fill in the argument pack below.
6080 if ((*Param)->isTemplateParameterPack()) {
6081 assert(!getExpandedPackSize(*Param) &&
6082 "Should have dealt with this already");
6083
6084 // A non-expanded parameter pack before the end of the parameter list
6085 // only occurs for an ill-formed template parameter list, unless we've
6086 // got a partial argument list for a function template, so just bail out.
6087 if (Param + 1 != ParamEnd) {
6088 assert(
6089 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6090 "Concept templates must have parameter packs at the end.");
6091 return true;
6092 }
6093
6094 CTAI.SugaredConverted.push_back(
6095 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6096 SugaredArgumentPack.clear();
6097
6098 CTAI.CanonicalConverted.push_back(
6099 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6100 CanonicalArgumentPack.clear();
6101
6102 ++Param;
6103 continue;
6104 }
6105
6106 // Check whether we have a default argument.
6107 bool HasDefaultArg;
6108
6109 // Retrieve the default template argument from the template
6110 // parameter. For each kind of template parameter, we substitute the
6111 // template arguments provided thus far and any "outer" template arguments
6112 // (when the template parameter was part of a nested template) into
6113 // the default argument.
6114 TemplateArgumentLoc Arg = SubstDefaultTemplateArgumentIfAvailable(
6115 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateNameLoc: TemplateLoc, RAngleLoc,
6116 Param: *Param, SugaredConverted: CTAI.SugaredConverted, CanonicalConverted: CTAI.CanonicalConverted, HasDefaultArg);
6117
6118 if (Arg.getArgument().isNull()) {
6119 if (!HasDefaultArg) {
6120 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *Param))
6121 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: TTP,
6122 Args&: NewArgs);
6123 if (NonTypeTemplateParmDecl *NTTP =
6124 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param))
6125 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: NTTP,
6126 Args&: NewArgs);
6127 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template,
6128 D: cast<TemplateTemplateParmDecl>(Val: *Param),
6129 Args&: NewArgs);
6130 }
6131 return true;
6132 }
6133
6134 // Introduce an instantiation record that describes where we are using
6135 // the default template argument. We're not actually instantiating a
6136 // template here, we just create this object to put a note into the
6137 // context stack.
6138 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6139 CTAI.SugaredConverted,
6140 SourceRange(TemplateLoc, RAngleLoc));
6141 if (Inst.isInvalid())
6142 return true;
6143
6144 SaveAndRestore _1(CTAI.PartialOrdering, false);
6145 SaveAndRestore _2(CTAI.MatchingTTP, false);
6146 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6147 // Check the default template argument.
6148 if (CheckTemplateArgument(Param: *Param, ArgLoc&: Arg, Template, TemplateLoc, RAngleLoc, ArgumentPackIndex: 0,
6149 CTAI, CTAK: CTAK_Specified))
6150 return true;
6151
6152 CTAI.SugaredConverted.back().setIsDefaulted(true);
6153 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6154
6155 // Core issue 150 (assumed resolution): if this is a template template
6156 // parameter, keep track of the default template arguments from the
6157 // template definition.
6158 if (isTemplateTemplateParameter)
6159 NewArgs.addArgument(Loc: Arg);
6160
6161 // Move to the next template parameter and argument.
6162 ++Param;
6163 ++ArgIdx;
6164 }
6165
6166 // If we're performing a partial argument substitution, allow any trailing
6167 // pack expansions; they might be empty. This can happen even if
6168 // PartialTemplateArgs is false (the list of arguments is complete but
6169 // still dependent).
6170 if (CTAI.MatchingTTP ||
6171 (CurrentInstantiationScope &&
6172 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6173 while (ArgIdx < NumArgs &&
6174 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6175 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6176 CTAI.SugaredConverted.push_back(Elt: Arg);
6177 CTAI.CanonicalConverted.push_back(
6178 Elt: Context.getCanonicalTemplateArgument(Arg));
6179 }
6180 }
6181
6182 // If we have any leftover arguments, then there were too many arguments.
6183 // Complain and fail.
6184 if (ArgIdx < NumArgs) {
6185 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
6186 << /*too many args*/1
6187 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
6188 << Template
6189 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6190 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
6191 return true;
6192 }
6193
6194 // No problems found with the new argument list, propagate changes back
6195 // to caller.
6196 if (UpdateArgsWithConversions)
6197 TemplateArgs = std::move(NewArgs);
6198
6199 if (!PartialTemplateArgs) {
6200 // Setup the context/ThisScope for the case where we are needing to
6201 // re-instantiate constraints outside of normal instantiation.
6202 DeclContext *NewContext = Template->getDeclContext();
6203
6204 // If this template is in a template, make sure we extract the templated
6205 // decl.
6206 if (auto *TD = dyn_cast<TemplateDecl>(Val: NewContext))
6207 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6208 auto *RD = dyn_cast<CXXRecordDecl>(Val: NewContext);
6209
6210 Qualifiers ThisQuals;
6211 if (const auto *Method =
6212 dyn_cast_or_null<CXXMethodDecl>(Val: Template->getTemplatedDecl()))
6213 ThisQuals = Method->getMethodQualifiers();
6214
6215 ContextRAII Context(*this, NewContext);
6216 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6217
6218 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6219 D: Template, DC: NewContext, /*Final=*/true, Innermost: CTAI.SugaredConverted,
6220 /*RelativeToPrimary=*/true,
6221 /*Pattern=*/nullptr,
6222 /*ForConceptInstantiation=*/ForConstraintInstantiation: true);
6223 if (!isa<ConceptDecl>(Val: Template) &&
6224 EnsureTemplateArgumentListConstraints(
6225 Template, TemplateArgs: MLTAL,
6226 TemplateIDRange: SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6227 if (ConstraintsNotSatisfied)
6228 *ConstraintsNotSatisfied = true;
6229 return true;
6230 }
6231 }
6232
6233 return false;
6234}
6235
6236namespace {
6237 class UnnamedLocalNoLinkageFinder
6238 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6239 {
6240 Sema &S;
6241 SourceRange SR;
6242
6243 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6244
6245 public:
6246 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6247
6248 bool Visit(QualType T) {
6249 return T.isNull() ? false : inherited::Visit(T: T.getTypePtr());
6250 }
6251
6252#define TYPE(Class, Parent) \
6253 bool Visit##Class##Type(const Class##Type *);
6254#define ABSTRACT_TYPE(Class, Parent) \
6255 bool Visit##Class##Type(const Class##Type *) { return false; }
6256#define NON_CANONICAL_TYPE(Class, Parent) \
6257 bool Visit##Class##Type(const Class##Type *) { return false; }
6258#include "clang/AST/TypeNodes.inc"
6259
6260 bool VisitTagDecl(const TagDecl *Tag);
6261 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6262 };
6263} // end anonymous namespace
6264
6265bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6266 return false;
6267}
6268
6269bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6270 return Visit(T: T->getElementType());
6271}
6272
6273bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6274 return Visit(T: T->getPointeeType());
6275}
6276
6277bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6278 const BlockPointerType* T) {
6279 return Visit(T: T->getPointeeType());
6280}
6281
6282bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6283 const LValueReferenceType* T) {
6284 return Visit(T: T->getPointeeType());
6285}
6286
6287bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6288 const RValueReferenceType* T) {
6289 return Visit(T: T->getPointeeType());
6290}
6291
6292bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6293 const MemberPointerType *T) {
6294 if (Visit(T: T->getPointeeType()))
6295 return true;
6296 if (auto *RD = T->getMostRecentCXXRecordDecl())
6297 return VisitTagDecl(Tag: RD);
6298 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6299}
6300
6301bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6302 const ConstantArrayType* T) {
6303 return Visit(T: T->getElementType());
6304}
6305
6306bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6307 const IncompleteArrayType* T) {
6308 return Visit(T: T->getElementType());
6309}
6310
6311bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6312 const VariableArrayType* T) {
6313 return Visit(T: T->getElementType());
6314}
6315
6316bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6317 const DependentSizedArrayType* T) {
6318 return Visit(T: T->getElementType());
6319}
6320
6321bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6322 const DependentSizedExtVectorType* T) {
6323 return Visit(T: T->getElementType());
6324}
6325
6326bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6327 const DependentSizedMatrixType *T) {
6328 return Visit(T: T->getElementType());
6329}
6330
6331bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6332 const DependentAddressSpaceType *T) {
6333 return Visit(T: T->getPointeeType());
6334}
6335
6336bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6337 return Visit(T: T->getElementType());
6338}
6339
6340bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6341 const DependentVectorType *T) {
6342 return Visit(T: T->getElementType());
6343}
6344
6345bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6346 return Visit(T: T->getElementType());
6347}
6348
6349bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6350 const ConstantMatrixType *T) {
6351 return Visit(T: T->getElementType());
6352}
6353
6354bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6355 const FunctionProtoType* T) {
6356 for (const auto &A : T->param_types()) {
6357 if (Visit(T: A))
6358 return true;
6359 }
6360
6361 return Visit(T: T->getReturnType());
6362}
6363
6364bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6365 const FunctionNoProtoType* T) {
6366 return Visit(T: T->getReturnType());
6367}
6368
6369bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6370 const UnresolvedUsingType*) {
6371 return false;
6372}
6373
6374bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6375 return false;
6376}
6377
6378bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6379 return Visit(T: T->getUnmodifiedType());
6380}
6381
6382bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6383 return false;
6384}
6385
6386bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6387 const PackIndexingType *) {
6388 return false;
6389}
6390
6391bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6392 const UnaryTransformType*) {
6393 return false;
6394}
6395
6396bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6397 return Visit(T: T->getDeducedType());
6398}
6399
6400bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6401 const DeducedTemplateSpecializationType *T) {
6402 return Visit(T: T->getDeducedType());
6403}
6404
6405bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6406 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6407}
6408
6409bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6410 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6411}
6412
6413bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6414 const TemplateTypeParmType*) {
6415 return false;
6416}
6417
6418bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6419 const SubstTemplateTypeParmPackType *) {
6420 return false;
6421}
6422
6423bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6424 const SubstBuiltinTemplatePackType *) {
6425 return false;
6426}
6427
6428bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6429 const TemplateSpecializationType*) {
6430 return false;
6431}
6432
6433bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6434 const InjectedClassNameType* T) {
6435 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6436}
6437
6438bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6439 const DependentNameType* T) {
6440 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6441}
6442
6443bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6444 const PackExpansionType* T) {
6445 return Visit(T: T->getPattern());
6446}
6447
6448bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6449 return false;
6450}
6451
6452bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6453 const ObjCInterfaceType *) {
6454 return false;
6455}
6456
6457bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6458 const ObjCObjectPointerType *) {
6459 return false;
6460}
6461
6462bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6463 return Visit(T: T->getValueType());
6464}
6465
6466bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6467 const OverflowBehaviorType *T) {
6468 return Visit(T: T->getUnderlyingType());
6469}
6470
6471bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6472 return false;
6473}
6474
6475bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6476 return false;
6477}
6478
6479bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6480 const ArrayParameterType *T) {
6481 return VisitConstantArrayType(T);
6482}
6483
6484bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6485 const DependentBitIntType *T) {
6486 return false;
6487}
6488
6489bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6490 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6491 S.Diag(Loc: SR.getBegin(), DiagID: S.getLangOpts().CPlusPlus11
6492 ? diag::warn_cxx98_compat_template_arg_local_type
6493 : diag::ext_template_arg_local_type)
6494 << S.Context.getCanonicalTagType(TD: Tag) << SR;
6495 return true;
6496 }
6497
6498 if (!Tag->hasNameForLinkage()) {
6499 S.Diag(Loc: SR.getBegin(),
6500 DiagID: S.getLangOpts().CPlusPlus11 ?
6501 diag::warn_cxx98_compat_template_arg_unnamed_type :
6502 diag::ext_template_arg_unnamed_type) << SR;
6503 S.Diag(Loc: Tag->getLocation(), DiagID: diag::note_template_unnamed_type_here);
6504 return true;
6505 }
6506
6507 return false;
6508}
6509
6510bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6511 NestedNameSpecifier NNS) {
6512 switch (NNS.getKind()) {
6513 case NestedNameSpecifier::Kind::Null:
6514 case NestedNameSpecifier::Kind::Namespace:
6515 case NestedNameSpecifier::Kind::Global:
6516 case NestedNameSpecifier::Kind::MicrosoftSuper:
6517 return false;
6518 case NestedNameSpecifier::Kind::Type:
6519 return Visit(T: QualType(NNS.getAsType(), 0));
6520 }
6521 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6522}
6523
6524bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6525 const HLSLAttributedResourceType *T) {
6526 if (T->hasContainedType() && Visit(T: T->getContainedType()))
6527 return true;
6528 return Visit(T: T->getWrappedType());
6529}
6530
6531bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6532 const HLSLInlineSpirvType *T) {
6533 for (auto &Operand : T->getOperands())
6534 if (Operand.isConstant() && Operand.isLiteral())
6535 if (Visit(T: Operand.getResultType()))
6536 return true;
6537 return false;
6538}
6539
6540bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6541 assert(ArgInfo && "invalid TypeSourceInfo");
6542 QualType Arg = ArgInfo->getType();
6543 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6544 QualType CanonArg = Context.getCanonicalType(T: Arg);
6545
6546 if (CanonArg->isVariablyModifiedType()) {
6547 return Diag(Loc: SR.getBegin(), DiagID: diag::err_variably_modified_template_arg) << Arg;
6548 } else if (Context.hasSameUnqualifiedType(T1: Arg, T2: Context.OverloadTy)) {
6549 return Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_overload_type) << SR;
6550 }
6551
6552 // C++03 [temp.arg.type]p2:
6553 // A local type, a type with no linkage, an unnamed type or a type
6554 // compounded from any of these types shall not be used as a
6555 // template-argument for a template type-parameter.
6556 //
6557 // C++11 allows these, and even in C++03 we allow them as an extension with
6558 // a warning.
6559 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6560 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6561 (void)Finder.Visit(T: CanonArg);
6562 }
6563
6564 return false;
6565}
6566
6567enum NullPointerValueKind {
6568 NPV_NotNullPointer,
6569 NPV_NullPointer,
6570 NPV_Error
6571};
6572
6573/// Determine whether the given template argument is a null pointer
6574/// value of the appropriate type.
6575static NullPointerValueKind
6576isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param,
6577 QualType ParamType, Expr *Arg,
6578 Decl *Entity = nullptr) {
6579 if (Arg->isValueDependent() || Arg->isTypeDependent())
6580 return NPV_NotNullPointer;
6581
6582 // dllimport'd entities aren't constant but are available inside of template
6583 // arguments.
6584 if (Entity && Entity->hasAttr<DLLImportAttr>())
6585 return NPV_NotNullPointer;
6586
6587 if (!S.isCompleteType(Loc: Arg->getExprLoc(), T: ParamType))
6588 llvm_unreachable(
6589 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6590
6591 if (!S.getLangOpts().CPlusPlus11)
6592 return NPV_NotNullPointer;
6593
6594 // Determine whether we have a constant expression.
6595 ExprResult ArgRV = S.DefaultFunctionArrayConversion(E: Arg);
6596 if (ArgRV.isInvalid())
6597 return NPV_Error;
6598 Arg = ArgRV.get();
6599
6600 Expr::EvalResult EvalResult;
6601 SmallVector<PartialDiagnosticAt, 8> Notes;
6602 EvalResult.Diag = &Notes;
6603 if (!Arg->EvaluateAsRValue(Result&: EvalResult, Ctx: S.Context) ||
6604 EvalResult.HasSideEffects) {
6605 SourceLocation DiagLoc = Arg->getExprLoc();
6606
6607 // If our only note is the usual "invalid subexpression" note, just point
6608 // the caret at its location rather than producing an essentially
6609 // redundant note.
6610 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6611 diag::note_invalid_subexpr_in_const_expr) {
6612 DiagLoc = Notes[0].first;
6613 Notes.clear();
6614 }
6615
6616 S.Diag(Loc: DiagLoc, DiagID: diag::err_template_arg_not_address_constant)
6617 << Arg->getType() << Arg->getSourceRange();
6618 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6619 S.Diag(Loc: Notes[I].first, PD: Notes[I].second);
6620
6621 S.NoteTemplateParameterLocation(Decl: *Param);
6622 return NPV_Error;
6623 }
6624
6625 // C++11 [temp.arg.nontype]p1:
6626 // - an address constant expression of type std::nullptr_t
6627 if (Arg->getType()->isNullPtrType())
6628 return NPV_NullPointer;
6629
6630 // - a constant expression that evaluates to a null pointer value (4.10); or
6631 // - a constant expression that evaluates to a null member pointer value
6632 // (4.11); or
6633 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6634 (EvalResult.Val.isMemberPointer() &&
6635 !EvalResult.Val.getMemberPointerDecl())) {
6636 // If our expression has an appropriate type, we've succeeded.
6637 bool ObjCLifetimeConversion;
6638 if (S.Context.hasSameUnqualifiedType(T1: Arg->getType(), T2: ParamType) ||
6639 S.IsQualificationConversion(FromType: Arg->getType(), ToType: ParamType, CStyle: false,
6640 ObjCLifetimeConversion))
6641 return NPV_NullPointer;
6642
6643 // The types didn't match, but we know we got a null pointer; complain,
6644 // then recover as if the types were correct.
6645 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_wrongtype_null_constant)
6646 << Arg->getType() << ParamType << Arg->getSourceRange();
6647 S.NoteTemplateParameterLocation(Decl: *Param);
6648 return NPV_NullPointer;
6649 }
6650
6651 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6652 // We found a pointer that isn't null, but doesn't refer to an object.
6653 // We could just return NPV_NotNullPointer, but we can print a better
6654 // message with the information we have here.
6655 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_invalid)
6656 << EvalResult.Val.getAsString(Ctx: S.Context, Ty: ParamType);
6657 S.NoteTemplateParameterLocation(Decl: *Param);
6658 return NPV_Error;
6659 }
6660
6661 // If we don't have a null pointer value, but we do have a NULL pointer
6662 // constant, suggest a cast to the appropriate type.
6663 if (Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_NeverValueDependent)) {
6664 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6665 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_untyped_null_constant)
6666 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code)
6667 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: Arg->getEndLoc()),
6668 Code: ")");
6669 S.NoteTemplateParameterLocation(Decl: *Param);
6670 return NPV_NullPointer;
6671 }
6672
6673 // FIXME: If we ever want to support general, address-constant expressions
6674 // as non-type template arguments, we should return the ExprResult here to
6675 // be interpreted by the caller.
6676 return NPV_NotNullPointer;
6677}
6678
6679/// Checks whether the given template argument is compatible with its
6680/// template parameter.
6681static bool
6682CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param,
6683 QualType ParamType, Expr *ArgIn,
6684 Expr *Arg, QualType ArgType) {
6685 bool ObjCLifetimeConversion;
6686 if (ParamType->isPointerType() &&
6687 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6688 S.IsQualificationConversion(FromType: ArgType, ToType: ParamType, CStyle: false,
6689 ObjCLifetimeConversion)) {
6690 // For pointer-to-object types, qualification conversions are
6691 // permitted.
6692 } else {
6693 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6694 if (!ParamRef->getPointeeType()->isFunctionType()) {
6695 // C++ [temp.arg.nontype]p5b3:
6696 // For a non-type template-parameter of type reference to
6697 // object, no conversions apply. The type referred to by the
6698 // reference may be more cv-qualified than the (otherwise
6699 // identical) type of the template- argument. The
6700 // template-parameter is bound directly to the
6701 // template-argument, which shall be an lvalue.
6702
6703 // FIXME: Other qualifiers?
6704 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6705 unsigned ArgQuals = ArgType.getCVRQualifiers();
6706
6707 if ((ParamQuals | ArgQuals) != ParamQuals) {
6708 S.Diag(Loc: Arg->getBeginLoc(),
6709 DiagID: diag::err_template_arg_ref_bind_ignores_quals)
6710 << ParamType << Arg->getType() << Arg->getSourceRange();
6711 S.NoteTemplateParameterLocation(Decl: *Param);
6712 return true;
6713 }
6714 }
6715 }
6716
6717 // At this point, the template argument refers to an object or
6718 // function with external linkage. We now need to check whether the
6719 // argument and parameter types are compatible.
6720 if (!S.Context.hasSameUnqualifiedType(T1: ArgType,
6721 T2: ParamType.getNonReferenceType())) {
6722 // We can't perform this conversion or binding.
6723 if (ParamType->isReferenceType())
6724 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_no_ref_bind)
6725 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6726 else
6727 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
6728 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6729 S.NoteTemplateParameterLocation(Decl: *Param);
6730 return true;
6731 }
6732 }
6733
6734 return false;
6735}
6736
6737/// Checks whether the given template argument is the address
6738/// of an object or function according to C++ [temp.arg.nontype]p1.
6739static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6740 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6741 bool IsSpecified, TemplateArgument &SugaredConverted,
6742 TemplateArgument &CanonicalConverted) {
6743 Expr *Arg = ArgIn;
6744 QualType ArgType = Arg->getType();
6745
6746 bool AddressTaken = false;
6747 SourceLocation AddrOpLoc;
6748 if (S.getLangOpts().MicrosoftExt) {
6749 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6750 // dereference and address-of operators.
6751 Arg = Arg->IgnoreParenCasts();
6752
6753 bool ExtWarnMSTemplateArg = false;
6754 UnaryOperatorKind FirstOpKind;
6755 SourceLocation FirstOpLoc;
6756 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6757 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6758 if (UnOpKind == UO_Deref)
6759 ExtWarnMSTemplateArg = true;
6760 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6761 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6762 if (!AddrOpLoc.isValid()) {
6763 FirstOpKind = UnOpKind;
6764 FirstOpLoc = UnOp->getOperatorLoc();
6765 }
6766 } else
6767 break;
6768 }
6769 if (FirstOpLoc.isValid()) {
6770 if (ExtWarnMSTemplateArg)
6771 S.Diag(Loc: ArgIn->getBeginLoc(), DiagID: diag::ext_ms_deref_template_argument)
6772 << ArgIn->getSourceRange();
6773
6774 if (FirstOpKind == UO_AddrOf)
6775 AddressTaken = true;
6776 else if (Arg->getType()->isPointerType()) {
6777 // We cannot let pointers get dereferenced here, that is obviously not a
6778 // constant expression.
6779 assert(FirstOpKind == UO_Deref);
6780 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6781 << Arg->getSourceRange();
6782 }
6783 }
6784 } else {
6785 // See through any implicit casts we added to fix the type.
6786 // Also ignore parentheses for deduced template arguments.
6787 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6788
6789 // C++ [temp.arg.nontype]p1:
6790 //
6791 // A template-argument for a non-type, non-template
6792 // template-parameter shall be one of: [...]
6793 //
6794 // -- the address of an object or function with external
6795 // linkage, including function templates and function
6796 // template-ids but excluding non-static class members,
6797 // expressed as & id-expression where the & is optional if
6798 // the name refers to a function or array, or if the
6799 // corresponding template-parameter is a reference; or
6800
6801 // In C++98/03 mode, give an extension warning on any extra parentheses.
6802 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6803 if (IsSpecified) {
6804 bool ExtraParens = false;
6805 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6806 if (!ExtraParens) {
6807 S.DiagCompat(Loc: Arg->getBeginLoc(),
6808 CompatDiagId: diag_compat::template_arg_extra_parens)
6809 << Arg->getSourceRange();
6810 ExtraParens = true;
6811 }
6812
6813 Arg = Parens->getSubExpr();
6814 }
6815 }
6816
6817 while (SubstNonTypeTemplateParmExpr *subst =
6818 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6819 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6820
6821 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6822 if (UnOp->getOpcode() == UO_AddrOf) {
6823 Arg = UnOp->getSubExpr();
6824 AddressTaken = true;
6825 AddrOpLoc = UnOp->getOperatorLoc();
6826 }
6827 }
6828
6829 while (SubstNonTypeTemplateParmExpr *subst =
6830 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6831 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6832 }
6833
6834 ValueDecl *Entity = nullptr;
6835 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg))
6836 Entity = DRE->getDecl();
6837 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Val: Arg))
6838 Entity = CUE->getGuidDecl();
6839
6840 // If our parameter has pointer type, check for a null template value.
6841 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6842 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ArgIn,
6843 Entity)) {
6844 case NPV_NullPointer:
6845 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
6846 SugaredConverted = TemplateArgument(ParamType,
6847 /*isNullPtr=*/true);
6848 CanonicalConverted =
6849 TemplateArgument(S.Context.getCanonicalType(T: ParamType),
6850 /*isNullPtr=*/true);
6851 return false;
6852
6853 case NPV_Error:
6854 return true;
6855
6856 case NPV_NotNullPointer:
6857 break;
6858 }
6859 }
6860
6861 // Stop checking the precise nature of the argument if it is value dependent,
6862 // it should be checked when instantiated.
6863 if (Arg->isValueDependent()) {
6864 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6865 CanonicalConverted =
6866 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6867 return false;
6868 }
6869
6870 if (!Entity) {
6871 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6872 << Arg->getSourceRange();
6873 S.NoteTemplateParameterLocation(Decl: *Param);
6874 return true;
6875 }
6876
6877 // Cannot refer to non-static data members
6878 if (isa<FieldDecl>(Val: Entity) || isa<IndirectFieldDecl>(Val: Entity)) {
6879 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_field)
6880 << Entity << Arg->getSourceRange();
6881 S.NoteTemplateParameterLocation(Decl: *Param);
6882 return true;
6883 }
6884
6885 // Cannot refer to non-static member functions
6886 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Entity)) {
6887 if (!Method->isStatic()) {
6888 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_method)
6889 << Method << Arg->getSourceRange();
6890 S.NoteTemplateParameterLocation(Decl: *Param);
6891 return true;
6892 }
6893 }
6894
6895 FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Entity);
6896 VarDecl *Var = dyn_cast<VarDecl>(Val: Entity);
6897 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Val: Entity);
6898
6899 // A non-type template argument must refer to an object or function.
6900 if (!Func && !Var && !Guid) {
6901 // We found something, but we don't know specifically what it is.
6902 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_object_or_func)
6903 << Arg->getSourceRange();
6904 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_refers_here);
6905 return true;
6906 }
6907
6908 // Address / reference template args must have external linkage in C++98.
6909 if (Entity->getFormalLinkage() == Linkage::Internal) {
6910 S.Diag(Loc: Arg->getBeginLoc(),
6911 DiagID: S.getLangOpts().CPlusPlus11
6912 ? diag::warn_cxx98_compat_template_arg_object_internal
6913 : diag::ext_template_arg_object_internal)
6914 << !Func << Entity << Arg->getSourceRange();
6915 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6916 << !Func;
6917 } else if (!Entity->hasLinkage()) {
6918 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_object_no_linkage)
6919 << !Func << Entity << Arg->getSourceRange();
6920 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6921 << !Func;
6922 return true;
6923 }
6924
6925 if (Var) {
6926 // A value of reference type is not an object.
6927 if (Var->getType()->isReferenceType()) {
6928 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_reference_var)
6929 << Var->getType() << Arg->getSourceRange();
6930 S.NoteTemplateParameterLocation(Decl: *Param);
6931 return true;
6932 }
6933
6934 // A template argument must have static storage duration.
6935 if (Var->getTLSKind()) {
6936 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_thread_local)
6937 << Arg->getSourceRange();
6938 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_template_arg_refers_here);
6939 return true;
6940 }
6941 }
6942
6943 if (AddressTaken && ParamType->isReferenceType()) {
6944 // If we originally had an address-of operator, but the
6945 // parameter has reference type, complain and (if things look
6946 // like they will work) drop the address-of operator.
6947 if (!S.Context.hasSameUnqualifiedType(T1: Entity->getType(),
6948 T2: ParamType.getNonReferenceType())) {
6949 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6950 << ParamType;
6951 S.NoteTemplateParameterLocation(Decl: *Param);
6952 return true;
6953 }
6954
6955 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6956 << ParamType
6957 << FixItHint::CreateRemoval(RemoveRange: AddrOpLoc);
6958 S.NoteTemplateParameterLocation(Decl: *Param);
6959
6960 ArgType = Entity->getType();
6961 }
6962
6963 // If the template parameter has pointer type, either we must have taken the
6964 // address or the argument must decay to a pointer.
6965 if (!AddressTaken && ParamType->isPointerType()) {
6966 if (Func) {
6967 // Function-to-pointer decay.
6968 ArgType = S.Context.getPointerType(T: Func->getType());
6969 } else if (Entity->getType()->isArrayType()) {
6970 // Array-to-pointer decay.
6971 ArgType = S.Context.getArrayDecayedType(T: Entity->getType());
6972 } else {
6973 // If the template parameter has pointer type but the address of
6974 // this object was not taken, complain and (possibly) recover by
6975 // taking the address of the entity.
6976 ArgType = S.Context.getPointerType(T: Entity->getType());
6977 if (!S.Context.hasSameUnqualifiedType(T1: ArgType, T2: ParamType)) {
6978 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6979 << ParamType;
6980 S.NoteTemplateParameterLocation(Decl: *Param);
6981 return true;
6982 }
6983
6984 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6985 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code: "&");
6986
6987 S.NoteTemplateParameterLocation(Decl: *Param);
6988 }
6989 }
6990
6991 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6992 Arg, ArgType))
6993 return true;
6994
6995 // Create the template argument.
6996 SugaredConverted = TemplateArgument(Entity, ParamType);
6997 CanonicalConverted =
6998 TemplateArgument(cast<ValueDecl>(Val: Entity->getCanonicalDecl()),
6999 S.Context.getCanonicalType(T: ParamType));
7000 S.MarkAnyDeclReferenced(Loc: Arg->getBeginLoc(), D: Entity, MightBeOdrUse: false);
7001 return false;
7002}
7003
7004/// Checks whether the given template argument is a pointer to
7005/// member constant according to C++ [temp.arg.nontype]p1.
7006static bool CheckTemplateArgumentPointerToMember(
7007 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7008 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7009 bool Invalid = false;
7010
7011 Expr *Arg = ResultArg;
7012 bool ObjCLifetimeConversion;
7013
7014 // C++ [temp.arg.nontype]p1:
7015 //
7016 // A template-argument for a non-type, non-template
7017 // template-parameter shall be one of: [...]
7018 //
7019 // -- a pointer to member expressed as described in 5.3.1.
7020 DeclRefExpr *DRE = nullptr;
7021
7022 // In C++98/03 mode, give an extension warning on any extra parentheses.
7023 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7024 bool ExtraParens = false;
7025 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
7026 if (!Invalid && !ExtraParens) {
7027 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
7028 << Arg->getSourceRange();
7029 ExtraParens = true;
7030 }
7031
7032 Arg = Parens->getSubExpr();
7033 }
7034
7035 while (SubstNonTypeTemplateParmExpr *subst =
7036 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
7037 Arg = subst->getReplacement()->IgnoreImpCasts();
7038
7039 // A pointer-to-member constant written &Class::member.
7040 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
7041 if (UnOp->getOpcode() == UO_AddrOf) {
7042 DRE = dyn_cast<DeclRefExpr>(Val: UnOp->getSubExpr());
7043 if (DRE && !DRE->getQualifier())
7044 DRE = nullptr;
7045 }
7046 }
7047 // A constant of pointer-to-member type.
7048 else if ((DRE = dyn_cast<DeclRefExpr>(Val: Arg))) {
7049 ValueDecl *VD = DRE->getDecl();
7050 if (VD->getType()->isMemberPointerType()) {
7051 if (isa<NonTypeTemplateParmDecl>(Val: VD)) {
7052 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7053 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7054 CanonicalConverted =
7055 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7056 } else {
7057 SugaredConverted = TemplateArgument(VD, ParamType);
7058 CanonicalConverted =
7059 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7060 S.Context.getCanonicalType(T: ParamType));
7061 }
7062 return Invalid;
7063 }
7064 }
7065
7066 DRE = nullptr;
7067 }
7068
7069 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7070
7071 // Check for a null pointer value.
7072 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ResultArg,
7073 Entity)) {
7074 case NPV_Error:
7075 return true;
7076 case NPV_NullPointer:
7077 S.Diag(Loc: ResultArg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7078 SugaredConverted = TemplateArgument(ParamType,
7079 /*isNullPtr*/ true);
7080 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(T: ParamType),
7081 /*isNullPtr*/ true);
7082 return false;
7083 case NPV_NotNullPointer:
7084 break;
7085 }
7086
7087 if (S.IsQualificationConversion(FromType: ResultArg->getType(),
7088 ToType: ParamType.getNonReferenceType(), CStyle: false,
7089 ObjCLifetimeConversion)) {
7090 ResultArg = S.ImpCastExprToType(E: ResultArg, Type: ParamType, CK: CK_NoOp,
7091 VK: ResultArg->getValueKind())
7092 .get();
7093 } else if (!S.Context.hasSameUnqualifiedType(
7094 T1: ResultArg->getType(), T2: ParamType.getNonReferenceType())) {
7095 // We can't perform this conversion.
7096 S.Diag(Loc: ResultArg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
7097 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7098 S.NoteTemplateParameterLocation(Decl: *Param);
7099 return true;
7100 }
7101
7102 if (!DRE)
7103 return S.Diag(Loc: Arg->getBeginLoc(),
7104 DiagID: diag::err_template_arg_not_pointer_to_member_form)
7105 << Arg->getSourceRange();
7106
7107 if (isa<FieldDecl>(Val: DRE->getDecl()) ||
7108 isa<IndirectFieldDecl>(Val: DRE->getDecl()) ||
7109 isa<CXXMethodDecl>(Val: DRE->getDecl())) {
7110 assert((isa<FieldDecl>(DRE->getDecl()) ||
7111 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7112 cast<CXXMethodDecl>(DRE->getDecl())
7113 ->isImplicitObjectMemberFunction()) &&
7114 "Only non-static member pointers can make it here");
7115
7116 // Okay: this is the address of a non-static member, and therefore
7117 // a member pointer constant.
7118 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7119 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7120 CanonicalConverted =
7121 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7122 } else {
7123 ValueDecl *D = DRE->getDecl();
7124 SugaredConverted = TemplateArgument(D, ParamType);
7125 CanonicalConverted =
7126 TemplateArgument(cast<ValueDecl>(Val: D->getCanonicalDecl()),
7127 S.Context.getCanonicalType(T: ParamType));
7128 }
7129 return Invalid;
7130 }
7131
7132 // We found something else, but we don't know specifically what it is.
7133 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_pointer_to_member_form)
7134 << Arg->getSourceRange();
7135 S.Diag(Loc: DRE->getDecl()->getLocation(), DiagID: diag::note_template_arg_refers_here);
7136 return true;
7137}
7138
7139/// Check a template argument against its corresponding
7140/// non-type template parameter.
7141///
7142/// This routine implements the semantics of C++ [temp.arg.nontype].
7143/// If an error occurred, it returns ExprError(); otherwise, it
7144/// returns the converted template argument. \p ParamType is the
7145/// type of the non-type template parameter after it has been instantiated.
7146ExprResult Sema::CheckTemplateArgument(NamedDecl *Param, QualType ParamType,
7147 Expr *Arg,
7148 TemplateArgument &SugaredConverted,
7149 TemplateArgument &CanonicalConverted,
7150 bool StrictCheck,
7151 CheckTemplateArgumentKind CTAK) {
7152 SourceLocation StartLoc = Arg->getBeginLoc();
7153 auto *ArgPE = dyn_cast<PackExpansionExpr>(Val: Arg);
7154 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7155 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7156 DeductionArg = NewDeductionArg;
7157 if (ArgPE) {
7158 // Recreate a pack expansion if we unwrapped one.
7159 Arg = new (Context) PackExpansionExpr(
7160 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7161 } else {
7162 Arg = DeductionArg;
7163 }
7164 };
7165
7166 // If the parameter type somehow involves auto, deduce the type now.
7167 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7168 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7169 if (IsDeduced) {
7170 // When checking a deduced template argument, deduce from its type even if
7171 // the type is dependent, in order to check the types of non-type template
7172 // arguments line up properly in partial ordering.
7173 TypeSourceInfo *TSI =
7174 Context.getTrivialTypeSourceInfo(T: ParamType, Loc: Param->getLocation());
7175 if (isa<DeducedTemplateSpecializationType>(Val: DeducedT)) {
7176 InitializedEntity Entity =
7177 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7178 InitializationKind Kind = InitializationKind::CreateForInit(
7179 Loc: DeductionArg->getBeginLoc(), /*DirectInit*/false, Init: DeductionArg);
7180 Expr *Inits[1] = {DeductionArg};
7181 ParamType =
7182 DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind, Init: Inits);
7183 if (ParamType.isNull())
7184 return ExprError();
7185 } else {
7186 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7187 Param->getTemplateDepth() + 1);
7188 ParamType = QualType();
7189 TemplateDeductionResult Result =
7190 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeductionArg, Result&: ParamType, Info,
7191 /*DependentDeduction=*/true,
7192 // We do not check constraints right now because the
7193 // immediately-declared constraint of the auto type is
7194 // also an associated constraint, and will be checked
7195 // along with the other associated constraints after
7196 // checking the template argument list.
7197 /*IgnoreConstraints=*/true);
7198 if (Result != TemplateDeductionResult::Success) {
7199 ParamType = TSI->getType();
7200 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7201 if (Result == TemplateDeductionResult::AlreadyDiagnosed)
7202 return ExprError();
7203 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param))
7204 Diag(Loc: Arg->getExprLoc(),
7205 DiagID: diag::err_non_type_template_parm_type_deduction_failure)
7206 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7207 << Arg->getSourceRange();
7208 NoteTemplateParameterLocation(Decl: *Param);
7209 return ExprError();
7210 }
7211 ParamType = SubstAutoTypeDependent(TypeWithAuto: ParamType);
7212 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7213 }
7214 }
7215 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7216 // an error. The error message normally references the parameter
7217 // declaration, but here we'll pass the argument location because that's
7218 // where the parameter type is deduced.
7219 ParamType = CheckNonTypeTemplateParameterType(T: ParamType, Loc: Arg->getExprLoc());
7220 if (ParamType.isNull()) {
7221 NoteTemplateParameterLocation(Decl: *Param);
7222 return ExprError();
7223 }
7224 }
7225
7226 // We should have already dropped all cv-qualifiers by now.
7227 assert(!ParamType.hasQualifiers() &&
7228 "non-type template parameter type cannot be qualified");
7229
7230 // If either the parameter has a dependent type or the argument is
7231 // type-dependent, there's nothing we can check now.
7232 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7233 // Force the argument to the type of the parameter to maintain invariants.
7234 if (!IsDeduced) {
7235 ExprResult E = ImpCastExprToType(
7236 E: DeductionArg, Type: ParamType.getNonLValueExprType(Context), CK: CK_Dependent,
7237 VK: ParamType->isLValueReferenceType() ? VK_LValue
7238 : ParamType->isRValueReferenceType() ? VK_XValue
7239 : VK_PRValue);
7240 if (E.isInvalid())
7241 return ExprError();
7242 setDeductionArg(E.get());
7243 }
7244 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7245 CanonicalConverted = TemplateArgument(
7246 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7247 return Arg;
7248 }
7249
7250 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7251 if (CTAK == CTAK_Deduced && !StrictCheck &&
7252 (ParamType->isReferenceType()
7253 ? !Context.hasSameType(T1: ParamType.getNonReferenceType(),
7254 T2: DeductionArg->getType())
7255 : !Context.hasSameUnqualifiedType(T1: ParamType,
7256 T2: DeductionArg->getType()))) {
7257 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7258 // we should actually be checking the type of the template argument in P,
7259 // not the type of the template argument deduced from A, against the
7260 // template parameter type.
7261 Diag(Loc: StartLoc, DiagID: diag::err_deduced_non_type_template_arg_type_mismatch)
7262 << Arg->getType() << ParamType.getUnqualifiedType();
7263 NoteTemplateParameterLocation(Decl: *Param);
7264 return ExprError();
7265 }
7266
7267 // If the argument is a pack expansion, we don't know how many times it would
7268 // expand. If we continue checking the argument, this will make the template
7269 // definition ill-formed if it would be ill-formed for any number of
7270 // expansions during instantiation time. When partial ordering or matching
7271 // template template parameters, this is exactly what we want. Otherwise, the
7272 // normal template rules apply: we accept the template if it would be valid
7273 // for any number of expansions (i.e. none).
7274 if (ArgPE && !StrictCheck) {
7275 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7276 CanonicalConverted = TemplateArgument(
7277 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7278 return Arg;
7279 }
7280
7281 // Avoid making a copy when initializing a template parameter of class type
7282 // from a template parameter object of the same type. This is going beyond
7283 // the standard, but is required for soundness: in
7284 // template<A a> struct X { X *p; X<a> *q; };
7285 // ... we need p and q to have the same type.
7286 //
7287 // Similarly, don't inject a call to a copy constructor when initializing
7288 // from a template parameter of the same type.
7289 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7290 if (ParamType->isRecordType() && isa<DeclRefExpr>(Val: InnerArg) &&
7291 Context.hasSameUnqualifiedType(T1: ParamType, T2: InnerArg->getType())) {
7292 NamedDecl *ND = cast<DeclRefExpr>(Val: InnerArg)->getDecl();
7293 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: ND)) {
7294
7295 SugaredConverted = TemplateArgument(TPO, ParamType);
7296 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7297 ParamType.getCanonicalType());
7298 return Arg;
7299 }
7300 if (isa<NonTypeTemplateParmDecl>(Val: ND)) {
7301 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7302 CanonicalConverted =
7303 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7304 return Arg;
7305 }
7306 }
7307
7308 // The initialization of the parameter from the argument is
7309 // a constant-evaluated context.
7310 EnterExpressionEvaluationContext ConstantEvaluated(
7311 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7312
7313 bool IsConvertedConstantExpression = true;
7314 if (isa<InitListExpr>(Val: DeductionArg) || ParamType->isRecordType()) {
7315 InitializationKind Kind = InitializationKind::CreateForInit(
7316 Loc: StartLoc, /*DirectInit=*/false, Init: DeductionArg);
7317 Expr *Inits[1] = {DeductionArg};
7318 InitializedEntity Entity =
7319 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7320 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7321 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Inits);
7322 if (Result.isInvalid() || !Result.get())
7323 return ExprError();
7324 Result = ActOnConstantExpression(Res: Result.get());
7325 if (Result.isInvalid() || !Result.get())
7326 return ExprError();
7327 setDeductionArg(ActOnFinishFullExpr(Expr: Result.get(), CC: Arg->getBeginLoc(),
7328 /*DiscardedValue=*/false,
7329 /*IsConstexpr=*/true,
7330 /*IsTemplateArgument=*/true)
7331 .get());
7332 IsConvertedConstantExpression = false;
7333 }
7334
7335 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7336 // C++17 [temp.arg.nontype]p1:
7337 // A template-argument for a non-type template parameter shall be
7338 // a converted constant expression of the type of the template-parameter.
7339 APValue Value;
7340 ExprResult ArgResult;
7341 if (IsConvertedConstantExpression) {
7342 ArgResult = BuildConvertedConstantExpression(
7343 From: DeductionArg, T: ParamType,
7344 CCE: StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Dest: Param);
7345 assert(!ArgResult.isUnset());
7346 if (ArgResult.isInvalid()) {
7347 NoteTemplateParameterLocation(Decl: *Param);
7348 return ExprError();
7349 }
7350 } else {
7351 ArgResult = DeductionArg;
7352 }
7353
7354 // For a value-dependent argument, CheckConvertedConstantExpression is
7355 // permitted (and expected) to be unable to determine a value.
7356 if (ArgResult.get()->isValueDependent()) {
7357 setDeductionArg(ArgResult.get());
7358 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7359 CanonicalConverted =
7360 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7361 return Arg;
7362 }
7363
7364 APValue PreNarrowingValue;
7365 ArgResult = EvaluateConvertedConstantExpression(
7366 E: ArgResult.get(), T: ParamType, Value, CCE: CCEKind::TemplateArg, /*RequireInt=*/
7367 false, PreNarrowingValue);
7368 if (ArgResult.isInvalid())
7369 return ExprError();
7370 setDeductionArg(ArgResult.get());
7371
7372 if (Value.isLValue()) {
7373 APValue::LValueBase Base = Value.getLValueBase();
7374 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7375 // For a non-type template-parameter of pointer or reference type,
7376 // the value of the constant expression shall not refer to
7377 assert(ParamType->isPointerOrReferenceType() ||
7378 ParamType->isNullPtrType());
7379 // -- a temporary object
7380 // -- a string literal
7381 // -- the result of a typeid expression, or
7382 // -- a predefined __func__ variable
7383 if (Base &&
7384 (!VD ||
7385 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(Val: VD))) {
7386 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
7387 << Arg->getSourceRange();
7388 return ExprError();
7389 }
7390
7391 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7392 VD->getType()->isArrayType() &&
7393 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7394 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7395 if (ArgPE) {
7396 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7397 CanonicalConverted =
7398 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7399 } else {
7400 SugaredConverted = TemplateArgument(VD, ParamType);
7401 CanonicalConverted =
7402 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7403 ParamType.getCanonicalType());
7404 }
7405 return Arg;
7406 }
7407
7408 // -- a subobject [until C++20]
7409 if (!getLangOpts().CPlusPlus20) {
7410 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7411 Value.isLValueOnePastTheEnd()) {
7412 Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_subobject)
7413 << Value.getAsString(Ctx: Context, Ty: ParamType);
7414 return ExprError();
7415 }
7416 assert((VD || !ParamType->isReferenceType()) &&
7417 "null reference should not be a constant expression");
7418 assert((!VD || !ParamType->isNullPtrType()) &&
7419 "non-null value of type nullptr_t?");
7420 }
7421 }
7422
7423 if (Value.isAddrLabelDiff())
7424 return Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_addr_label_diff);
7425
7426 if (ArgPE) {
7427 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7428 CanonicalConverted =
7429 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7430 } else {
7431 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7432 CanonicalConverted =
7433 TemplateArgument(Context, ParamType.getCanonicalType(), Value);
7434 }
7435 return Arg;
7436 }
7437
7438 // These should have all been handled above using the C++17 rules.
7439 assert(!ArgPE && !StrictCheck);
7440
7441 // C++ [temp.arg.nontype]p5:
7442 // The following conversions are performed on each expression used
7443 // as a non-type template-argument. If a non-type
7444 // template-argument cannot be converted to the type of the
7445 // corresponding template-parameter then the program is
7446 // ill-formed.
7447 if (ParamType->isIntegralOrEnumerationType()) {
7448 // C++11:
7449 // -- for a non-type template-parameter of integral or
7450 // enumeration type, conversions permitted in a converted
7451 // constant expression are applied.
7452 //
7453 // C++98:
7454 // -- for a non-type template-parameter of integral or
7455 // enumeration type, integral promotions (4.5) and integral
7456 // conversions (4.7) are applied.
7457
7458 if (getLangOpts().CPlusPlus11) {
7459 // C++ [temp.arg.nontype]p1:
7460 // A template-argument for a non-type, non-template template-parameter
7461 // shall be one of:
7462 //
7463 // -- for a non-type template-parameter of integral or enumeration
7464 // type, a converted constant expression of the type of the
7465 // template-parameter; or
7466 llvm::APSInt Value;
7467 ExprResult ArgResult = CheckConvertedConstantExpression(
7468 From: Arg, T: ParamType, Value, CCE: CCEKind::TemplateArg);
7469 if (ArgResult.isInvalid())
7470 return ExprError();
7471 Arg = ArgResult.get();
7472
7473 // We can't check arbitrary value-dependent arguments.
7474 if (Arg->isValueDependent()) {
7475 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7476 CanonicalConverted =
7477 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7478 return Arg;
7479 }
7480
7481 // Widen the argument value to sizeof(parameter type). This is almost
7482 // always a no-op, except when the parameter type is bool. In
7483 // that case, this may extend the argument from 1 bit to 8 bits.
7484 QualType IntegerType = ParamType;
7485 if (const auto *ED = IntegerType->getAsEnumDecl())
7486 IntegerType = ED->getIntegerType();
7487 Value = Value.extOrTrunc(width: IntegerType->isBitIntType()
7488 ? Context.getIntWidth(T: IntegerType)
7489 : Context.getTypeSize(T: IntegerType));
7490
7491 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7492 CanonicalConverted =
7493 TemplateArgument(Context, Value, Context.getCanonicalType(T: ParamType));
7494 return Arg;
7495 }
7496
7497 ExprResult ArgResult = DefaultLvalueConversion(E: Arg);
7498 if (ArgResult.isInvalid())
7499 return ExprError();
7500 Arg = ArgResult.get();
7501
7502 QualType ArgType = Arg->getType();
7503
7504 // C++ [temp.arg.nontype]p1:
7505 // A template-argument for a non-type, non-template
7506 // template-parameter shall be one of:
7507 //
7508 // -- an integral constant-expression of integral or enumeration
7509 // type; or
7510 // -- the name of a non-type template-parameter; or
7511 llvm::APSInt Value;
7512 if (!ArgType->isIntegralOrEnumerationType()) {
7513 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_integral_or_enumeral)
7514 << ArgType << Arg->getSourceRange();
7515 NoteTemplateParameterLocation(Decl: *Param);
7516 return ExprError();
7517 }
7518 if (!Arg->isValueDependent()) {
7519 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7520 QualType T;
7521
7522 public:
7523 TmplArgICEDiagnoser(QualType T) : T(T) { }
7524
7525 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7526 SourceLocation Loc) override {
7527 return S.Diag(Loc, DiagID: diag::err_template_arg_not_ice) << T;
7528 }
7529 } Diagnoser(ArgType);
7530
7531 Arg = VerifyIntegerConstantExpression(E: Arg, Result: &Value, Diagnoser).get();
7532 if (!Arg)
7533 return ExprError();
7534 }
7535
7536 // From here on out, all we care about is the unqualified form
7537 // of the argument type.
7538 ArgType = ArgType.getUnqualifiedType();
7539
7540 // Try to convert the argument to the parameter's type.
7541 if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
7542 // Okay: no conversion necessary
7543 } else if (ParamType->isBooleanType()) {
7544 // This is an integral-to-boolean conversion.
7545 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralToBoolean).get();
7546 } else if (IsIntegralPromotion(From: Arg, FromType: ArgType, ToType: ParamType) ||
7547 !ParamType->isEnumeralType()) {
7548 // This is an integral promotion or conversion.
7549 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralCast).get();
7550 } else {
7551 // We can't perform this conversion.
7552 Diag(Loc: StartLoc, DiagID: diag::err_template_arg_not_convertible)
7553 << Arg->getType() << ParamType << Arg->getSourceRange();
7554 NoteTemplateParameterLocation(Decl: *Param);
7555 return ExprError();
7556 }
7557
7558 // Add the value of this argument to the list of converted
7559 // arguments. We use the bitwidth and signedness of the template
7560 // parameter.
7561 if (Arg->isValueDependent()) {
7562 // The argument is value-dependent. Create a new
7563 // TemplateArgument with the converted expression.
7564 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7565 CanonicalConverted =
7566 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7567 return Arg;
7568 }
7569
7570 QualType IntegerType = ParamType;
7571 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7572 IntegerType = ED->getIntegerType();
7573 }
7574
7575 if (ParamType->isBooleanType()) {
7576 // Value must be zero or one.
7577 Value = Value != 0;
7578 unsigned AllowedBits = Context.getTypeSize(T: IntegerType);
7579 if (Value.getBitWidth() != AllowedBits)
7580 Value = Value.extOrTrunc(width: AllowedBits);
7581 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7582 } else {
7583 llvm::APSInt OldValue = Value;
7584
7585 // Coerce the template argument's value to the value it will have
7586 // based on the template parameter's type.
7587 unsigned AllowedBits = IntegerType->isBitIntType()
7588 ? Context.getIntWidth(T: IntegerType)
7589 : Context.getTypeSize(T: IntegerType);
7590 if (Value.getBitWidth() != AllowedBits)
7591 Value = Value.extOrTrunc(width: AllowedBits);
7592 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7593
7594 // Complain if an unsigned parameter received a negative value.
7595 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7596 (OldValue.isSigned() && OldValue.isNegative())) {
7597 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_negative)
7598 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7599 << Arg->getSourceRange();
7600 NoteTemplateParameterLocation(Decl: *Param);
7601 }
7602
7603 // Complain if we overflowed the template parameter's type.
7604 unsigned RequiredBits;
7605 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7606 RequiredBits = OldValue.getActiveBits();
7607 else if (OldValue.isUnsigned())
7608 RequiredBits = OldValue.getActiveBits() + 1;
7609 else
7610 RequiredBits = OldValue.getSignificantBits();
7611 if (RequiredBits > AllowedBits) {
7612 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_too_large)
7613 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7614 << Arg->getSourceRange();
7615 NoteTemplateParameterLocation(Decl: *Param);
7616 }
7617 }
7618
7619 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7620 SugaredConverted = TemplateArgument(Context, Value, T);
7621 CanonicalConverted =
7622 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7623 return Arg;
7624 }
7625
7626 QualType ArgType = Arg->getType();
7627 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7628 bool IsSpecified = CTAK == CTAK_Specified;
7629
7630 // Handle pointer-to-function, reference-to-function, and
7631 // pointer-to-member-function all in (roughly) the same way.
7632 if (// -- For a non-type template-parameter of type pointer to
7633 // function, only the function-to-pointer conversion (4.3) is
7634 // applied. If the template-argument represents a set of
7635 // overloaded functions (or a pointer to such), the matching
7636 // function is selected from the set (13.4).
7637 (ParamType->isPointerType() &&
7638 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7639 // -- For a non-type template-parameter of type reference to
7640 // function, no conversions apply. If the template-argument
7641 // represents a set of overloaded functions, the matching
7642 // function is selected from the set (13.4).
7643 (ParamType->isReferenceType() &&
7644 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7645 // -- For a non-type template-parameter of type pointer to
7646 // member function, no conversions apply. If the
7647 // template-argument represents a set of overloaded member
7648 // functions, the matching member function is selected from
7649 // the set (13.4).
7650 (ParamType->isMemberPointerType() &&
7651 ParamType->castAs<MemberPointerType>()->getPointeeType()
7652 ->isFunctionType())) {
7653
7654 if (Arg->getType() == Context.OverloadTy) {
7655 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg, TargetType: ParamType,
7656 Complain: true,
7657 Found&: FoundResult)) {
7658 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7659 return ExprError();
7660
7661 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7662 if (Res.isInvalid())
7663 return ExprError();
7664 Arg = Res.get();
7665 ArgType = Arg->getType();
7666 } else
7667 return ExprError();
7668 }
7669
7670 if (!ParamType->isMemberPointerType()) {
7671 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7672 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7673 CanonicalConverted))
7674 return ExprError();
7675 return Arg;
7676 }
7677
7678 if (CheckTemplateArgumentPointerToMember(
7679 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7680 return ExprError();
7681 return Arg;
7682 }
7683
7684 if (ParamType->isPointerType()) {
7685 // -- for a non-type template-parameter of type pointer to
7686 // object, qualification conversions (4.4) and the
7687 // array-to-pointer conversion (4.2) are applied.
7688 // C++0x also allows a value of std::nullptr_t.
7689 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7690 "Only object pointers allowed here");
7691
7692 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7693 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7694 CanonicalConverted))
7695 return ExprError();
7696 return Arg;
7697 }
7698
7699 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7700 // -- For a non-type template-parameter of type reference to
7701 // object, no conversions apply. The type referred to by the
7702 // reference may be more cv-qualified than the (otherwise
7703 // identical) type of the template-argument. The
7704 // template-parameter is bound directly to the
7705 // template-argument, which must be an lvalue.
7706 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7707 "Only object references allowed here");
7708
7709 if (Arg->getType() == Context.OverloadTy) {
7710 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg,
7711 TargetType: ParamRefType->getPointeeType(),
7712 Complain: true,
7713 Found&: FoundResult)) {
7714 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7715 return ExprError();
7716 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7717 if (Res.isInvalid())
7718 return ExprError();
7719 Arg = Res.get();
7720 ArgType = Arg->getType();
7721 } else
7722 return ExprError();
7723 }
7724
7725 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7726 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7727 CanonicalConverted))
7728 return ExprError();
7729 return Arg;
7730 }
7731
7732 // Deal with parameters of type std::nullptr_t.
7733 if (ParamType->isNullPtrType()) {
7734 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7735 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7736 CanonicalConverted =
7737 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7738 return Arg;
7739 }
7740
7741 switch (isNullPointerValueTemplateArgument(S&: *this, Param, ParamType, Arg)) {
7742 case NPV_NotNullPointer:
7743 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_not_convertible)
7744 << Arg->getType() << ParamType;
7745 NoteTemplateParameterLocation(Decl: *Param);
7746 return ExprError();
7747
7748 case NPV_Error:
7749 return ExprError();
7750
7751 case NPV_NullPointer:
7752 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7753 SugaredConverted = TemplateArgument(ParamType,
7754 /*isNullPtr=*/true);
7755 CanonicalConverted = TemplateArgument(Context.getCanonicalType(T: ParamType),
7756 /*isNullPtr=*/true);
7757 return Arg;
7758 }
7759 }
7760
7761 // -- For a non-type template-parameter of type pointer to data
7762 // member, qualification conversions (4.4) are applied.
7763 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7764
7765 if (CheckTemplateArgumentPointerToMember(
7766 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7767 return ExprError();
7768 return Arg;
7769}
7770
7771static void DiagnoseTemplateParameterListArityMismatch(
7772 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7773 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7774
7775bool Sema::CheckDeclCompatibleWithTemplateTemplate(
7776 TemplateDecl *Template, TemplateTemplateParmDecl *Param,
7777 const TemplateArgumentLoc &Arg) {
7778 // C++0x [temp.arg.template]p1:
7779 // A template-argument for a template template-parameter shall be
7780 // the name of a class template or an alias template, expressed as an
7781 // id-expression. When the template-argument names a class template, only
7782 // primary class templates are considered when matching the
7783 // template template argument with the corresponding parameter;
7784 // partial specializations are not considered even if their
7785 // parameter lists match that of the template template parameter.
7786 //
7787
7788 TemplateNameKind Kind = TNK_Non_template;
7789 unsigned DiagFoundKind = 0;
7790
7791 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Val: Template)) {
7792 switch (TTP->templateParameterKind()) {
7793 case TemplateNameKind::TNK_Concept_template:
7794 DiagFoundKind = 3;
7795 break;
7796 case TemplateNameKind::TNK_Var_template:
7797 DiagFoundKind = 2;
7798 break;
7799 default:
7800 DiagFoundKind = 1;
7801 break;
7802 }
7803 Kind = TTP->templateParameterKind();
7804 } else if (isa<ConceptDecl>(Val: Template)) {
7805 Kind = TemplateNameKind::TNK_Concept_template;
7806 DiagFoundKind = 3;
7807 } else if (isa<FunctionTemplateDecl>(Val: Template)) {
7808 Kind = TemplateNameKind::TNK_Function_template;
7809 DiagFoundKind = 0;
7810 } else if (isa<VarTemplateDecl>(Val: Template)) {
7811 Kind = TemplateNameKind::TNK_Var_template;
7812 DiagFoundKind = 2;
7813 } else if (isa<ClassTemplateDecl>(Val: Template) ||
7814 isa<TypeAliasTemplateDecl>(Val: Template) ||
7815 isa<BuiltinTemplateDecl>(Val: Template)) {
7816 Kind = TemplateNameKind::TNK_Type_template;
7817 DiagFoundKind = 1;
7818 } else {
7819 assert(false && "Unexpected Decl");
7820 }
7821
7822 if (Kind == Param->templateParameterKind()) {
7823 return true;
7824 }
7825
7826 unsigned DiagKind = 0;
7827 switch (Param->templateParameterKind()) {
7828 case TemplateNameKind::TNK_Concept_template:
7829 DiagKind = 2;
7830 break;
7831 case TemplateNameKind::TNK_Var_template:
7832 DiagKind = 1;
7833 break;
7834 default:
7835 DiagKind = 0;
7836 break;
7837 }
7838 Diag(Loc: Arg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
7839 << DiagKind;
7840 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_arg_refers_to_template_here)
7841 << DiagFoundKind << Template;
7842 return false;
7843}
7844
7845/// Check a template argument against its corresponding
7846/// template template parameter.
7847///
7848/// This routine implements the semantics of C++ [temp.arg.template].
7849/// It returns true if an error occurred, and false otherwise.
7850bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7851 TemplateParameterList *Params,
7852 TemplateArgumentLoc &Arg,
7853 bool PartialOrdering,
7854 bool *StrictPackMatch) {
7855 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7856 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7857 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7858 if (!Template) {
7859 // FIXME: Handle AssumedTemplateNames
7860 // Any dependent template name is fine.
7861 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7862 return false;
7863 }
7864
7865 if (Template->isInvalidDecl())
7866 return true;
7867
7868 if (!CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg)) {
7869 return true;
7870 }
7871
7872 // C++1z [temp.arg.template]p3: (DR 150)
7873 // A template-argument matches a template template-parameter P when P
7874 // is at least as specialized as the template-argument A.
7875 if (!isTemplateTemplateParameterAtLeastAsSpecializedAs(
7876 PParam: Params, PArg: Param, AArg: Template, DefaultArgs, ArgLoc: Arg.getLocation(),
7877 PartialOrdering, StrictPackMatch))
7878 return true;
7879 // P2113
7880 // C++20[temp.func.order]p2
7881 // [...] If both deductions succeed, the partial ordering selects the
7882 // more constrained template (if one exists) as determined below.
7883 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7884 Params->getAssociatedConstraints(AC&: ParamsAC);
7885 // C++20[temp.arg.template]p3
7886 // [...] In this comparison, if P is unconstrained, the constraints on A
7887 // are not considered.
7888 if (ParamsAC.empty())
7889 return false;
7890
7891 Template->getAssociatedConstraints(AC&: TemplateAC);
7892
7893 bool IsParamAtLeastAsConstrained;
7894 if (IsAtLeastAsConstrained(D1: Param, AC1: ParamsAC, D2: Template, AC2: TemplateAC,
7895 Result&: IsParamAtLeastAsConstrained))
7896 return true;
7897 if (!IsParamAtLeastAsConstrained) {
7898 Diag(Loc: Arg.getLocation(),
7899 DiagID: diag::err_template_template_parameter_not_at_least_as_constrained)
7900 << Template << Param << Arg.getSourceRange();
7901 Diag(Loc: Param->getLocation(), DiagID: diag::note_entity_declared_at) << Param;
7902 Diag(Loc: Template->getLocation(), DiagID: diag::note_entity_declared_at) << Template;
7903 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Param, AC1: ParamsAC, D2: Template,
7904 AC2: TemplateAC);
7905 return true;
7906 }
7907 return false;
7908}
7909
7910static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7911 unsigned HereDiagID,
7912 unsigned ExternalDiagID) {
7913 if (Decl.getLocation().isValid())
7914 return S.Diag(Loc: Decl.getLocation(), DiagID: HereDiagID);
7915
7916 SmallString<128> Str;
7917 llvm::raw_svector_ostream Out(Str);
7918 PrintingPolicy PP = S.getPrintingPolicy();
7919 PP.TerseOutput = 1;
7920 Decl.print(Out, Policy: PP);
7921 return S.Diag(Loc: Decl.getLocation(), DiagID: ExternalDiagID) << Out.str();
7922}
7923
7924void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7925 std::optional<SourceRange> ParamRange) {
7926 SemaDiagnosticBuilder DB =
7927 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_decl_here,
7928 ExternalDiagID: diag::note_template_decl_external);
7929 if (ParamRange && ParamRange->isValid()) {
7930 assert(Decl.getLocation().isValid() &&
7931 "Parameter range has location when Decl does not");
7932 DB << *ParamRange;
7933 }
7934}
7935
7936void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7937 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_param_here,
7938 ExternalDiagID: diag::note_template_param_external);
7939}
7940
7941/// Given a non-type template argument that refers to a
7942/// declaration and the type of its corresponding non-type template
7943/// parameter, produce an expression that properly refers to that
7944/// declaration.
7945ExprResult Sema::BuildExpressionFromDeclTemplateArgument(
7946 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
7947 // C++ [temp.param]p8:
7948 //
7949 // A non-type template-parameter of type "array of T" or
7950 // "function returning T" is adjusted to be of type "pointer to
7951 // T" or "pointer to function returning T", respectively.
7952 if (ParamType->isArrayType())
7953 ParamType = Context.getArrayDecayedType(T: ParamType);
7954 else if (ParamType->isFunctionType())
7955 ParamType = Context.getPointerType(T: ParamType);
7956
7957 // For a NULL non-type template argument, return nullptr casted to the
7958 // parameter's type.
7959 if (Arg.getKind() == TemplateArgument::NullPtr) {
7960 return ImpCastExprToType(
7961 E: new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7962 Type: ParamType,
7963 CK: ParamType->getAs<MemberPointerType>()
7964 ? CK_NullToMemberPointer
7965 : CK_NullToPointer);
7966 }
7967 assert(Arg.getKind() == TemplateArgument::Declaration &&
7968 "Only declaration template arguments permitted here");
7969
7970 ValueDecl *VD = Arg.getAsDecl();
7971
7972 CXXScopeSpec SS;
7973 if (ParamType->isMemberPointerType()) {
7974 // If this is a pointer to member, we need to use a qualified name to
7975 // form a suitable pointer-to-member constant.
7976 assert(VD->getDeclContext()->isRecord() &&
7977 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7978 isa<IndirectFieldDecl>(VD)));
7979 CanQualType ClassType =
7980 Context.getCanonicalTagType(TD: cast<RecordDecl>(Val: VD->getDeclContext()));
7981 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7982 SS.MakeTrivial(Context, Qualifier, R: Loc);
7983 }
7984
7985 ExprResult RefExpr = BuildDeclarationNameExpr(
7986 SS, NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
7987 if (RefExpr.isInvalid())
7988 return ExprError();
7989
7990 // For a pointer, the argument declaration is the pointee. Take its address.
7991 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7992 if (ParamType->isPointerType() && !ElemT.isNull() &&
7993 Context.hasSimilarType(T1: ElemT, T2: ParamType->getPointeeType())) {
7994 // Decay an array argument if we want a pointer to its first element.
7995 RefExpr = DefaultFunctionArrayConversion(E: RefExpr.get());
7996 if (RefExpr.isInvalid())
7997 return ExprError();
7998 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7999 // For any other pointer, take the address (or form a pointer-to-member).
8000 RefExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_AddrOf, InputExpr: RefExpr.get());
8001 if (RefExpr.isInvalid())
8002 return ExprError();
8003 } else if (ParamType->isRecordType()) {
8004 assert(isa<TemplateParamObjectDecl>(VD) &&
8005 "arg for class template param not a template parameter object");
8006 // No conversions apply in this case.
8007 return RefExpr;
8008 } else {
8009 assert(ParamType->isReferenceType() &&
8010 "unexpected type for decl template argument");
8011 // If the parameter has reference type, wrap it in paretheses so that this
8012 // expression will have the correct type under `decltype`.
8013 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8014 }
8015
8016 // At this point we should have the right value category.
8017 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8018 "value kind mismatch for non-type template argument");
8019
8020 // The type of the template parameter can differ from the type of the
8021 // argument in various ways; convert it now if necessary.
8022 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8023 QualType SrcExprType = RefExpr.get()->getType();
8024 if (!Context.hasSameType(T1: SrcExprType, T2: DestExprType)) {
8025 CastKind CK;
8026 if (Context.hasSimilarType(T1: SrcExprType, T2: DestExprType) ||
8027 IsFunctionConversion(FromType: SrcExprType, ToType: DestExprType)) {
8028 CK = CK_NoOp;
8029 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8030 CK = CK_BitCast;
8031 } else {
8032 // FIXME: Pointers to members can need conversion derived-to-base or
8033 // base-to-derived conversions. We currently don't retain enough
8034 // information to convert properly (we need to track a cast path or
8035 // subobject number in the template argument).
8036 llvm_unreachable(
8037 "unexpected conversion required for non-type template argument");
8038 }
8039 RefExpr = ImpCastExprToType(E: RefExpr.get(), Type: DestExprType, CK,
8040 VK: RefExpr.get()->getValueKind());
8041 }
8042
8043 return RefExpr;
8044}
8045
8046/// Construct a new expression that refers to the given
8047/// integral template argument with the given source-location
8048/// information.
8049///
8050/// This routine takes care of the mapping from an integral template
8051/// argument (which may have any integral type) to the appropriate
8052/// literal value.
8053static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
8054 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8055 assert(OrigT->isIntegralOrEnumerationType());
8056
8057 // If this is an enum type that we're instantiating, we need to use an integer
8058 // type the same size as the enumerator. We don't want to build an
8059 // IntegerLiteral with enum type. The integer type of an enum type can be of
8060 // any integral type with C++11 enum classes, make sure we create the right
8061 // type of literal for it.
8062 QualType T = OrigT;
8063 if (const auto *ED = OrigT->getAsEnumDecl())
8064 T = ED->getIntegerType();
8065
8066 Expr *E;
8067 if (T->isAnyCharacterType()) {
8068 CharacterLiteralKind Kind;
8069 if (T->isWideCharType())
8070 Kind = CharacterLiteralKind::Wide;
8071 else if (T->isChar8Type() && S.getLangOpts().Char8)
8072 Kind = CharacterLiteralKind::UTF8;
8073 else if (T->isChar16Type())
8074 Kind = CharacterLiteralKind::UTF16;
8075 else if (T->isChar32Type())
8076 Kind = CharacterLiteralKind::UTF32;
8077 else
8078 Kind = CharacterLiteralKind::Ascii;
8079
8080 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8081 } else if (T->isBooleanType()) {
8082 E = CXXBoolLiteralExpr::Create(C: S.Context, Val: Int.getBoolValue(), Ty: T, Loc);
8083 } else {
8084 E = IntegerLiteral::Create(C: S.Context, V: Int, type: T, l: Loc);
8085 }
8086
8087 if (OrigT->isEnumeralType()) {
8088 // FIXME: This is a hack. We need a better way to handle substituted
8089 // non-type template parameters.
8090 E = CStyleCastExpr::Create(Context: S.Context, T: OrigT, VK: VK_PRValue, K: CK_IntegralCast, Op: E,
8091 BasePath: nullptr, FPO: S.CurFPFeatureOverrides(),
8092 WrittenTy: S.Context.getTrivialTypeSourceInfo(T: OrigT, Loc),
8093 L: Loc, R: Loc);
8094 }
8095
8096 return E;
8097}
8098
8099static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
8100 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8101 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8102 auto *ILE = new (S.Context)
8103 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8104 ILE->setType(T);
8105 return ILE;
8106 };
8107
8108 switch (Val.getKind()) {
8109 case APValue::AddrLabelDiff:
8110 // This cannot occur in a template argument at all.
8111 case APValue::Array:
8112 case APValue::Struct:
8113 case APValue::Union:
8114 // These can only occur within a template parameter object, which is
8115 // represented as a TemplateArgument::Declaration.
8116 llvm_unreachable("unexpected template argument value");
8117
8118 case APValue::Int:
8119 return BuildExpressionFromIntegralTemplateArgumentValue(S, OrigT: T, Int: Val.getInt(),
8120 Loc);
8121
8122 case APValue::Float:
8123 return FloatingLiteral::Create(C: S.Context, V: Val.getFloat(), /*IsExact=*/isexact: true,
8124 Type: T, L: Loc);
8125
8126 case APValue::FixedPoint:
8127 return FixedPointLiteral::CreateFromRawInt(
8128 C: S.Context, V: Val.getFixedPoint().getValue(), type: T, l: Loc,
8129 Scale: Val.getFixedPoint().getScale());
8130
8131 case APValue::ComplexInt: {
8132 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8133 return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
8134 S, OrigT: ElemT, Int: Val.getComplexIntReal(), Loc),
8135 BuildExpressionFromIntegralTemplateArgumentValue(
8136 S, OrigT: ElemT, Int: Val.getComplexIntImag(), Loc)});
8137 }
8138
8139 case APValue::ComplexFloat: {
8140 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8141 return MakeInitList(
8142 {FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatReal(), isexact: true,
8143 Type: ElemT, L: Loc),
8144 FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatImag(), isexact: true,
8145 Type: ElemT, L: Loc)});
8146 }
8147
8148 case APValue::Vector: {
8149 QualType ElemT = T->castAs<VectorType>()->getElementType();
8150 llvm::SmallVector<Expr *, 8> Elts;
8151 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8152 Elts.push_back(Elt: BuildExpressionFromNonTypeTemplateArgumentValue(
8153 S, T: ElemT, Val: Val.getVectorElt(I), Loc));
8154 return MakeInitList(Elts);
8155 }
8156
8157 case APValue::Matrix:
8158 llvm_unreachable("Matrix template argument expression not yet supported");
8159
8160 case APValue::None:
8161 case APValue::Indeterminate:
8162 llvm_unreachable("Unexpected APValue kind.");
8163 case APValue::LValue:
8164 case APValue::MemberPointer:
8165 // There isn't necessarily a valid equivalent source-level syntax for
8166 // these; in particular, a naive lowering might violate access control.
8167 // So for now we lower to a ConstantExpr holding the value, wrapped around
8168 // an OpaqueValueExpr.
8169 // FIXME: We should have a better representation for this.
8170 ExprValueKind VK = VK_PRValue;
8171 if (T->isReferenceType()) {
8172 T = T->getPointeeType();
8173 VK = VK_LValue;
8174 }
8175 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8176 return ConstantExpr::Create(Context: S.Context, E: OVE, Result: Val);
8177 }
8178 llvm_unreachable("Unhandled APValue::ValueKind enum");
8179}
8180
8181ExprResult
8182Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
8183 SourceLocation Loc) {
8184 switch (Arg.getKind()) {
8185 case TemplateArgument::Null:
8186 case TemplateArgument::Type:
8187 case TemplateArgument::Template:
8188 case TemplateArgument::TemplateExpansion:
8189 case TemplateArgument::Pack:
8190 llvm_unreachable("not a non-type template argument");
8191
8192 case TemplateArgument::Expression:
8193 return Arg.getAsExpr();
8194
8195 case TemplateArgument::NullPtr:
8196 case TemplateArgument::Declaration:
8197 return BuildExpressionFromDeclTemplateArgument(
8198 Arg, ParamType: Arg.getNonTypeTemplateArgumentType(), Loc);
8199
8200 case TemplateArgument::Integral:
8201 return BuildExpressionFromIntegralTemplateArgumentValue(
8202 S&: *this, OrigT: Arg.getIntegralType(), Int: Arg.getAsIntegral(), Loc);
8203
8204 case TemplateArgument::StructuralValue:
8205 return BuildExpressionFromNonTypeTemplateArgumentValue(
8206 S&: *this, T: Arg.getStructuralValueType(), Val: Arg.getAsStructuralValue(), Loc);
8207 }
8208 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8209}
8210
8211/// Match two template parameters within template parameter lists.
8212static bool MatchTemplateParameterKind(
8213 Sema &S, NamedDecl *New,
8214 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8215 const NamedDecl *OldInstFrom, bool Complain,
8216 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8217 // Check the actual kind (type, non-type, template).
8218 if (Old->getKind() != New->getKind()) {
8219 if (Complain) {
8220 unsigned NextDiag = diag::err_template_param_different_kind;
8221 if (TemplateArgLoc.isValid()) {
8222 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8223 NextDiag = diag::note_template_param_different_kind;
8224 }
8225 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8226 << (Kind != Sema::TPL_TemplateMatch);
8227 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_prev_declaration)
8228 << (Kind != Sema::TPL_TemplateMatch);
8229 }
8230
8231 return false;
8232 }
8233
8234 // Check that both are parameter packs or neither are parameter packs.
8235 // However, if we are matching a template template argument to a
8236 // template template parameter, the template template parameter can have
8237 // a parameter pack where the template template argument does not.
8238 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8239 if (Complain) {
8240 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8241 if (TemplateArgLoc.isValid()) {
8242 S.Diag(Loc: TemplateArgLoc,
8243 DiagID: diag::err_template_arg_template_params_mismatch);
8244 NextDiag = diag::note_template_parameter_pack_non_pack;
8245 }
8246
8247 unsigned ParamKind = isa<TemplateTypeParmDecl>(Val: New)? 0
8248 : isa<NonTypeTemplateParmDecl>(Val: New)? 1
8249 : 2;
8250 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8251 << ParamKind << New->isParameterPack();
8252 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_parameter_pack_here)
8253 << ParamKind << Old->isParameterPack();
8254 }
8255
8256 return false;
8257 }
8258 // For non-type template parameters, check the type of the parameter.
8259 if (NonTypeTemplateParmDecl *OldNTTP =
8260 dyn_cast<NonTypeTemplateParmDecl>(Val: Old)) {
8261 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(Val: New);
8262
8263 // If we are matching a template template argument to a template
8264 // template parameter and one of the non-type template parameter types
8265 // is dependent, then we must wait until template instantiation time
8266 // to actually compare the arguments.
8267 if (Kind != Sema::TPL_TemplateTemplateParmMatch ||
8268 (!OldNTTP->getType()->isDependentType() &&
8269 !NewNTTP->getType()->isDependentType())) {
8270 // C++20 [temp.over.link]p6:
8271 // Two [non-type] template-parameters are equivalent [if] they have
8272 // equivalent types ignoring the use of type-constraints for
8273 // placeholder types
8274 QualType OldType = S.Context.getUnconstrainedType(T: OldNTTP->getType());
8275 QualType NewType = S.Context.getUnconstrainedType(T: NewNTTP->getType());
8276 if (!S.Context.hasSameType(T1: OldType, T2: NewType)) {
8277 if (Complain) {
8278 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8279 if (TemplateArgLoc.isValid()) {
8280 S.Diag(Loc: TemplateArgLoc,
8281 DiagID: diag::err_template_arg_template_params_mismatch);
8282 NextDiag = diag::note_template_nontype_parm_different_type;
8283 }
8284 S.Diag(Loc: NewNTTP->getLocation(), DiagID: NextDiag)
8285 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8286 S.Diag(Loc: OldNTTP->getLocation(),
8287 DiagID: diag::note_template_nontype_parm_prev_declaration)
8288 << OldNTTP->getType();
8289 }
8290 return false;
8291 }
8292 }
8293 }
8294 // For template template parameters, check the template parameter types.
8295 // The template parameter lists of template template
8296 // parameters must agree.
8297 else if (TemplateTemplateParmDecl *OldTTP =
8298 dyn_cast<TemplateTemplateParmDecl>(Val: Old)) {
8299 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(Val: New);
8300 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8301 return false;
8302 if (!S.TemplateParameterListsAreEqual(
8303 NewInstFrom, New: NewTTP->getTemplateParameters(), OldInstFrom,
8304 Old: OldTTP->getTemplateParameters(), Complain,
8305 Kind: (Kind == Sema::TPL_TemplateMatch
8306 ? Sema::TPL_TemplateTemplateParmMatch
8307 : Kind),
8308 TemplateArgLoc))
8309 return false;
8310 }
8311
8312 if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8313 Kind != Sema::TPL_TemplateTemplateParmMatch &&
8314 !isa<TemplateTemplateParmDecl>(Val: Old)) {
8315 const Expr *NewC = nullptr, *OldC = nullptr;
8316
8317 if (isa<TemplateTypeParmDecl>(Val: New)) {
8318 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: New)->getTypeConstraint())
8319 NewC = TC->getImmediatelyDeclaredConstraint();
8320 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: Old)->getTypeConstraint())
8321 OldC = TC->getImmediatelyDeclaredConstraint();
8322 } else if (isa<NonTypeTemplateParmDecl>(Val: New)) {
8323 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: New)
8324 ->getPlaceholderTypeConstraint())
8325 NewC = E;
8326 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: Old)
8327 ->getPlaceholderTypeConstraint())
8328 OldC = E;
8329 } else
8330 llvm_unreachable("unexpected template parameter type");
8331
8332 auto Diagnose = [&] {
8333 S.Diag(Loc: NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8334 DiagID: diag::err_template_different_type_constraint);
8335 S.Diag(Loc: OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8336 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8337 };
8338
8339 if (!NewC != !OldC) {
8340 if (Complain)
8341 Diagnose();
8342 return false;
8343 }
8344
8345 if (NewC) {
8346 if (!S.AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldC, New: NewInstFrom,
8347 NewConstr: NewC)) {
8348 if (Complain)
8349 Diagnose();
8350 return false;
8351 }
8352 }
8353 }
8354
8355 return true;
8356}
8357
8358/// Diagnose a known arity mismatch when comparing template argument
8359/// lists.
8360static
8361void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8362 TemplateParameterList *New,
8363 TemplateParameterList *Old,
8364 Sema::TemplateParameterListEqualKind Kind,
8365 SourceLocation TemplateArgLoc) {
8366 unsigned NextDiag = diag::err_template_param_list_different_arity;
8367 if (TemplateArgLoc.isValid()) {
8368 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8369 NextDiag = diag::note_template_param_list_different_arity;
8370 }
8371 S.Diag(Loc: New->getTemplateLoc(), DiagID: NextDiag)
8372 << (New->size() > Old->size())
8373 << (Kind != Sema::TPL_TemplateMatch)
8374 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8375 S.Diag(Loc: Old->getTemplateLoc(), DiagID: diag::note_template_prev_declaration)
8376 << (Kind != Sema::TPL_TemplateMatch)
8377 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8378}
8379
8380bool Sema::TemplateParameterListsAreEqual(
8381 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8382 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8383 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8384 if (Old->size() != New->size()) {
8385 if (Complain)
8386 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8387 TemplateArgLoc);
8388
8389 return false;
8390 }
8391
8392 // C++0x [temp.arg.template]p3:
8393 // A template-argument matches a template template-parameter (call it P)
8394 // when each of the template parameters in the template-parameter-list of
8395 // the template-argument's corresponding class template or alias template
8396 // (call it A) matches the corresponding template parameter in the
8397 // template-parameter-list of P. [...]
8398 TemplateParameterList::iterator NewParm = New->begin();
8399 TemplateParameterList::iterator NewParmEnd = New->end();
8400 for (TemplateParameterList::iterator OldParm = Old->begin(),
8401 OldParmEnd = Old->end();
8402 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8403 if (NewParm == NewParmEnd) {
8404 if (Complain)
8405 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8406 TemplateArgLoc);
8407 return false;
8408 }
8409 if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm,
8410 OldInstFrom, Complain, Kind,
8411 TemplateArgLoc))
8412 return false;
8413 }
8414
8415 // Make sure we exhausted all of the arguments.
8416 if (NewParm != NewParmEnd) {
8417 if (Complain)
8418 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8419 TemplateArgLoc);
8420
8421 return false;
8422 }
8423
8424 if (Kind != TPL_TemplateParamsEquivalent) {
8425 const Expr *NewRC = New->getRequiresClause();
8426 const Expr *OldRC = Old->getRequiresClause();
8427
8428 auto Diagnose = [&] {
8429 Diag(Loc: NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8430 DiagID: diag::err_template_different_requires_clause);
8431 Diag(Loc: OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8432 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8433 };
8434
8435 if (!NewRC != !OldRC) {
8436 if (Complain)
8437 Diagnose();
8438 return false;
8439 }
8440
8441 if (NewRC) {
8442 if (!AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldRC, New: NewInstFrom,
8443 NewConstr: NewRC)) {
8444 if (Complain)
8445 Diagnose();
8446 return false;
8447 }
8448 }
8449 }
8450
8451 return true;
8452}
8453
8454bool
8455Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8456 if (!S)
8457 return false;
8458
8459 // Find the nearest enclosing declaration scope.
8460 S = S->getDeclParent();
8461
8462 // C++ [temp.pre]p6: [P2096]
8463 // A template, explicit specialization, or partial specialization shall not
8464 // have C linkage.
8465 DeclContext *Ctx = S->getEntity();
8466 if (Ctx && Ctx->isExternCContext()) {
8467 SourceRange Range =
8468 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8469 ? TemplateParams->getParam(Idx: 0)->getSourceRange()
8470 : TemplateParams->getSourceRange();
8471 Diag(Loc: Range.getBegin(), DiagID: diag::err_template_linkage) << Range;
8472 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8473 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
8474 return true;
8475 }
8476 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8477
8478 // C++ [temp]p2:
8479 // A template-declaration can appear only as a namespace scope or
8480 // class scope declaration.
8481 // C++ [temp.expl.spec]p3:
8482 // An explicit specialization may be declared in any scope in which the
8483 // corresponding primary template may be defined.
8484 // C++ [temp.class.spec]p6: [P2096]
8485 // A partial specialization may be declared in any scope in which the
8486 // corresponding primary template may be defined.
8487 if (Ctx) {
8488 if (Ctx->isFileContext())
8489 return false;
8490 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Ctx)) {
8491 // C++ [temp.mem]p2:
8492 // A local class shall not have member templates.
8493 if (RD->isLocalClass())
8494 return Diag(Loc: TemplateParams->getTemplateLoc(),
8495 DiagID: diag::err_template_inside_local_class)
8496 << TemplateParams->getSourceRange();
8497 else
8498 return false;
8499 }
8500 }
8501
8502 return Diag(Loc: TemplateParams->getTemplateLoc(),
8503 DiagID: diag::err_template_outside_namespace_or_class_scope)
8504 << TemplateParams->getSourceRange();
8505}
8506
8507/// Determine what kind of template specialization the given declaration
8508/// is.
8509static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8510 if (!D)
8511 return TSK_Undeclared;
8512
8513 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D))
8514 return Record->getTemplateSpecializationKind();
8515 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D))
8516 return Function->getTemplateSpecializationKind();
8517 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D))
8518 return Var->getTemplateSpecializationKind();
8519
8520 return TSK_Undeclared;
8521}
8522
8523/// Check whether a specialization is well-formed in the current
8524/// context.
8525///
8526/// This routine determines whether a template specialization can be declared
8527/// in the current context (C++ [temp.expl.spec]p2).
8528///
8529/// \param S the semantic analysis object for which this check is being
8530/// performed.
8531///
8532/// \param Specialized the entity being specialized or instantiated, which
8533/// may be a kind of template (class template, function template, etc.) or
8534/// a member of a class template (member function, static data member,
8535/// member class).
8536///
8537/// \param PrevDecl the previous declaration of this entity, if any.
8538///
8539/// \param Loc the location of the explicit specialization or instantiation of
8540/// this entity.
8541///
8542/// \param IsPartialSpecialization whether this is a partial specialization of
8543/// a class template.
8544///
8545/// \returns true if there was an error that we cannot recover from, false
8546/// otherwise.
8547static bool CheckTemplateSpecializationScope(Sema &S,
8548 NamedDecl *Specialized,
8549 NamedDecl *PrevDecl,
8550 SourceLocation Loc,
8551 bool IsPartialSpecialization) {
8552 // Keep these "kind" numbers in sync with the %select statements in the
8553 // various diagnostics emitted by this routine.
8554 int EntityKind = 0;
8555 if (isa<ClassTemplateDecl>(Val: Specialized))
8556 EntityKind = IsPartialSpecialization? 1 : 0;
8557 else if (isa<VarTemplateDecl>(Val: Specialized))
8558 EntityKind = IsPartialSpecialization ? 3 : 2;
8559 else if (isa<FunctionTemplateDecl>(Val: Specialized))
8560 EntityKind = 4;
8561 else if (isa<CXXMethodDecl>(Val: Specialized))
8562 EntityKind = 5;
8563 else if (isa<VarDecl>(Val: Specialized))
8564 EntityKind = 6;
8565 else if (isa<RecordDecl>(Val: Specialized))
8566 EntityKind = 7;
8567 else if (isa<EnumDecl>(Val: Specialized) && S.getLangOpts().CPlusPlus11)
8568 EntityKind = 8;
8569 else {
8570 S.Diag(Loc, DiagID: diag::err_template_spec_unknown_kind)
8571 << S.getLangOpts().CPlusPlus11;
8572 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8573 return true;
8574 }
8575
8576 // C++ [temp.expl.spec]p2:
8577 // An explicit specialization may be declared in any scope in which
8578 // the corresponding primary template may be defined.
8579 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8580 S.Diag(Loc, DiagID: diag::err_template_spec_decl_function_scope)
8581 << Specialized;
8582 return true;
8583 }
8584
8585 // C++ [temp.class.spec]p6:
8586 // A class template partial specialization may be declared in any
8587 // scope in which the primary template may be defined.
8588 DeclContext *SpecializedContext =
8589 Specialized->getDeclContext()->getRedeclContext();
8590 DeclContext *DC = S.CurContext->getRedeclContext();
8591
8592 // Make sure that this redeclaration (or definition) occurs in the same
8593 // scope or an enclosing namespace.
8594 if (!(DC->isFileContext() ? DC->Encloses(DC: SpecializedContext)
8595 : DC->Equals(DC: SpecializedContext))) {
8596 if (isa<TranslationUnitDecl>(Val: SpecializedContext))
8597 S.Diag(Loc, DiagID: diag::err_template_spec_redecl_global_scope)
8598 << EntityKind << Specialized;
8599 else {
8600 auto *ND = cast<NamedDecl>(Val: SpecializedContext);
8601 int Diag = diag::err_template_spec_redecl_out_of_scope;
8602 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8603 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8604 S.Diag(Loc, DiagID: Diag) << EntityKind << Specialized
8605 << ND << isa<CXXRecordDecl>(Val: ND);
8606 }
8607
8608 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8609
8610 // Don't allow specializing in the wrong class during error recovery.
8611 // Otherwise, things can go horribly wrong.
8612 if (DC->isRecord())
8613 return true;
8614 }
8615
8616 return false;
8617}
8618
8619static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8620 if (!E->isTypeDependent())
8621 return SourceLocation();
8622 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8623 Checker.TraverseStmt(S: E);
8624 if (Checker.MatchLoc.isInvalid())
8625 return E->getSourceRange();
8626 return Checker.MatchLoc;
8627}
8628
8629static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8630 if (!TL.getType()->isDependentType())
8631 return SourceLocation();
8632 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8633 Checker.TraverseTypeLoc(TL);
8634 if (Checker.MatchLoc.isInvalid())
8635 return TL.getSourceRange();
8636 return Checker.MatchLoc;
8637}
8638
8639/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8640/// that checks non-type template partial specialization arguments.
8641static bool CheckNonTypeTemplatePartialSpecializationArgs(
8642 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8643 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8644 bool HasError = false;
8645 for (unsigned I = 0; I != NumArgs; ++I) {
8646 if (Args[I].getKind() == TemplateArgument::Pack) {
8647 if (CheckNonTypeTemplatePartialSpecializationArgs(
8648 S, TemplateNameLoc, Param, Args: Args[I].pack_begin(),
8649 NumArgs: Args[I].pack_size(), IsDefaultArgument))
8650 return true;
8651
8652 continue;
8653 }
8654
8655 if (Args[I].getKind() != TemplateArgument::Expression)
8656 continue;
8657
8658 Expr *ArgExpr = Args[I].getAsExpr();
8659 if (ArgExpr->containsErrors()) {
8660 HasError = true;
8661 continue;
8662 }
8663
8664 // We can have a pack expansion of any of the bullets below.
8665 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: ArgExpr))
8666 ArgExpr = Expansion->getPattern();
8667
8668 // Strip off any implicit casts we added as part of type checking.
8669 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
8670 ArgExpr = ICE->getSubExpr();
8671
8672 // C++ [temp.class.spec]p8:
8673 // A non-type argument is non-specialized if it is the name of a
8674 // non-type parameter. All other non-type arguments are
8675 // specialized.
8676 //
8677 // Below, we check the two conditions that only apply to
8678 // specialized non-type arguments, so skip any non-specialized
8679 // arguments.
8680 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ArgExpr))
8681 if (isa<NonTypeTemplateParmDecl>(Val: DRE->getDecl()))
8682 continue;
8683
8684 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ArgExpr);
8685 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8686 continue;
8687 }
8688
8689 // C++ [temp.class.spec]p9:
8690 // Within the argument list of a class template partial
8691 // specialization, the following restrictions apply:
8692 // -- A partially specialized non-type argument expression
8693 // shall not involve a template parameter of the partial
8694 // specialization except when the argument expression is a
8695 // simple identifier.
8696 // -- The type of a template parameter corresponding to a
8697 // specialized non-type argument shall not be dependent on a
8698 // parameter of the specialization.
8699 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8700 // We implement a compromise between the original rules and DR1315:
8701 // -- A specialized non-type template argument shall not be
8702 // type-dependent and the corresponding template parameter
8703 // shall have a non-dependent type.
8704 SourceRange ParamUseRange =
8705 findTemplateParameterInType(Depth: Param->getDepth(), E: ArgExpr);
8706 if (ParamUseRange.isValid()) {
8707 if (IsDefaultArgument) {
8708 S.Diag(Loc: TemplateNameLoc,
8709 DiagID: diag::err_dependent_non_type_arg_in_partial_spec);
8710 S.Diag(Loc: ParamUseRange.getBegin(),
8711 DiagID: diag::note_dependent_non_type_default_arg_in_partial_spec)
8712 << ParamUseRange;
8713 } else {
8714 S.Diag(Loc: ParamUseRange.getBegin(),
8715 DiagID: diag::err_dependent_non_type_arg_in_partial_spec)
8716 << ParamUseRange;
8717 }
8718 return true;
8719 }
8720
8721 ParamUseRange = findTemplateParameter(
8722 Depth: Param->getDepth(), TL: Param->getTypeSourceInfo()->getTypeLoc());
8723 if (ParamUseRange.isValid()) {
8724 S.Diag(Loc: IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8725 DiagID: diag::err_dependent_typed_non_type_arg_in_partial_spec)
8726 << Param->getType();
8727 S.NoteTemplateParameterLocation(Decl: *Param);
8728 return true;
8729 }
8730 }
8731
8732 return HasError;
8733}
8734
8735bool Sema::CheckTemplatePartialSpecializationArgs(
8736 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8737 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8738 // We have to be conservative when checking a template in a dependent
8739 // context.
8740 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8741 return false;
8742
8743 TemplateParameterList *TemplateParams =
8744 PrimaryTemplate->getTemplateParameters();
8745 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8746 NonTypeTemplateParmDecl *Param
8747 = dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: I));
8748 if (!Param)
8749 continue;
8750
8751 if (CheckNonTypeTemplatePartialSpecializationArgs(S&: *this, TemplateNameLoc,
8752 Param, Args: &TemplateArgs[I],
8753 NumArgs: 1, IsDefaultArgument: I >= NumExplicit))
8754 return true;
8755 }
8756
8757 return false;
8758}
8759
8760DeclResult Sema::ActOnClassTemplateSpecialization(
8761 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8762 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8763 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8764 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8765 assert(TUK != TagUseKind::Reference && "References are not specializations");
8766
8767 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8768 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8769 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8770
8771 // Find the class template we're specializing
8772 TemplateName Name = TemplateId.Template.get();
8773 ClassTemplateDecl *ClassTemplate
8774 = dyn_cast_or_null<ClassTemplateDecl>(Val: Name.getAsTemplateDecl());
8775
8776 if (!ClassTemplate) {
8777 Diag(Loc: TemplateNameLoc, DiagID: diag::err_not_class_template_specialization)
8778 << (Name.getAsTemplateDecl() &&
8779 isa<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl()));
8780 return true;
8781 }
8782
8783 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8784 auto Message = DSA->getMessage();
8785 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
8786 << ClassTemplate << !Message.empty() << Message;
8787 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
8788 }
8789
8790 if (S->isTemplateParamScope())
8791 EnterTemplatedContext(S, DC: ClassTemplate->getTemplatedDecl());
8792
8793 DeclContext *DC = ClassTemplate->getDeclContext();
8794
8795 bool isMemberSpecialization = false;
8796 bool isPartialSpecialization = false;
8797
8798 if (SS.isSet()) {
8799 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8800 diagnoseQualifiedDeclaration(SS, DC, Name: ClassTemplate->getDeclName(),
8801 Loc: TemplateNameLoc, TemplateId: &TemplateId,
8802 /*IsMemberSpecialization=*/false))
8803 return true;
8804 }
8805
8806 // Check the validity of the template headers that introduce this
8807 // template.
8808 // FIXME: We probably shouldn't complain about these headers for
8809 // friend declarations.
8810 bool Invalid = false;
8811 TemplateParameterList *TemplateParams =
8812 MatchTemplateParametersToScopeSpecifier(
8813 DeclStartLoc: KWLoc, DeclLoc: TemplateNameLoc, SS, TemplateId: &TemplateId, ParamLists: TemplateParameterLists,
8814 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
8815 if (Invalid)
8816 return true;
8817
8818 // Check that we can declare a template specialization here.
8819 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8820 return true;
8821
8822 if (TemplateParams && DC->isDependentContext()) {
8823 ContextRAII SavedContext(*this, DC);
8824 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
8825 return true;
8826 }
8827
8828 if (TemplateParams && TemplateParams->size() > 0) {
8829 isPartialSpecialization = true;
8830
8831 if (TUK == TagUseKind::Friend) {
8832 Diag(Loc: KWLoc, DiagID: diag::err_partial_specialization_friend)
8833 << SourceRange(LAngleLoc, RAngleLoc);
8834 return true;
8835 }
8836
8837 // C++ [temp.class.spec]p10:
8838 // The template parameter list of a specialization shall not
8839 // contain default template argument values.
8840 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8841 Decl *Param = TemplateParams->getParam(Idx: I);
8842 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
8843 if (TTP->hasDefaultArgument()) {
8844 Diag(Loc: TTP->getDefaultArgumentLoc(),
8845 DiagID: diag::err_default_arg_in_partial_spec);
8846 TTP->removeDefaultArgument();
8847 }
8848 } else if (NonTypeTemplateParmDecl *NTTP
8849 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
8850 if (NTTP->hasDefaultArgument()) {
8851 Diag(Loc: NTTP->getDefaultArgumentLoc(),
8852 DiagID: diag::err_default_arg_in_partial_spec)
8853 << NTTP->getDefaultArgument().getSourceRange();
8854 NTTP->removeDefaultArgument();
8855 }
8856 } else {
8857 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
8858 if (TTP->hasDefaultArgument()) {
8859 Diag(Loc: TTP->getDefaultArgument().getLocation(),
8860 DiagID: diag::err_default_arg_in_partial_spec)
8861 << TTP->getDefaultArgument().getSourceRange();
8862 TTP->removeDefaultArgument();
8863 }
8864 }
8865 }
8866 } else if (TemplateParams) {
8867 if (TUK == TagUseKind::Friend)
8868 Diag(Loc: KWLoc, DiagID: diag::err_template_spec_friend)
8869 << FixItHint::CreateRemoval(
8870 RemoveRange: SourceRange(TemplateParams->getTemplateLoc(),
8871 TemplateParams->getRAngleLoc()))
8872 << SourceRange(LAngleLoc, RAngleLoc);
8873 } else {
8874 assert(TUK == TagUseKind::Friend &&
8875 "should have a 'template<>' for this decl");
8876 }
8877
8878 // Check that the specialization uses the same tag kind as the
8879 // original template.
8880 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
8881 assert(Kind != TagTypeKind::Enum &&
8882 "Invalid enum tag in class template spec!");
8883 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(), NewTag: Kind,
8884 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
8885 Name: ClassTemplate->getIdentifier())) {
8886 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
8887 << ClassTemplate
8888 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
8889 Code: ClassTemplate->getTemplatedDecl()->getKindName());
8890 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
8891 DiagID: diag::note_previous_use);
8892 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8893 }
8894
8895 // Translate the parser's template argument list in our AST format.
8896 TemplateArgumentListInfo TemplateArgs =
8897 makeTemplateArgumentListInfo(S&: *this, TemplateId);
8898
8899 // Check for unexpanded parameter packs in any of the template arguments.
8900 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8901 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
8902 UPPC: isPartialSpecialization
8903 ? UPPC_PartialSpecialization
8904 : UPPC_ExplicitSpecialization))
8905 return true;
8906
8907 // Check that the template argument list is well-formed for this
8908 // template.
8909 CheckTemplateArgumentInfo CTAI;
8910 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
8911 /*DefaultArgs=*/{},
8912 /*PartialTemplateArgs=*/false, CTAI,
8913 /*UpdateArgsWithConversions=*/true))
8914 return true;
8915
8916 // Find the class template (partial) specialization declaration that
8917 // corresponds to these arguments.
8918 if (isPartialSpecialization) {
8919 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, PrimaryTemplate: ClassTemplate,
8920 NumExplicit: TemplateArgs.size(),
8921 TemplateArgs: CTAI.CanonicalConverted))
8922 return true;
8923
8924 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8925 // also do it during instantiation.
8926 if (!Name.isDependent() &&
8927 !TemplateSpecializationType::anyDependentTemplateArguments(
8928 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
8929 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
8930 << ClassTemplate->getDeclName();
8931 isPartialSpecialization = false;
8932 Invalid = true;
8933 }
8934 }
8935
8936 void *InsertPos = nullptr;
8937 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8938
8939 if (isPartialSpecialization)
8940 PrevDecl = ClassTemplate->findPartialSpecialization(
8941 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
8942 else
8943 PrevDecl =
8944 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
8945
8946 ClassTemplateSpecializationDecl *Specialization = nullptr;
8947
8948 // Check whether we can declare a class template specialization in
8949 // the current scope.
8950 if (TUK != TagUseKind::Friend &&
8951 CheckTemplateSpecializationScope(S&: *this, Specialized: ClassTemplate, PrevDecl,
8952 Loc: TemplateNameLoc,
8953 IsPartialSpecialization: isPartialSpecialization))
8954 return true;
8955
8956 if (!isPartialSpecialization) {
8957 // Create a new class template specialization declaration node for
8958 // this explicit specialization or friend declaration.
8959 Specialization = ClassTemplateSpecializationDecl::Create(
8960 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
8961 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
8962 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8963 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
8964 if (TemplateParameterLists.size() > 0) {
8965 Specialization->setTemplateParameterListsInfo(Context,
8966 TPLists: TemplateParameterLists);
8967 }
8968
8969 if (!PrevDecl)
8970 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
8971 } else {
8972 CanQualType CanonType = CanQualType::CreateUnsafe(
8973 Other: Context.getCanonicalTemplateSpecializationType(
8974 Keyword: ElaboratedTypeKeyword::None,
8975 T: TemplateName(ClassTemplate->getCanonicalDecl()),
8976 CanonicalArgs: CTAI.CanonicalConverted));
8977 if (Context.hasSameType(
8978 T1: CanonType,
8979 T2: ClassTemplate->getCanonicalInjectedSpecializationType(Ctx: Context)) &&
8980 (!Context.getLangOpts().CPlusPlus20 ||
8981 !TemplateParams->hasAssociatedConstraints())) {
8982 // C++ [temp.class.spec]p9b3:
8983 //
8984 // -- The argument list of the specialization shall not be identical
8985 // to the implicit argument list of the primary template.
8986 //
8987 // This rule has since been removed, because it's redundant given DR1495,
8988 // but we keep it because it produces better diagnostics and recovery.
8989 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
8990 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8991 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
8992 return CheckClassTemplate(
8993 S, TagSpec, TUK, KWLoc, SS, Name: ClassTemplate->getIdentifier(),
8994 NameLoc: TemplateNameLoc, Attr, TemplateParams, AS: AS_none,
8995 /*ModulePrivateLoc=*/SourceLocation(),
8996 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
8997 OuterTemplateParamLists: TemplateParameterLists.data(), IsMemberSpecialization: isMemberSpecialization);
8998 }
8999
9000 // Create a new class template partial specialization declaration node.
9001 ClassTemplatePartialSpecializationDecl *PrevPartial =
9002 cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl);
9003 ClassTemplatePartialSpecializationDecl *Partial =
9004 ClassTemplatePartialSpecializationDecl::Create(
9005 Context, TK: Kind, DC, StartLoc: KWLoc, IdLoc: TemplateNameLoc, Params: TemplateParams,
9006 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, CanonInjectedTST: CanonType, PrevDecl: PrevPartial);
9007 Partial->setTemplateArgsAsWritten(TemplateArgs);
9008 SetNestedNameSpecifier(S&: *this, T: Partial, SS);
9009 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9010 Partial->setTemplateParameterListsInfo(
9011 Context, TPLists: TemplateParameterLists.drop_back(N: 1));
9012 }
9013
9014 if (!PrevPartial)
9015 ClassTemplate->AddPartialSpecialization(D: Partial, InsertPos);
9016 Specialization = Partial;
9017
9018 // If we are providing an explicit specialization of a member class
9019 // template specialization, make a note of that.
9020 if (isMemberSpecialization)
9021 Partial->setMemberSpecialization();
9022
9023 CheckTemplatePartialSpecialization(Partial);
9024 }
9025
9026 // C++ [temp.expl.spec]p6:
9027 // If a template, a member template or the member of a class template is
9028 // explicitly specialized then that specialization shall be declared
9029 // before the first use of that specialization that would cause an implicit
9030 // instantiation to take place, in every translation unit in which such a
9031 // use occurs; no diagnostic is required.
9032 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9033 bool Okay = false;
9034 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9035 // Is there any previous explicit specialization declaration?
9036 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9037 Okay = true;
9038 break;
9039 }
9040 }
9041
9042 if (!Okay) {
9043 SourceRange Range(TemplateNameLoc, RAngleLoc);
9044 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
9045 << Context.getCanonicalTagType(TD: Specialization) << Range;
9046
9047 Diag(Loc: PrevDecl->getPointOfInstantiation(),
9048 DiagID: diag::note_instantiation_required_here)
9049 << (PrevDecl->getTemplateSpecializationKind()
9050 != TSK_ImplicitInstantiation);
9051 return true;
9052 }
9053 }
9054
9055 // If this is not a friend, note that this is an explicit specialization.
9056 if (TUK != TagUseKind::Friend)
9057 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9058
9059 // Check that this isn't a redefinition of this specialization.
9060 if (TUK == TagUseKind::Definition) {
9061 RecordDecl *Def = Specialization->getDefinition();
9062 NamedDecl *Hidden = nullptr;
9063 bool HiddenDefVisible = false;
9064 if (Def && SkipBody &&
9065 isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible)) {
9066 SkipBody->ShouldSkip = true;
9067 SkipBody->Previous = Def;
9068 if (!HiddenDefVisible && Hidden)
9069 makeMergedDefinitionVisible(ND: Hidden);
9070 } else if (Def) {
9071 SourceRange Range(TemplateNameLoc, RAngleLoc);
9072 Diag(Loc: TemplateNameLoc, DiagID: diag::err_redefinition) << Specialization << Range;
9073 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
9074 Specialization->setInvalidDecl();
9075 return true;
9076 }
9077 }
9078
9079 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
9080 ProcessAPINotes(D: Specialization);
9081
9082 // Add alignment attributes if necessary; these attributes are checked when
9083 // the ASTContext lays out the structure.
9084 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9085 if (LangOpts.HLSL)
9086 Specialization->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
9087 AddAlignmentAttributesForRecord(RD: Specialization);
9088 AddMsStructLayoutForRecord(RD: Specialization);
9089 }
9090
9091 if (ModulePrivateLoc.isValid())
9092 Diag(Loc: Specialization->getLocation(), DiagID: diag::err_module_private_specialization)
9093 << (isPartialSpecialization? 1 : 0)
9094 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
9095
9096 // C++ [temp.expl.spec]p9:
9097 // A template explicit specialization is in the scope of the
9098 // namespace in which the template was defined.
9099 //
9100 // We actually implement this paragraph where we set the semantic
9101 // context (in the creation of the ClassTemplateSpecializationDecl),
9102 // but we also maintain the lexical context where the actual
9103 // definition occurs.
9104 Specialization->setLexicalDeclContext(CurContext);
9105
9106 // We may be starting the definition of this specialization.
9107 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9108 Specialization->startDefinition();
9109
9110 if (TUK == TagUseKind::Friend) {
9111 CanQualType CanonType = Context.getCanonicalTagType(TD: Specialization);
9112 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9113 Keyword: ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9114 QualifierLoc: SS.getWithLocInContext(Context),
9115 /*TemplateKeywordLoc=*/SourceLocation(), T: Name, TLoc: TemplateNameLoc,
9116 SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted, Canon: CanonType);
9117
9118 // Build the fully-sugared type for this class template
9119 // specialization as the user wrote in the specialization
9120 // itself. This means that we'll pretty-print the type retrieved
9121 // from the specialization's declaration the way that the user
9122 // actually wrote the specialization, rather than formatting the
9123 // name based on the "canonical" representation used to store the
9124 // template arguments in the specialization.
9125 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext,
9126 L: TemplateNameLoc,
9127 Friend_: WrittenTy,
9128 /*FIXME:*/FriendL: KWLoc);
9129 Friend->setAccess(AS_public);
9130 CurContext->addDecl(D: Friend);
9131 } else {
9132 // Add the specialization into its lexical context, so that it can
9133 // be seen when iterating through the list of declarations in that
9134 // context. However, specializations are not found by name lookup.
9135 CurContext->addDecl(D: Specialization);
9136 }
9137
9138 if (SkipBody && SkipBody->ShouldSkip)
9139 return SkipBody->Previous;
9140
9141 Specialization->setInvalidDecl(Invalid);
9142 inferGslOwnerPointerAttribute(Record: Specialization);
9143 return Specialization;
9144}
9145
9146Decl *Sema::ActOnTemplateDeclarator(Scope *S,
9147 MultiTemplateParamsArg TemplateParameterLists,
9148 Declarator &D) {
9149 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9150 ActOnDocumentableDecl(D: NewDecl);
9151 return NewDecl;
9152}
9153
9154ConceptDecl *Sema::ActOnStartConceptDefinition(
9155 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9156 const IdentifierInfo *Name, SourceLocation NameLoc) {
9157 DeclContext *DC = CurContext;
9158
9159 if (!DC->getRedeclContext()->isFileContext()) {
9160 Diag(Loc: NameLoc,
9161 DiagID: diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9162 return nullptr;
9163 }
9164
9165 if (TemplateParameterLists.size() > 1) {
9166 Diag(Loc: NameLoc, DiagID: diag::err_concept_extra_headers);
9167 return nullptr;
9168 }
9169
9170 TemplateParameterList *Params = TemplateParameterLists.front();
9171
9172 if (Params->size() == 0) {
9173 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_parameters);
9174 return nullptr;
9175 }
9176
9177 // Ensure that the parameter pack, if present, is the last parameter in the
9178 // template.
9179 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9180 ParamEnd = Params->end();
9181 ParamIt != ParamEnd; ++ParamIt) {
9182 Decl const *Param = *ParamIt;
9183 if (Param->isParameterPack()) {
9184 if (++ParamIt == ParamEnd)
9185 break;
9186 Diag(Loc: Param->getLocation(),
9187 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
9188 return nullptr;
9189 }
9190 }
9191
9192 ConceptDecl *NewDecl =
9193 ConceptDecl::Create(C&: Context, DC, L: NameLoc, Name, Params);
9194
9195 if (NewDecl->hasAssociatedConstraints()) {
9196 // C++2a [temp.concept]p4:
9197 // A concept shall not have associated constraints.
9198 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_associated_constraints);
9199 NewDecl->setInvalidDecl();
9200 }
9201
9202 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9203 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9204 forRedeclarationInCurContext());
9205 LookupName(R&: Previous, S);
9206 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9207 /*AllowInlineNamespace*/ false);
9208
9209 // We cannot properly handle redeclarations until we parse the constraint
9210 // expression, so only inject the name if we are sure we are not redeclaring a
9211 // symbol
9212 if (Previous.empty())
9213 PushOnScopeChains(D: NewDecl, S, AddToContext: true);
9214
9215 return NewDecl;
9216}
9217
9218static bool RemoveLookupResult(LookupResult &R, NamedDecl *C) {
9219 bool Found = false;
9220 LookupResult::Filter F = R.makeFilter();
9221 while (F.hasNext()) {
9222 NamedDecl *D = F.next();
9223 if (D == C) {
9224 F.erase();
9225 Found = true;
9226 break;
9227 }
9228 }
9229 F.done();
9230 return Found;
9231}
9232
9233ConceptDecl *
9234Sema::ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
9235 Expr *ConstraintExpr,
9236 const ParsedAttributesView &Attrs) {
9237 assert(!C->hasDefinition() && "Concept already defined");
9238 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr)) {
9239 C->setInvalidDecl();
9240 return nullptr;
9241 }
9242 C->setDefinition(ConstraintExpr);
9243 ProcessDeclAttributeList(S, D: C, AttrList: Attrs);
9244
9245 // Check for conflicting previous declaration.
9246 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9247 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9248 forRedeclarationInCurContext());
9249 LookupName(R&: Previous, S);
9250 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9251 /*AllowInlineNamespace*/ false);
9252 bool WasAlreadyAdded = RemoveLookupResult(R&: Previous, C);
9253 bool AddToScope = true;
9254 CheckConceptRedefinition(NewDecl: C, Previous, AddToScope);
9255
9256 ActOnDocumentableDecl(D: C);
9257 if (!WasAlreadyAdded && AddToScope)
9258 PushOnScopeChains(D: C, S);
9259
9260 return C;
9261}
9262
9263void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
9264 LookupResult &Previous, bool &AddToScope) {
9265 AddToScope = true;
9266
9267 if (Previous.empty())
9268 return;
9269
9270 auto *OldConcept = dyn_cast<ConceptDecl>(Val: Previous.getRepresentativeDecl()->getUnderlyingDecl());
9271 if (!OldConcept) {
9272 auto *Old = Previous.getRepresentativeDecl();
9273 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_kind)
9274 << NewDecl->getDeclName();
9275 notePreviousDefinition(Old, New: NewDecl->getLocation());
9276 AddToScope = false;
9277 return;
9278 }
9279 // Check if we can merge with a concept declaration.
9280 bool IsSame = Context.isSameEntity(X: NewDecl, Y: OldConcept);
9281 if (!IsSame) {
9282 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_concept)
9283 << NewDecl->getDeclName();
9284 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9285 AddToScope = false;
9286 return;
9287 }
9288 if (hasReachableDefinition(D: OldConcept) &&
9289 IsRedefinitionInModule(New: NewDecl, Old: OldConcept)) {
9290 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition)
9291 << NewDecl->getDeclName();
9292 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9293 AddToScope = false;
9294 return;
9295 }
9296 if (!Previous.isSingleResult()) {
9297 // FIXME: we should produce an error in case of ambig and failed lookups.
9298 // Other decls (e.g. namespaces) also have this shortcoming.
9299 return;
9300 }
9301 // We unwrap canonical decl late to check for module visibility.
9302 Context.setPrimaryMergedDecl(D: NewDecl, Primary: OldConcept->getCanonicalDecl());
9303}
9304
9305bool Sema::CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc) {
9306 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Val: Concept);
9307 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9308 Diag(Loc, DiagID: diag::err_recursive_concept) << CE;
9309 Diag(Loc: CE->getLocation(), DiagID: diag::note_declared_at);
9310 return true;
9311 }
9312 // Concept template parameters don't have a definition and can't
9313 // be defined recursively.
9314 return false;
9315}
9316
9317/// \brief Strips various properties off an implicit instantiation
9318/// that has just been explicitly specialized.
9319static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9320 if (MinGW || (isa<FunctionDecl>(Val: D) &&
9321 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization()))
9322 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9323
9324 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D))
9325 FD->setInlineSpecified(false);
9326}
9327
9328/// Create an ExplicitInstantiationDecl to record source-location info for an
9329/// explicit template instantiation statement, and add it to \p CurContext.
9330///
9331/// For class templates / nested classes, the caller should build a
9332/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9333/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9334///
9335/// For function / variable templates, the caller should pass TypeAsWritten for
9336/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9337static void addExplicitInstantiationDecl(
9338 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9339 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9340 NestedNameSpecifierLoc QualifierLoc,
9341 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9342 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9343 auto *EID = ExplicitInstantiationDecl::Create(
9344 C&: Context, DC: CurContext, Specialization: Spec, ExternLoc, TemplateLoc, QualifierLoc,
9345 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9346 Context.addExplicitInstantiationDecl(Spec, EID);
9347 CurContext->addDecl(D: EID);
9348}
9349
9350/// Compute the diagnostic location for an explicit instantiation
9351// declaration or definition.
9352static SourceLocation
9353DiagLocForExplicitInstantiation(NamedDecl *D,
9354 SourceLocation PointOfInstantiation) {
9355 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(Spec: D))
9356 if (EID->getTemplateSpecializationKind() ==
9357 TSK_ExplicitInstantiationDefinition)
9358 return EID->getTemplateLoc();
9359
9360 // Explicit instantiations following a specialization have no effect and
9361 // hence no PointOfInstantiation. In that case, walk decl backwards
9362 // until a valid name loc is found.
9363 SourceLocation PrevDiagLoc = PointOfInstantiation;
9364 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9365 Prev = Prev->getPreviousDecl()) {
9366 PrevDiagLoc = Prev->getLocation();
9367 }
9368 assert(PrevDiagLoc.isValid() &&
9369 "Explicit instantiation without point of instantiation?");
9370 return PrevDiagLoc;
9371}
9372
9373bool
9374Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9375 TemplateSpecializationKind NewTSK,
9376 NamedDecl *PrevDecl,
9377 TemplateSpecializationKind PrevTSK,
9378 SourceLocation PrevPointOfInstantiation,
9379 bool &HasNoEffect) {
9380 HasNoEffect = false;
9381
9382 switch (NewTSK) {
9383 case TSK_Undeclared:
9384 case TSK_ImplicitInstantiation:
9385 assert(
9386 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9387 "previous declaration must be implicit!");
9388 return false;
9389
9390 case TSK_ExplicitSpecialization:
9391 switch (PrevTSK) {
9392 case TSK_Undeclared:
9393 case TSK_ExplicitSpecialization:
9394 // Okay, we're just specializing something that is either already
9395 // explicitly specialized or has merely been mentioned without any
9396 // instantiation.
9397 return false;
9398
9399 case TSK_ImplicitInstantiation:
9400 if (PrevPointOfInstantiation.isInvalid()) {
9401 // The declaration itself has not actually been instantiated, so it is
9402 // still okay to specialize it.
9403 StripImplicitInstantiation(
9404 D: PrevDecl, MinGW: Context.getTargetInfo().getTriple().isOSCygMing());
9405 return false;
9406 }
9407 // Fall through
9408 [[fallthrough]];
9409
9410 case TSK_ExplicitInstantiationDeclaration:
9411 case TSK_ExplicitInstantiationDefinition:
9412 assert((PrevTSK == TSK_ImplicitInstantiation ||
9413 PrevPointOfInstantiation.isValid()) &&
9414 "Explicit instantiation without point of instantiation?");
9415
9416 // C++ [temp.expl.spec]p6:
9417 // If a template, a member template or the member of a class template
9418 // is explicitly specialized then that specialization shall be declared
9419 // before the first use of that specialization that would cause an
9420 // implicit instantiation to take place, in every translation unit in
9421 // which such a use occurs; no diagnostic is required.
9422 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9423 // Is there any previous explicit specialization declaration?
9424 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization)
9425 return false;
9426 }
9427
9428 Diag(Loc: NewLoc, DiagID: diag::err_specialization_after_instantiation)
9429 << PrevDecl;
9430 Diag(Loc: PrevPointOfInstantiation, DiagID: diag::note_instantiation_required_here)
9431 << (PrevTSK != TSK_ImplicitInstantiation);
9432
9433 return true;
9434 }
9435 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9436
9437 case TSK_ExplicitInstantiationDeclaration:
9438 switch (PrevTSK) {
9439 case TSK_ExplicitInstantiationDeclaration:
9440 // This explicit instantiation declaration is redundant (that's okay).
9441 HasNoEffect = true;
9442 return false;
9443
9444 case TSK_Undeclared:
9445 case TSK_ImplicitInstantiation:
9446 // We're explicitly instantiating something that may have already been
9447 // implicitly instantiated; that's fine.
9448 return false;
9449
9450 case TSK_ExplicitSpecialization:
9451 // C++0x [temp.explicit]p4:
9452 // For a given set of template parameters, if an explicit instantiation
9453 // of a template appears after a declaration of an explicit
9454 // specialization for that template, the explicit instantiation has no
9455 // effect.
9456 HasNoEffect = true;
9457 return false;
9458
9459 case TSK_ExplicitInstantiationDefinition:
9460 // C++0x [temp.explicit]p10:
9461 // If an entity is the subject of both an explicit instantiation
9462 // declaration and an explicit instantiation definition in the same
9463 // translation unit, the definition shall follow the declaration.
9464 Diag(Loc: NewLoc,
9465 DiagID: diag::err_explicit_instantiation_declaration_after_definition);
9466
9467 // Explicit instantiations following a specialization have no effect and
9468 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9469 // until a valid name loc is found.
9470 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9471 DiagID: diag::note_explicit_instantiation_definition_here);
9472 HasNoEffect = true;
9473 return false;
9474 }
9475 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9476
9477 case TSK_ExplicitInstantiationDefinition:
9478 switch (PrevTSK) {
9479 case TSK_Undeclared:
9480 case TSK_ImplicitInstantiation:
9481 // We're explicitly instantiating something that may have already been
9482 // implicitly instantiated; that's fine.
9483 return false;
9484
9485 case TSK_ExplicitSpecialization:
9486 // C++ DR 259, C++0x [temp.explicit]p4:
9487 // For a given set of template parameters, if an explicit
9488 // instantiation of a template appears after a declaration of
9489 // an explicit specialization for that template, the explicit
9490 // instantiation has no effect.
9491 Diag(Loc: NewLoc, DiagID: diag::warn_explicit_instantiation_after_specialization)
9492 << PrevDecl;
9493 Diag(Loc: PrevDecl->getLocation(),
9494 DiagID: diag::note_previous_template_specialization);
9495 HasNoEffect = true;
9496 return false;
9497
9498 case TSK_ExplicitInstantiationDeclaration:
9499 // We're explicitly instantiating a definition for something for which we
9500 // were previously asked to suppress instantiations. That's fine.
9501
9502 // C++0x [temp.explicit]p4:
9503 // For a given set of template parameters, if an explicit instantiation
9504 // of a template appears after a declaration of an explicit
9505 // specialization for that template, the explicit instantiation has no
9506 // effect.
9507 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9508 // Is there any previous explicit specialization declaration?
9509 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9510 HasNoEffect = true;
9511 break;
9512 }
9513 }
9514
9515 return false;
9516
9517 case TSK_ExplicitInstantiationDefinition:
9518 // C++0x [temp.spec]p5:
9519 // For a given template and a given set of template-arguments,
9520 // - an explicit instantiation definition shall appear at most once
9521 // in a program,
9522
9523 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9524 Diag(Loc: NewLoc, DiagID: (getLangOpts().MSVCCompat)
9525 ? diag::ext_explicit_instantiation_duplicate
9526 : diag::err_explicit_instantiation_duplicate)
9527 << PrevDecl;
9528 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9529 DiagID: diag::note_previous_explicit_instantiation);
9530 HasNoEffect = true;
9531 return false;
9532 }
9533 }
9534
9535 llvm_unreachable("Missing specialization/instantiation case?");
9536}
9537
9538bool Sema::CheckDependentFunctionTemplateSpecialization(
9539 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9540 LookupResult &Previous) {
9541 // Remove anything from Previous that isn't a function template in
9542 // the correct context.
9543 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9544 LookupResult::Filter F = Previous.makeFilter();
9545 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9546 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9547 while (F.hasNext()) {
9548 NamedDecl *D = F.next()->getUnderlyingDecl();
9549 if (!isa<FunctionTemplateDecl>(Val: D)) {
9550 F.erase();
9551 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAFunctionTemplate, y&: D));
9552 continue;
9553 }
9554
9555 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9556 NS: D->getDeclContext()->getRedeclContext())) {
9557 F.erase();
9558 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAMemberOfEnclosing, y&: D));
9559 continue;
9560 }
9561 }
9562 F.done();
9563
9564 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9565 if (Previous.empty()) {
9566 Diag(Loc: FD->getLocation(), DiagID: diag::err_dependent_function_template_spec_no_match)
9567 << IsFriend;
9568 for (auto &P : DiscardedCandidates)
9569 Diag(Loc: P.second->getLocation(),
9570 DiagID: diag::note_dependent_function_template_spec_discard_reason)
9571 << P.first << IsFriend;
9572 return true;
9573 }
9574
9575 FD->setDependentTemplateSpecialization(Context, Templates: Previous.asUnresolvedSet(),
9576 TemplateArgs: ExplicitTemplateArgs);
9577 return false;
9578}
9579
9580bool Sema::CheckFunctionTemplateSpecialization(
9581 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9582 LookupResult &Previous, bool QualifiedFriend) {
9583 // The set of function template specializations that could match this
9584 // explicit function template specialization.
9585 UnresolvedSet<8> Candidates;
9586 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9587 /*ForTakingAddress=*/false);
9588
9589 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9590 ConvertedTemplateArgs;
9591
9592 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9593 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9594 I != E; ++I) {
9595 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9596 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Ovl)) {
9597 // Only consider templates found within the same semantic lookup scope as
9598 // FD.
9599 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9600 NS: Ovl->getDeclContext()->getRedeclContext()))
9601 continue;
9602
9603 QualType FT = FD->getType();
9604 // C++11 [dcl.constexpr]p8:
9605 // A constexpr specifier for a non-static member function that is not
9606 // a constructor declares that member function to be const.
9607 //
9608 // When matching a constexpr member function template specialization
9609 // against the primary template, we don't yet know whether the
9610 // specialization has an implicit 'const' (because we don't know whether
9611 // it will be a static member function until we know which template it
9612 // specializes). This rule was removed in C++14.
9613 if (auto *NewMD = dyn_cast<CXXMethodDecl>(Val: FD);
9614 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9615 !isa<CXXConstructorDecl, CXXDestructorDecl>(Val: NewMD)) {
9616 auto *OldMD = dyn_cast<CXXMethodDecl>(Val: FunTmpl->getTemplatedDecl());
9617 if (OldMD && OldMD->isConst()) {
9618 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9619 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9620 EPI.TypeQuals.addConst();
9621 FT = Context.getFunctionType(ResultTy: FPT->getReturnType(),
9622 Args: FPT->getParamTypes(), EPI);
9623 }
9624 }
9625
9626 TemplateArgumentListInfo Args;
9627 if (ExplicitTemplateArgs)
9628 Args = *ExplicitTemplateArgs;
9629
9630 // C++ [temp.expl.spec]p11:
9631 // A trailing template-argument can be left unspecified in the
9632 // template-id naming an explicit function template specialization
9633 // provided it can be deduced from the function argument type.
9634 // Perform template argument deduction to determine whether we may be
9635 // specializing this template.
9636 // FIXME: It is somewhat wasteful to build
9637 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9638 FunctionDecl *Specialization = nullptr;
9639 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9640 FunctionTemplate: cast<FunctionTemplateDecl>(Val: FunTmpl->getFirstDecl()),
9641 ExplicitTemplateArgs: ExplicitTemplateArgs ? &Args : nullptr, ArgFunctionType: FT, Specialization, Info);
9642 TDK != TemplateDeductionResult::Success) {
9643 // Template argument deduction failed; record why it failed, so
9644 // that we can provide nifty diagnostics.
9645 FailedCandidates.addCandidate().set(
9646 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9647 Info: MakeDeductionFailureInfo(Context, TDK, Info));
9648 (void)TDK;
9649 continue;
9650 }
9651
9652 // Target attributes are part of the cuda function signature, so
9653 // the deduced template's cuda target must match that of the
9654 // specialization. Given that C++ template deduction does not
9655 // take target attributes into account, we reject candidates
9656 // here that have a different target.
9657 if (LangOpts.CUDA &&
9658 CUDA().IdentifyTarget(D: Specialization,
9659 /* IgnoreImplicitHDAttr = */ true) !=
9660 CUDA().IdentifyTarget(D: FD, /* IgnoreImplicitHDAttr = */ true)) {
9661 FailedCandidates.addCandidate().set(
9662 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9663 Info: MakeDeductionFailureInfo(
9664 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
9665 continue;
9666 }
9667
9668 // Record this candidate.
9669 if (ExplicitTemplateArgs)
9670 ConvertedTemplateArgs[Specialization] = std::move(Args);
9671 Candidates.addDecl(D: Specialization, AS: I.getAccess());
9672 }
9673 }
9674
9675 // For a qualified friend declaration (with no explicit marker to indicate
9676 // that a template specialization was intended), note all (template and
9677 // non-template) candidates.
9678 if (QualifiedFriend && Candidates.empty()) {
9679 Diag(Loc: FD->getLocation(), DiagID: diag::err_qualified_friend_no_match)
9680 << FD->getDeclName() << FDLookupContext;
9681 // FIXME: We should form a single candidate list and diagnose all
9682 // candidates at once, to get proper sorting and limiting.
9683 for (auto *OldND : Previous) {
9684 if (auto *OldFD = dyn_cast<FunctionDecl>(Val: OldND->getUnderlyingDecl()))
9685 NoteOverloadCandidate(Found: OldND, Fn: OldFD, RewriteKind: CRK_None, DestType: FD->getType(), TakingAddress: false);
9686 }
9687 FailedCandidates.NoteCandidates(S&: *this, Loc: FD->getLocation());
9688 return true;
9689 }
9690
9691 // Find the most specialized function template.
9692 UnresolvedSetIterator Result = getMostSpecialized(
9693 SBegin: Candidates.begin(), SEnd: Candidates.end(), FailedCandidates, Loc: FD->getLocation(),
9694 NoneDiag: PDiag(DiagID: diag::err_function_template_spec_no_match) << FD->getDeclName(),
9695 AmbigDiag: PDiag(DiagID: diag::err_function_template_spec_ambiguous)
9696 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9697 CandidateDiag: PDiag(DiagID: diag::note_function_template_spec_matched));
9698
9699 if (Result == Candidates.end())
9700 return true;
9701
9702 // Ignore access information; it doesn't figure into redeclaration checking.
9703 FunctionDecl *Specialization = cast<FunctionDecl>(Val: *Result);
9704
9705 if (const auto *PT = Specialization->getPrimaryTemplate();
9706 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9707 auto Message = DSA->getMessage();
9708 Diag(Loc: FD->getLocation(), DiagID: diag::warn_invalid_specialization)
9709 << PT << !Message.empty() << Message;
9710 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
9711 }
9712
9713 // C++23 [except.spec]p13:
9714 // An exception specification is considered to be needed when:
9715 // - [...]
9716 // - the exception specification is compared to that of another declaration
9717 // (e.g., an explicit specialization or an overriding virtual function);
9718 // - [...]
9719 //
9720 // The exception specification of a defaulted function is evaluated as
9721 // described above only when needed; similarly, the noexcept-specifier of a
9722 // specialization of a function template or member function of a class
9723 // template is instantiated only when needed.
9724 //
9725 // The standard doesn't specify what the "comparison with another declaration"
9726 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9727 // not state which properties of an explicit specialization must match the
9728 // primary template.
9729 //
9730 // We assume that an explicit specialization must correspond with (per
9731 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9732 // the declaration produced by substitution into the function template.
9733 //
9734 // Since the determination whether two function declarations correspond does
9735 // not consider exception specification, we only need to instantiate it once
9736 // we determine the primary template when comparing types per
9737 // [basic.link]p11.1.
9738 auto *SpecializationFPT =
9739 Specialization->getType()->castAs<FunctionProtoType>();
9740 // If the function has a dependent exception specification, resolve it after
9741 // we have selected the primary template so we can check whether it matches.
9742 if (getLangOpts().CPlusPlus17 &&
9743 isUnresolvedExceptionSpec(ESpecType: SpecializationFPT->getExceptionSpecType()) &&
9744 !ResolveExceptionSpec(Loc: FD->getLocation(), FPT: SpecializationFPT))
9745 return true;
9746
9747 FunctionTemplateSpecializationInfo *SpecInfo
9748 = Specialization->getTemplateSpecializationInfo();
9749 assert(SpecInfo && "Function template specialization info missing?");
9750
9751 // Note: do not overwrite location info if previous template
9752 // specialization kind was explicit.
9753 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9754 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9755 Specialization->setLocation(FD->getLocation());
9756 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9757 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9758 // function can differ from the template declaration with respect to
9759 // the constexpr specifier.
9760 // FIXME: We need an update record for this AST mutation.
9761 // FIXME: What if there are multiple such prior declarations (for instance,
9762 // from different modules)?
9763 Specialization->setConstexprKind(FD->getConstexprKind());
9764 }
9765
9766 // FIXME: Check if the prior specialization has a point of instantiation.
9767 // If so, we have run afoul of .
9768
9769 // If this is a friend declaration, then we're not really declaring
9770 // an explicit specialization.
9771 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9772
9773 // Check the scope of this explicit specialization.
9774 if (!isFriend &&
9775 CheckTemplateSpecializationScope(S&: *this,
9776 Specialized: Specialization->getPrimaryTemplate(),
9777 PrevDecl: Specialization, Loc: FD->getLocation(),
9778 IsPartialSpecialization: false))
9779 return true;
9780
9781 // C++ [temp.expl.spec]p6:
9782 // If a template, a member template or the member of a class template is
9783 // explicitly specialized then that specialization shall be declared
9784 // before the first use of that specialization that would cause an implicit
9785 // instantiation to take place, in every translation unit in which such a
9786 // use occurs; no diagnostic is required.
9787 bool HasNoEffect = false;
9788 if (!isFriend &&
9789 CheckSpecializationInstantiationRedecl(NewLoc: FD->getLocation(),
9790 NewTSK: TSK_ExplicitSpecialization,
9791 PrevDecl: Specialization,
9792 PrevTSK: SpecInfo->getTemplateSpecializationKind(),
9793 PrevPointOfInstantiation: SpecInfo->getPointOfInstantiation(),
9794 HasNoEffect))
9795 return true;
9796
9797 // Mark the prior declaration as an explicit specialization, so that later
9798 // clients know that this is an explicit specialization.
9799 // A dependent friend specialization which has a definition should be treated
9800 // as explicit specialization, despite being invalid.
9801 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9802 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9803 // Since explicit specializations do not inherit '=delete' from their
9804 // primary function template - check if the 'specialization' that was
9805 // implicitly generated (during template argument deduction for partial
9806 // ordering) from the most specialized of all the function templates that
9807 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9808 // first check that it was implicitly generated during template argument
9809 // deduction by making sure it wasn't referenced, and then reset the deleted
9810 // flag to not-deleted, so that we can inherit that information from 'FD'.
9811 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9812 !Specialization->getCanonicalDecl()->isReferenced()) {
9813 // FIXME: This assert will not hold in the presence of modules.
9814 assert(
9815 Specialization->getCanonicalDecl() == Specialization &&
9816 "This must be the only existing declaration of this specialization");
9817 // FIXME: We need an update record for this AST mutation.
9818 Specialization->setDeletedAsWritten(D: false);
9819 }
9820 // FIXME: We need an update record for this AST mutation.
9821 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9822 MarkUnusedFileScopedDecl(D: Specialization);
9823 }
9824
9825 // Turn the given function declaration into a function template
9826 // specialization, with the template arguments from the previous
9827 // specialization.
9828 // Take copies of (semantic and syntactic) template argument lists.
9829 TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
9830 Context, Args: Specialization->getTemplateSpecializationArgs()->asArray());
9831 FD->setFunctionTemplateSpecialization(
9832 Template: Specialization->getPrimaryTemplate(), TemplateArgs: TemplArgs, /*InsertPos=*/nullptr,
9833 TSK: SpecInfo->getTemplateSpecializationKind(),
9834 TemplateArgsAsWritten: ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9835
9836 // A function template specialization inherits the target attributes
9837 // of its template. (We require the attributes explicitly in the
9838 // code to match, but a template may have implicit attributes by
9839 // virtue e.g. of being constexpr, and it passes these implicit
9840 // attributes on to its specializations.)
9841 if (LangOpts.CUDA)
9842 CUDA().inheritTargetAttrs(FD, TD: *Specialization->getPrimaryTemplate());
9843
9844 // The "previous declaration" for this function template specialization is
9845 // the prior function template specialization.
9846 Previous.clear();
9847 Previous.addDecl(D: Specialization);
9848 return false;
9849}
9850
9851bool
9852Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9853 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9854 "Only for non-template members");
9855
9856 // Try to find the member we are instantiating.
9857 NamedDecl *FoundInstantiation = nullptr;
9858 NamedDecl *Instantiation = nullptr;
9859 NamedDecl *InstantiatedFrom = nullptr;
9860 MemberSpecializationInfo *MSInfo = nullptr;
9861
9862 if (Previous.empty()) {
9863 // Nowhere to look anyway.
9864 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Member)) {
9865 UnresolvedSet<8> Candidates;
9866 for (NamedDecl *Candidate : Previous) {
9867 auto *Method = dyn_cast<CXXMethodDecl>(Val: Candidate->getUnderlyingDecl());
9868 // Ignore any candidates that aren't member functions.
9869 if (!Method)
9870 continue;
9871
9872 QualType Adjusted = Function->getType();
9873 if (!hasExplicitCallingConv(T: Adjusted))
9874 Adjusted = adjustCCAndNoReturn(ArgFunctionType: Adjusted, FunctionType: Method->getType());
9875 // Ignore any candidates with the wrong type.
9876 // This doesn't handle deduced return types, but both function
9877 // declarations should be undeduced at this point.
9878 // FIXME: The exception specification should probably be ignored when
9879 // comparing the types.
9880 if (!Context.hasSameType(T1: Adjusted, T2: Method->getType()))
9881 continue;
9882
9883 // Ignore any candidates with unsatisfied constraints.
9884 if (ConstraintSatisfaction Satisfaction;
9885 Method->getTrailingRequiresClause() &&
9886 (CheckFunctionConstraints(FD: Method, Satisfaction,
9887 /*UsageLoc=*/Member->getLocation(),
9888 /*ForOverloadResolution=*/true) ||
9889 !Satisfaction.IsSatisfied))
9890 continue;
9891
9892 Candidates.addDecl(D: Candidate);
9893 }
9894
9895 // If we have no viable candidates left after filtering, we are done.
9896 if (Candidates.empty())
9897 return false;
9898
9899 // Find the function that is more constrained than every other function it
9900 // has been compared to.
9901 UnresolvedSetIterator Best = Candidates.begin();
9902 CXXMethodDecl *BestMethod = nullptr;
9903 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9904 I != E; ++I) {
9905 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9906 if (I == Best ||
9907 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) == Method) {
9908 Best = I;
9909 BestMethod = Method;
9910 }
9911 }
9912
9913 FoundInstantiation = *Best;
9914 Instantiation = BestMethod;
9915 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9916 MSInfo = BestMethod->getMemberSpecializationInfo();
9917
9918 // Make sure the best candidate is more constrained than all of the others.
9919 bool Ambiguous = false;
9920 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9921 I != E; ++I) {
9922 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9923 if (I != Best &&
9924 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) != BestMethod) {
9925 Ambiguous = true;
9926 break;
9927 }
9928 }
9929
9930 if (Ambiguous) {
9931 Diag(Loc: Member->getLocation(), DiagID: diag::err_function_member_spec_ambiguous)
9932 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9933 for (NamedDecl *Candidate : Candidates) {
9934 Candidate = Candidate->getUnderlyingDecl();
9935 Diag(Loc: Candidate->getLocation(), DiagID: diag::note_function_member_spec_matched)
9936 << Candidate;
9937 }
9938 return true;
9939 }
9940 } else if (isa<VarDecl>(Val: Member)) {
9941 VarDecl *PrevVar;
9942 if (Previous.isSingleResult() &&
9943 (PrevVar = dyn_cast<VarDecl>(Val: Previous.getFoundDecl())))
9944 if (PrevVar->isStaticDataMember()) {
9945 FoundInstantiation = Previous.getRepresentativeDecl();
9946 Instantiation = PrevVar;
9947 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9948 MSInfo = PrevVar->getMemberSpecializationInfo();
9949 }
9950 } else if (isa<RecordDecl>(Val: Member)) {
9951 CXXRecordDecl *PrevRecord;
9952 if (Previous.isSingleResult() &&
9953 (PrevRecord = dyn_cast<CXXRecordDecl>(Val: Previous.getFoundDecl()))) {
9954 FoundInstantiation = Previous.getRepresentativeDecl();
9955 Instantiation = PrevRecord;
9956 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9957 MSInfo = PrevRecord->getMemberSpecializationInfo();
9958 }
9959 } else if (isa<EnumDecl>(Val: Member)) {
9960 EnumDecl *PrevEnum;
9961 if (Previous.isSingleResult() &&
9962 (PrevEnum = dyn_cast<EnumDecl>(Val: Previous.getFoundDecl()))) {
9963 FoundInstantiation = Previous.getRepresentativeDecl();
9964 Instantiation = PrevEnum;
9965 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9966 MSInfo = PrevEnum->getMemberSpecializationInfo();
9967 }
9968 }
9969
9970 if (!Instantiation) {
9971 // There is no previous declaration that matches. Since member
9972 // specializations are always out-of-line, the caller will complain about
9973 // this mismatch later.
9974 return false;
9975 }
9976
9977 // A member specialization in a friend declaration isn't really declaring
9978 // an explicit specialization, just identifying a specific (possibly implicit)
9979 // specialization. Don't change the template specialization kind.
9980 //
9981 // FIXME: Is this really valid? Other compilers reject.
9982 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9983 // Preserve instantiation information.
9984 if (InstantiatedFrom && isa<CXXMethodDecl>(Val: Member)) {
9985 cast<CXXMethodDecl>(Val: Member)->setInstantiationOfMemberFunction(
9986 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom),
9987 TSK: cast<CXXMethodDecl>(Val: Instantiation)->getTemplateSpecializationKind());
9988 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Val: Member)) {
9989 cast<CXXRecordDecl>(Val: Member)->setInstantiationOfMemberClass(
9990 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom),
9991 TSK: cast<CXXRecordDecl>(Val: Instantiation)->getTemplateSpecializationKind());
9992 }
9993
9994 Previous.clear();
9995 Previous.addDecl(D: FoundInstantiation);
9996 return false;
9997 }
9998
9999 // Make sure that this is a specialization of a member.
10000 if (!InstantiatedFrom) {
10001 Diag(Loc: Member->getLocation(), DiagID: diag::err_spec_member_not_instantiated)
10002 << Member;
10003 Diag(Loc: Instantiation->getLocation(), DiagID: diag::note_specialized_decl);
10004 return true;
10005 }
10006
10007 // C++ [temp.expl.spec]p6:
10008 // If a template, a member template or the member of a class template is
10009 // explicitly specialized then that specialization shall be declared
10010 // before the first use of that specialization that would cause an implicit
10011 // instantiation to take place, in every translation unit in which such a
10012 // use occurs; no diagnostic is required.
10013 assert(MSInfo && "Member specialization info missing?");
10014
10015 bool HasNoEffect = false;
10016 if (CheckSpecializationInstantiationRedecl(NewLoc: Member->getLocation(),
10017 NewTSK: TSK_ExplicitSpecialization,
10018 PrevDecl: Instantiation,
10019 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10020 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10021 HasNoEffect))
10022 return true;
10023
10024 // Check the scope of this explicit specialization.
10025 if (CheckTemplateSpecializationScope(S&: *this,
10026 Specialized: InstantiatedFrom,
10027 PrevDecl: Instantiation, Loc: Member->getLocation(),
10028 IsPartialSpecialization: false))
10029 return true;
10030
10031 // Note that this member specialization is an "instantiation of" the
10032 // corresponding member of the original template.
10033 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Val: Member)) {
10034 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Val: Instantiation);
10035 if (InstantiationFunction->getTemplateSpecializationKind() ==
10036 TSK_ImplicitInstantiation) {
10037 // Explicit specializations of member functions of class templates do not
10038 // inherit '=delete' from the member function they are specializing.
10039 if (InstantiationFunction->isDeleted()) {
10040 // FIXME: This assert will not hold in the presence of modules.
10041 assert(InstantiationFunction->getCanonicalDecl() ==
10042 InstantiationFunction);
10043 // FIXME: We need an update record for this AST mutation.
10044 InstantiationFunction->setDeletedAsWritten(D: false);
10045 }
10046 }
10047
10048 MemberFunction->setInstantiationOfMemberFunction(
10049 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10050 } else if (auto *MemberVar = dyn_cast<VarDecl>(Val: Member)) {
10051 MemberVar->setInstantiationOfStaticDataMember(
10052 VD: cast<VarDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10053 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
10054 MemberClass->setInstantiationOfMemberClass(
10055 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10056 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Val: Member)) {
10057 MemberEnum->setInstantiationOfMemberEnum(
10058 ED: cast<EnumDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10059 } else {
10060 llvm_unreachable("unknown member specialization kind");
10061 }
10062
10063 // Save the caller the trouble of having to figure out which declaration
10064 // this specialization matches.
10065 Previous.clear();
10066 Previous.addDecl(D: FoundInstantiation);
10067 return false;
10068}
10069
10070/// Complete the explicit specialization of a member of a class template by
10071/// updating the instantiated member to be marked as an explicit specialization.
10072///
10073/// \param OrigD The member declaration instantiated from the template.
10074/// \param Loc The location of the explicit specialization of the member.
10075template<typename DeclT>
10076static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10077 SourceLocation Loc) {
10078 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10079 return;
10080
10081 // FIXME: Inform AST mutation listeners of this AST mutation.
10082 // FIXME: If there are multiple in-class declarations of the member (from
10083 // multiple modules, or a declaration and later definition of a member type),
10084 // should we update all of them?
10085 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10086 OrigD->setLocation(Loc);
10087}
10088
10089void Sema::CompleteMemberSpecialization(NamedDecl *Member,
10090 LookupResult &Previous) {
10091 NamedDecl *Instantiation = cast<NamedDecl>(Val: Member->getCanonicalDecl());
10092 if (Instantiation == Member)
10093 return;
10094
10095 if (auto *Function = dyn_cast<CXXMethodDecl>(Val: Instantiation))
10096 completeMemberSpecializationImpl(S&: *this, OrigD: Function, Loc: Member->getLocation());
10097 else if (auto *Var = dyn_cast<VarDecl>(Val: Instantiation))
10098 completeMemberSpecializationImpl(S&: *this, OrigD: Var, Loc: Member->getLocation());
10099 else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: Instantiation))
10100 completeMemberSpecializationImpl(S&: *this, OrigD: Record, Loc: Member->getLocation());
10101 else if (auto *Enum = dyn_cast<EnumDecl>(Val: Instantiation))
10102 completeMemberSpecializationImpl(S&: *this, OrigD: Enum, Loc: Member->getLocation());
10103 else
10104 llvm_unreachable("unknown member specialization kind");
10105}
10106
10107/// Check the scope of an explicit instantiation.
10108///
10109/// \returns true if a serious error occurs, false otherwise.
10110static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
10111 SourceLocation InstLoc,
10112 bool WasQualifiedName) {
10113 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
10114 DeclContext *CurContext = S.CurContext->getRedeclContext();
10115
10116 if (CurContext->isRecord()) {
10117 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_in_class)
10118 << D;
10119 return true;
10120 }
10121
10122 // C++11 [temp.explicit]p3:
10123 // An explicit instantiation shall appear in an enclosing namespace of its
10124 // template. If the name declared in the explicit instantiation is an
10125 // unqualified name, the explicit instantiation shall appear in the
10126 // namespace where its template is declared or, if that namespace is inline
10127 // (7.3.1), any namespace from its enclosing namespace set.
10128 //
10129 // This is DR275, which we do not retroactively apply to C++98/03.
10130 if (WasQualifiedName) {
10131 if (CurContext->Encloses(DC: OrigContext))
10132 return false;
10133 } else {
10134 if (CurContext->InEnclosingNamespaceSetOf(NS: OrigContext))
10135 return false;
10136 }
10137
10138 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: OrigContext)) {
10139 if (WasQualifiedName)
10140 S.Diag(Loc: InstLoc,
10141 DiagID: S.getLangOpts().CPlusPlus11?
10142 diag::err_explicit_instantiation_out_of_scope :
10143 diag::warn_explicit_instantiation_out_of_scope_0x)
10144 << D << NS;
10145 else
10146 S.Diag(Loc: InstLoc,
10147 DiagID: S.getLangOpts().CPlusPlus11?
10148 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10149 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10150 << D << NS;
10151 } else
10152 S.Diag(Loc: InstLoc,
10153 DiagID: S.getLangOpts().CPlusPlus11?
10154 diag::err_explicit_instantiation_must_be_global :
10155 diag::warn_explicit_instantiation_must_be_global_0x)
10156 << D;
10157 S.Diag(Loc: D->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10158 return false;
10159}
10160
10161/// Common checks for whether an explicit instantiation of \p D is valid.
10162static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
10163 SourceLocation InstLoc,
10164 bool WasQualifiedName,
10165 TemplateSpecializationKind TSK) {
10166 // C++ [temp.explicit]p13:
10167 // An explicit instantiation declaration shall not name a specialization of
10168 // a template with internal linkage.
10169 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10170 D->getFormalLinkage() == Linkage::Internal) {
10171 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_internal_linkage) << D;
10172 return true;
10173 }
10174
10175 // C++11 [temp.explicit]p3: [DR 275]
10176 // An explicit instantiation shall appear in an enclosing namespace of its
10177 // template.
10178 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10179 return true;
10180
10181 return false;
10182}
10183
10184/// Determine whether the given scope specifier has a template-id in it.
10185static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
10186 // C++11 [temp.explicit]p3:
10187 // If the explicit instantiation is for a member function, a member class
10188 // or a static data member of a class template specialization, the name of
10189 // the class template specialization in the qualified-id for the member
10190 // name shall be a simple-template-id.
10191 //
10192 // C++98 has the same restriction, just worded differently.
10193 for (NestedNameSpecifier NNS = SS.getScopeRep();
10194 NNS.getKind() == NestedNameSpecifier::Kind::Type;
10195 /**/) {
10196 const Type *T = NNS.getAsType();
10197 if (isa<TemplateSpecializationType>(Val: T))
10198 return true;
10199 NNS = T->getPrefix();
10200 }
10201 return false;
10202}
10203
10204/// Make a dllexport or dllimport attr on a class template specialization take
10205/// effect.
10206static void dllExportImportClassTemplateSpecialization(
10207 Sema &S, ClassTemplateSpecializationDecl *Def) {
10208 auto *A = cast_or_null<InheritableAttr>(Val: getDLLAttr(D: Def));
10209 assert(A && "dllExportImportClassTemplateSpecialization called "
10210 "on Def without dllexport or dllimport");
10211
10212 // We reject explicit instantiations in class scope, so there should
10213 // never be any delayed exported classes to worry about.
10214 assert(S.DelayedDllExportClasses.empty() &&
10215 "delayed exports present at explicit instantiation");
10216 S.checkClassLevelDLLAttribute(Class: Def);
10217
10218 // Propagate attribute to base class templates.
10219 for (auto &B : Def->bases()) {
10220 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10221 Val: B.getType()->getAsCXXRecordDecl()))
10222 S.propagateDLLAttrToBaseClassTemplate(Class: Def, ClassAttr: A, BaseTemplateSpec: BT, BaseLoc: B.getBeginLoc());
10223 }
10224
10225 S.referenceDLLExportedClassMethods();
10226}
10227
10228DeclResult Sema::ActOnExplicitInstantiation(
10229 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10230 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10231 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10232 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10233 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10234 // Find the class template we're specializing
10235 TemplateName Name = TemplateD.get();
10236 TemplateDecl *TD = Name.getAsTemplateDecl();
10237 // Check that the specialization uses the same tag kind as the
10238 // original template.
10239 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10240 assert(Kind != TagTypeKind::Enum &&
10241 "Invalid enum tag in class template explicit instantiation!");
10242
10243 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: TD);
10244
10245 if (!ClassTemplate) {
10246 NonTagKind NTK = getNonTagTypeDeclKind(D: TD, TTK: Kind);
10247 Diag(Loc: TemplateNameLoc, DiagID: diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10248 Diag(Loc: TD->getLocation(), DiagID: diag::note_previous_use);
10249 return true;
10250 }
10251
10252 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(),
10253 NewTag: Kind, /*isDefinition*/false, NewTagLoc: KWLoc,
10254 Name: ClassTemplate->getIdentifier())) {
10255 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
10256 << ClassTemplate
10257 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
10258 Code: ClassTemplate->getTemplatedDecl()->getKindName());
10259 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
10260 DiagID: diag::note_previous_use);
10261 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10262 }
10263
10264 // C++0x [temp.explicit]p2:
10265 // There are two forms of explicit instantiation: an explicit instantiation
10266 // definition and an explicit instantiation declaration. An explicit
10267 // instantiation declaration begins with the extern keyword. [...]
10268 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10269 ? TSK_ExplicitInstantiationDefinition
10270 : TSK_ExplicitInstantiationDeclaration;
10271
10272 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10273 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10274 // Check for dllexport class template instantiation declarations,
10275 // except for MinGW mode.
10276 for (const ParsedAttr &AL : Attr) {
10277 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10278 Diag(Loc: ExternLoc,
10279 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10280 Diag(Loc: AL.getLoc(), DiagID: diag::note_attribute);
10281 break;
10282 }
10283 }
10284
10285 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10286 Diag(Loc: ExternLoc,
10287 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10288 Diag(Loc: A->getLocation(), DiagID: diag::note_attribute);
10289 }
10290 }
10291
10292 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10293 // instantiation declarations for most purposes.
10294 bool DLLImportExplicitInstantiationDef = false;
10295 if (TSK == TSK_ExplicitInstantiationDefinition &&
10296 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10297 // Check for dllimport class template instantiation definitions.
10298 bool DLLImport =
10299 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10300 for (const ParsedAttr &AL : Attr) {
10301 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10302 DLLImport = true;
10303 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10304 // dllexport trumps dllimport here.
10305 DLLImport = false;
10306 break;
10307 }
10308 }
10309 if (DLLImport) {
10310 TSK = TSK_ExplicitInstantiationDeclaration;
10311 DLLImportExplicitInstantiationDef = true;
10312 }
10313 }
10314
10315 // Translate the parser's template argument list in our AST format.
10316 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10317 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10318
10319 // Check that the template argument list is well-formed for this
10320 // template.
10321 CheckTemplateArgumentInfo CTAI;
10322 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
10323 /*DefaultArgs=*/{}, PartialTemplateArgs: false, CTAI,
10324 /*UpdateArgsWithConversions=*/true,
10325 /*ConstraintsNotSatisfied=*/nullptr))
10326 return true;
10327
10328 // Find the class template specialization declaration that
10329 // corresponds to these arguments.
10330 void *InsertPos = nullptr;
10331 ClassTemplateSpecializationDecl *PrevDecl =
10332 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
10333
10334 TemplateSpecializationKind PrevDecl_TSK
10335 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10336
10337 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10338 Context.getTargetInfo().getTriple().isOSCygMing()) {
10339 // Check for dllexport class template instantiation definitions in MinGW
10340 // mode, if a previous declaration of the instantiation was seen.
10341 for (const ParsedAttr &AL : Attr) {
10342 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10343 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10344 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attr_dllexport_explicit_inst_def);
10345 } else {
10346 Diag(Loc: AL.getLoc(),
10347 DiagID: diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10348 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_prev_decl_missing_dllexport);
10349 }
10350 break;
10351 }
10352 }
10353 }
10354
10355 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10356 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10357 llvm::none_of(Range: Attr, P: [](const ParsedAttr &AL) {
10358 return AL.getKind() == ParsedAttr::AT_DLLExport;
10359 })) {
10360 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10361 Diag(Loc: TemplateLoc, DiagID: diag::warn_dllexport_on_decl_ignored);
10362 Diag(Loc: DEA->getLoc(), DiagID: diag::note_dllexport_on_decl);
10363 }
10364 }
10365
10366 if (CheckExplicitInstantiation(S&: *this, D: ClassTemplate, InstLoc: TemplateNameLoc,
10367 WasQualifiedName: SS.isSet(), TSK))
10368 return true;
10369
10370 ClassTemplateSpecializationDecl *Specialization = nullptr;
10371
10372 bool HasNoEffect = false;
10373 if (PrevDecl) {
10374 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateNameLoc, NewTSK: TSK,
10375 PrevDecl, PrevTSK: PrevDecl_TSK,
10376 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
10377 HasNoEffect))
10378 return PrevDecl;
10379
10380 // Even though HasNoEffect == true means that this explicit instantiation
10381 // has no effect on semantics, we go on to put its syntax in the AST.
10382
10383 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10384 PrevDecl_TSK == TSK_Undeclared) {
10385 // Since the only prior class template specialization with these
10386 // arguments was referenced but not declared, reuse that
10387 // declaration node as our own, updating the source location
10388 // for the template name to reflect our new declaration.
10389 // (Other source locations will be updated later.)
10390 Specialization = PrevDecl;
10391 Specialization->setLocation(TemplateNameLoc);
10392 PrevDecl = nullptr;
10393 }
10394
10395 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10396 DLLImportExplicitInstantiationDef) {
10397 // The new specialization might add a dllimport attribute.
10398 HasNoEffect = false;
10399 }
10400 }
10401
10402 if (!Specialization) {
10403 // Create a new class template specialization declaration node for
10404 // this explicit specialization.
10405 Specialization = ClassTemplateSpecializationDecl::Create(
10406 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
10407 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
10408 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
10409
10410 // A MSInheritanceAttr attached to the previous declaration must be
10411 // propagated to the new node prior to instantiation.
10412 if (PrevDecl) {
10413 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10414 auto *Clone = A->clone(C&: getASTContext());
10415 Clone->setInherited(true);
10416 Specialization->addAttr(A: Clone);
10417 Consumer.AssignInheritanceModel(RD: Specialization);
10418 }
10419 }
10420
10421 if (!HasNoEffect && !PrevDecl) {
10422 // Insert the new specialization.
10423 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
10424 }
10425 }
10426
10427 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10428
10429 // Set source locations for keywords.
10430 Specialization->setExternKeywordLoc(ExternLoc);
10431 Specialization->setTemplateKeywordLoc(TemplateLoc);
10432 Specialization->setBraceRange(SourceRange());
10433
10434 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10435 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
10436 ProcessAPINotes(D: Specialization);
10437
10438 // Add the explicit instantiation into its lexical context. However,
10439 // since explicit instantiations are never found by name lookup, we
10440 // just put it into the declaration context directly.
10441 Specialization->setLexicalDeclContext(CurContext);
10442 CurContext->addDecl(D: Specialization);
10443
10444 // Syntax is now OK, so return if it has no other effect on semantics.
10445 if (HasNoEffect) {
10446 // Set the template specialization kind.
10447 Specialization->setTemplateSpecializationKind(TSK);
10448
10449 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
10450 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10451 Keyword: KW, ElaboratedKeywordLoc: KWLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: SourceLocation(), T: Name,
10452 TLoc: TemplateNameLoc, SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted,
10453 Canon: Context.getCanonicalTagType(TD: Specialization));
10454 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
10455 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10456 NameLoc: TemplateNameLoc, TypeAsWritten: TSI, TSK);
10457 return Specialization;
10458 }
10459
10460 // C++ [temp.explicit]p3:
10461 // A definition of a class template or class member template
10462 // shall be in scope at the point of the explicit instantiation of
10463 // the class template or class member template.
10464 //
10465 // This check comes when we actually try to perform the
10466 // instantiation.
10467 ClassTemplateSpecializationDecl *Def
10468 = cast_or_null<ClassTemplateSpecializationDecl>(
10469 Val: Specialization->getDefinition());
10470 if (!Def)
10471 InstantiateClassTemplateSpecialization(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Specialization, TSK,
10472 /*Complain=*/true,
10473 PrimaryStrictPackMatch: CTAI.StrictPackMatch);
10474 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10475 MarkVTableUsed(Loc: TemplateNameLoc, Class: Specialization, DefinitionRequired: true);
10476 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10477 }
10478
10479 // Instantiate the members of this class template specialization.
10480 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10481 Val: Specialization->getDefinition());
10482 if (Def) {
10483 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10484 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10485 // TSK_ExplicitInstantiationDefinition
10486 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10487 (TSK == TSK_ExplicitInstantiationDefinition ||
10488 DLLImportExplicitInstantiationDef)) {
10489 // FIXME: Need to notify the ASTMutationListener that we did this.
10490 Def->setTemplateSpecializationKind(TSK);
10491
10492 if (!getDLLAttr(D: Def) && getDLLAttr(D: Specialization) &&
10493 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10494 // An explicit instantiation definition can add a dll attribute to a
10495 // template with a previous instantiation declaration. MinGW doesn't
10496 // allow this.
10497 auto *A = cast<InheritableAttr>(
10498 Val: getDLLAttr(D: Specialization)->clone(C&: getASTContext()));
10499 A->setInherited(true);
10500 Def->addAttr(A);
10501 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10502 }
10503 }
10504
10505 // Fix a TSK_ImplicitInstantiation followed by a
10506 // TSK_ExplicitInstantiationDefinition
10507 bool NewlyDLLExported =
10508 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10509 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10510 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10511 // An explicit instantiation definition can add a dll attribute to a
10512 // template with a previous implicit instantiation. MinGW doesn't allow
10513 // this. We limit clang to only adding dllexport, to avoid potentially
10514 // strange codegen behavior. For example, if we extend this conditional
10515 // to dllimport, and we have a source file calling a method on an
10516 // implicitly instantiated template class instance and then declaring a
10517 // dllimport explicit instantiation definition for the same template
10518 // class, the codegen for the method call will not respect the dllimport,
10519 // while it will with cl. The Def will already have the DLL attribute,
10520 // since the Def and Specialization will be the same in the case of
10521 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10522 // attribute to the Specialization; we just need to make it take effect.
10523 assert(Def == Specialization &&
10524 "Def and Specialization should match for implicit instantiation");
10525 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10526 }
10527
10528 // In MinGW mode, export the template instantiation if the declaration
10529 // was marked dllexport.
10530 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10531 Context.getTargetInfo().getTriple().isOSCygMing() &&
10532 PrevDecl->hasAttr<DLLExportAttr>()) {
10533 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10534 }
10535
10536 // Set the template specialization kind. Make sure it is set before
10537 // instantiating the members which will trigger ASTConsumer callbacks.
10538 Specialization->setTemplateSpecializationKind(TSK);
10539 InstantiateClassTemplateSpecializationMembers(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Def, TSK);
10540 } else {
10541
10542 // Set the template specialization kind.
10543 Specialization->setTemplateSpecializationKind(TSK);
10544 }
10545
10546 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
10547 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10548 Keyword: KW, ElaboratedKeywordLoc: KWLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: SourceLocation(), T: Name,
10549 TLoc: TemplateNameLoc, SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted,
10550 Canon: Context.getCanonicalTagType(TD: Specialization));
10551 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
10552 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10553 NameLoc: TemplateNameLoc, TypeAsWritten: TSI, TSK);
10554 return Specialization;
10555}
10556
10557DeclResult
10558Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10559 SourceLocation TemplateLoc, unsigned TagSpec,
10560 SourceLocation KWLoc, CXXScopeSpec &SS,
10561 IdentifierInfo *Name, SourceLocation NameLoc,
10562 const ParsedAttributesView &Attr) {
10563
10564 bool Owned = false;
10565 bool IsDependent = false;
10566 Decl *TagD =
10567 ActOnTag(S, TagSpec, TUK: TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10568 Attr, AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10569 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent, ScopedEnumKWLoc: SourceLocation(),
10570 ScopedEnumUsesClassTag: false, UnderlyingType: TypeResult(), /*IsTypeSpecifier*/ false,
10571 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10572 .get();
10573 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10574
10575 if (!TagD)
10576 return true;
10577
10578 TagDecl *Tag = cast<TagDecl>(Val: TagD);
10579 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10580
10581 if (Tag->isInvalidDecl())
10582 return true;
10583
10584 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: Tag);
10585 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10586 if (!Pattern) {
10587 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_nontemplate_type)
10588 << Context.getCanonicalTagType(TD: Record);
10589 Diag(Loc: Record->getLocation(), DiagID: diag::note_nontemplate_decl_here);
10590 return true;
10591 }
10592
10593 // C++0x [temp.explicit]p2:
10594 // If the explicit instantiation is for a class or member class, the
10595 // elaborated-type-specifier in the declaration shall include a
10596 // simple-template-id.
10597 //
10598 // C++98 has the same restriction, just worded differently.
10599 if (!ScopeSpecifierHasTemplateId(SS))
10600 Diag(Loc: TemplateLoc, DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10601 << Record << SS.getRange();
10602
10603 // C++0x [temp.explicit]p2:
10604 // There are two forms of explicit instantiation: an explicit instantiation
10605 // definition and an explicit instantiation declaration. An explicit
10606 // instantiation declaration begins with the extern keyword. [...]
10607 TemplateSpecializationKind TSK
10608 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10609 : TSK_ExplicitInstantiationDeclaration;
10610
10611 CheckExplicitInstantiation(S&: *this, D: Record, InstLoc: NameLoc, WasQualifiedName: true, TSK);
10612
10613 // Verify that it is okay to explicitly instantiate here.
10614 CXXRecordDecl *PrevDecl
10615 = cast_or_null<CXXRecordDecl>(Val: Record->getPreviousDecl());
10616 if (!PrevDecl && Record->getDefinition())
10617 PrevDecl = Record;
10618 if (PrevDecl) {
10619 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10620 bool HasNoEffect = false;
10621 assert(MSInfo && "No member specialization information?");
10622 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateLoc, NewTSK: TSK,
10623 PrevDecl,
10624 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10625 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10626 HasNoEffect))
10627 return true;
10628 if (HasNoEffect) {
10629 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10630 ElaboratedTypeKeyword KW =
10631 TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
10632 QualType TagTy = Context.getTagType(Keyword: KW, Qualifier: SS.getScopeRep(), TD: Record, OwnsTag: false);
10633 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T: TagTy);
10634 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10635 TL.setElaboratedKeywordLoc(KWLoc);
10636 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10637 TL.setNameLoc(NameLoc);
10638 addExplicitInstantiationDecl(Context, CurContext, Spec: Record, ExternLoc,
10639 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(),
10640 ArgsAsWritten: nullptr, NameLoc, TypeAsWritten: TSI, TSK);
10641 return TagD;
10642 }
10643 }
10644
10645 CXXRecordDecl *RecordDef
10646 = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10647 if (!RecordDef) {
10648 // C++ [temp.explicit]p3:
10649 // A definition of a member class of a class template shall be in scope
10650 // at the point of an explicit instantiation of the member class.
10651 CXXRecordDecl *Def
10652 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
10653 if (!Def) {
10654 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_undefined_member)
10655 << 0 << Record->getDeclName() << Record->getDeclContext();
10656 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_forward_declaration)
10657 << Pattern;
10658 return true;
10659 } else {
10660 if (InstantiateClass(PointOfInstantiation: NameLoc, Instantiation: Record, Pattern: Def,
10661 TemplateArgs: getTemplateInstantiationArgs(D: Record),
10662 TSK))
10663 return true;
10664
10665 RecordDef = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10666 if (!RecordDef)
10667 return true;
10668 }
10669 }
10670
10671 // Instantiate all of the members of the class.
10672 InstantiateClassMembers(PointOfInstantiation: NameLoc, Instantiation: RecordDef,
10673 TemplateArgs: getTemplateInstantiationArgs(D: Record), TSK);
10674
10675 if (TSK == TSK_ExplicitInstantiationDefinition)
10676 MarkVTableUsed(Loc: NameLoc, Class: RecordDef, DefinitionRequired: true);
10677
10678 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10679 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
10680 QualType TagTy = Context.getTagType(Keyword: KW, Qualifier: SS.getScopeRep(), TD: Record, OwnsTag: false);
10681 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T: TagTy);
10682 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10683 TL.setElaboratedKeywordLoc(KWLoc);
10684 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10685 TL.setNameLoc(NameLoc);
10686 addExplicitInstantiationDecl(Context, CurContext, Spec: Record, ExternLoc,
10687 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10688 NameLoc, TypeAsWritten: TSI, TSK);
10689 return TagD;
10690}
10691
10692DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10693 SourceLocation ExternLoc,
10694 SourceLocation TemplateLoc,
10695 Declarator &D) {
10696 // Explicit instantiations always require a name.
10697 // TODO: check if/when DNInfo should replace Name.
10698 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10699 DeclarationName Name = NameInfo.getName();
10700 if (!Name) {
10701 if (!D.isInvalidType())
10702 Diag(Loc: D.getDeclSpec().getBeginLoc(),
10703 DiagID: diag::err_explicit_instantiation_requires_name)
10704 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10705
10706 return true;
10707 }
10708
10709 // Get the innermost enclosing declaration scope.
10710 S = S->getDeclParent();
10711
10712 // Determine the type of the declaration.
10713 TypeSourceInfo *T = GetTypeForDeclarator(D);
10714 QualType R = T->getType();
10715 if (R.isNull())
10716 return true;
10717
10718 // C++ [dcl.stc]p1:
10719 // A storage-class-specifier shall not be specified in [...] an explicit
10720 // instantiation (14.7.2) directive.
10721 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10722 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_of_typedef)
10723 << Name;
10724 return true;
10725 } else if (D.getDeclSpec().getStorageClassSpec()
10726 != DeclSpec::SCS_unspecified) {
10727 // Complain about then remove the storage class specifier.
10728 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_storage_class)
10729 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10730
10731 D.getMutableDeclSpec().ClearStorageClassSpecs();
10732 }
10733
10734 // C++0x [temp.explicit]p1:
10735 // [...] An explicit instantiation of a function template shall not use the
10736 // inline or constexpr specifiers.
10737 // Presumably, this also applies to member functions of class templates as
10738 // well.
10739 if (D.getDeclSpec().isInlineSpecified())
10740 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10741 DiagID: getLangOpts().CPlusPlus11 ?
10742 diag::err_explicit_instantiation_inline :
10743 diag::warn_explicit_instantiation_inline_0x)
10744 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10745 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10746 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10747 // not already specified.
10748 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10749 DiagID: diag::err_explicit_instantiation_constexpr);
10750
10751 // A deduction guide is not on the list of entities that can be explicitly
10752 // instantiated.
10753 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10754 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
10755 << /*explicit instantiation*/ 0;
10756 return true;
10757 }
10758
10759 // C++0x [temp.explicit]p2:
10760 // There are two forms of explicit instantiation: an explicit instantiation
10761 // definition and an explicit instantiation declaration. An explicit
10762 // instantiation declaration begins with the extern keyword. [...]
10763 TemplateSpecializationKind TSK
10764 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10765 : TSK_ExplicitInstantiationDeclaration;
10766
10767 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10768 LookupParsedName(R&: Previous, S, SS: &D.getCXXScopeSpec(),
10769 /*ObjectType=*/QualType());
10770
10771 if (!R->isFunctionType()) {
10772 // C++ [temp.explicit]p1:
10773 // A [...] static data member of a class template can be explicitly
10774 // instantiated from the member definition associated with its class
10775 // template.
10776 // C++1y [temp.explicit]p1:
10777 // A [...] variable [...] template specialization can be explicitly
10778 // instantiated from its template.
10779 if (Previous.isAmbiguous())
10780 return true;
10781
10782 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10783 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10784 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10785
10786 if (!PrevTemplate) {
10787 if (!Prev || !Prev->isStaticDataMember()) {
10788 // We expect to see a static data member here.
10789 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_not_known)
10790 << Name;
10791 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10792 P != PEnd; ++P)
10793 Diag(Loc: (*P)->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10794 return true;
10795 }
10796
10797 if (!Prev->getInstantiatedFromStaticDataMember()) {
10798 // FIXME: Check for explicit specialization?
10799 Diag(Loc: D.getIdentifierLoc(),
10800 DiagID: diag::err_explicit_instantiation_data_member_not_instantiated)
10801 << Prev;
10802 Diag(Loc: Prev->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10803 // FIXME: Can we provide a note showing where this was declared?
10804 return true;
10805 }
10806 } else {
10807 // Explicitly instantiate a variable template.
10808
10809 // C++1y [dcl.spec.auto]p6:
10810 // ... A program that uses auto or decltype(auto) in a context not
10811 // explicitly allowed in this section is ill-formed.
10812 //
10813 // This includes auto-typed variable template instantiations.
10814 if (R->isUndeducedType()) {
10815 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10816 DiagID: diag::err_auto_not_allowed_var_inst);
10817 return true;
10818 }
10819
10820 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10821 // C++1y [temp.explicit]p3:
10822 // If the explicit instantiation is for a variable, the unqualified-id
10823 // in the declaration shall be a template-id.
10824 Diag(Loc: D.getIdentifierLoc(),
10825 DiagID: diag::err_explicit_instantiation_without_template_id)
10826 << PrevTemplate;
10827 Diag(Loc: PrevTemplate->getLocation(),
10828 DiagID: diag::note_explicit_instantiation_here);
10829 return true;
10830 }
10831
10832 // Translate the parser's template argument list into our AST format.
10833 TemplateArgumentListInfo TemplateArgs =
10834 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10835
10836 DeclResult Res =
10837 CheckVarTemplateId(Template: PrevTemplate, TemplateLoc, TemplateNameLoc: D.getIdentifierLoc(),
10838 TemplateArgs, /*SetWrittenArgs=*/true);
10839 if (Res.isInvalid())
10840 return true;
10841
10842 if (!Res.isUsable()) {
10843 // We somehow specified dependent template arguments in an explicit
10844 // instantiation. This should probably only happen during error
10845 // recovery.
10846 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_dependent);
10847 return true;
10848 }
10849
10850 // Ignore access control bits, we don't need them for redeclaration
10851 // checking.
10852 Prev = cast<VarDecl>(Val: Res.get());
10853 ArgsAsWritten =
10854 ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
10855 }
10856
10857 // C++0x [temp.explicit]p2:
10858 // If the explicit instantiation is for a member function, a member class
10859 // or a static data member of a class template specialization, the name of
10860 // the class template specialization in the qualified-id for the member
10861 // name shall be a simple-template-id.
10862 //
10863 // C++98 has the same restriction, just worded differently.
10864 //
10865 // This does not apply to variable template specializations, where the
10866 // template-id is in the unqualified-id instead.
10867 if (!ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()) && !PrevTemplate)
10868 Diag(Loc: D.getIdentifierLoc(),
10869 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10870 << Prev << D.getCXXScopeSpec().getRange();
10871
10872 CheckExplicitInstantiation(S&: *this, D: Prev, InstLoc: D.getIdentifierLoc(), WasQualifiedName: true, TSK);
10873
10874 // Verify that it is okay to explicitly instantiate here.
10875 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10876 SourceLocation POI = Prev->getPointOfInstantiation();
10877 bool HasNoEffect = false;
10878 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK, PrevDecl: Prev,
10879 PrevTSK, PrevPointOfInstantiation: POI, HasNoEffect))
10880 return true;
10881
10882 if (!HasNoEffect) {
10883 // Instantiate static data member or variable template.
10884 Prev->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
10885 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: Prev)) {
10886 VTSD->setExternKeywordLoc(ExternLoc);
10887 VTSD->setTemplateKeywordLoc(TemplateLoc);
10888 }
10889
10890 // Merge attributes.
10891 ProcessDeclAttributeList(S, D: Prev, AttrList: D.getDeclSpec().getAttributes());
10892 if (PrevTemplate)
10893 ProcessAPINotes(D: Prev);
10894
10895 if (TSK == TSK_ExplicitInstantiationDefinition)
10896 InstantiateVariableDefinition(PointOfInstantiation: D.getIdentifierLoc(), Var: Prev);
10897 }
10898
10899 // Check the new variable specialization against the parsed input.
10900 if (PrevTemplate && !Context.hasSameType(T1: Prev->getType(), T2: R)) {
10901 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10902 DiagID: diag::err_invalid_var_template_spec_type)
10903 << 0 << PrevTemplate << R << Prev->getType();
10904 Diag(Loc: PrevTemplate->getLocation(), DiagID: diag::note_template_declared_here)
10905 << 2 << PrevTemplate->getDeclName();
10906 return true;
10907 }
10908
10909 addExplicitInstantiationDecl(
10910 Context, CurContext, Spec: Prev, ExternLoc, TemplateLoc,
10911 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
10912 NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
10913 return (Decl *)nullptr;
10914 }
10915
10916 // If the declarator is a template-id, translate the parser's template
10917 // argument list into our AST format.
10918 bool HasExplicitTemplateArgs = false;
10919 TemplateArgumentListInfo TemplateArgs;
10920 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10921 TemplateArgs = makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10922 HasExplicitTemplateArgs = true;
10923 }
10924
10925 // C++ [temp.explicit]p1:
10926 // A [...] function [...] can be explicitly instantiated from its template.
10927 // A member function [...] of a class template can be explicitly
10928 // instantiated from the member definition associated with its class
10929 // template.
10930 UnresolvedSet<8> TemplateMatches;
10931 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10932 OverloadCandidateSet::CSK_Normal);
10933 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10934 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10935 P != PEnd; ++P) {
10936 NamedDecl *Prev = *P;
10937 if (!HasExplicitTemplateArgs) {
10938 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Prev)) {
10939 QualType Adjusted = adjustCCAndNoReturn(ArgFunctionType: R, FunctionType: Method->getType(),
10940 /*AdjustExceptionSpec*/true);
10941 if (Context.hasSameUnqualifiedType(T1: Method->getType(), T2: Adjusted)) {
10942 if (Method->getPrimaryTemplate()) {
10943 TemplateMatches.addDecl(D: Method, AS: P.getAccess());
10944 } else {
10945 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10946 C.FoundDecl = P.getPair();
10947 C.Function = Method;
10948 C.Viable = true;
10949 ConstraintSatisfaction S;
10950 if (Method->getTrailingRequiresClause() &&
10951 (CheckFunctionConstraints(FD: Method, Satisfaction&: S, UsageLoc: D.getIdentifierLoc(),
10952 /*ForOverloadResolution=*/true) ||
10953 !S.IsSatisfied)) {
10954 C.Viable = false;
10955 C.FailureKind = ovl_fail_constraints_not_satisfied;
10956 }
10957 }
10958 }
10959 }
10960 }
10961
10962 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Prev);
10963 if (!FunTmpl)
10964 continue;
10965
10966 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10967 FunctionDecl *Specialization = nullptr;
10968 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
10969 FunctionTemplate: FunTmpl, ExplicitTemplateArgs: (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), ArgFunctionType: R,
10970 Specialization, Info);
10971 TDK != TemplateDeductionResult::Success) {
10972 // Keep track of almost-matches.
10973 FailedTemplateCandidates.addCandidate().set(
10974 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
10975 Info: MakeDeductionFailureInfo(Context, TDK, Info));
10976 (void)TDK;
10977 continue;
10978 }
10979
10980 // Target attributes are part of the cuda function signature, so
10981 // the cuda target of the instantiated function must match that of its
10982 // template. Given that C++ template deduction does not take
10983 // target attributes into account, we reject candidates here that
10984 // have a different target.
10985 if (LangOpts.CUDA &&
10986 CUDA().IdentifyTarget(D: Specialization,
10987 /* IgnoreImplicitHDAttr = */ true) !=
10988 CUDA().IdentifyTarget(Attrs: D.getDeclSpec().getAttributes())) {
10989 FailedTemplateCandidates.addCandidate().set(
10990 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
10991 Info: MakeDeductionFailureInfo(
10992 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
10993 continue;
10994 }
10995
10996 TemplateMatches.addDecl(D: Specialization, AS: P.getAccess());
10997 }
10998
10999 FunctionDecl *Specialization = nullptr;
11000 if (!NonTemplateMatches.empty()) {
11001 unsigned Msg = 0;
11002 OverloadCandidateDisplayKind DisplayKind;
11003 OverloadCandidateSet::iterator Best;
11004 switch (NonTemplateMatches.BestViableFunction(S&: *this, Loc: D.getIdentifierLoc(),
11005 Best)) {
11006 case OR_Success:
11007 case OR_Deleted:
11008 Specialization = cast<FunctionDecl>(Val: Best->Function);
11009 break;
11010 case OR_Ambiguous:
11011 Msg = diag::err_explicit_instantiation_ambiguous;
11012 DisplayKind = OCD_AmbiguousCandidates;
11013 break;
11014 case OR_No_Viable_Function:
11015 Msg = diag::err_explicit_instantiation_no_candidate;
11016 DisplayKind = OCD_AllCandidates;
11017 break;
11018 }
11019 if (Msg) {
11020 PartialDiagnostic Diag = PDiag(DiagID: Msg) << Name;
11021 NonTemplateMatches.NoteCandidates(
11022 PA: PartialDiagnosticAt(D.getIdentifierLoc(), Diag), S&: *this, OCD: DisplayKind,
11023 Args: {});
11024 return true;
11025 }
11026 }
11027
11028 if (!Specialization) {
11029 // Find the most specialized function template specialization.
11030 UnresolvedSetIterator Result = getMostSpecialized(
11031 SBegin: TemplateMatches.begin(), SEnd: TemplateMatches.end(),
11032 FailedCandidates&: FailedTemplateCandidates, Loc: D.getIdentifierLoc(),
11033 NoneDiag: PDiag(DiagID: diag::err_explicit_instantiation_not_known) << Name,
11034 AmbigDiag: PDiag(DiagID: diag::err_explicit_instantiation_ambiguous) << Name,
11035 CandidateDiag: PDiag(DiagID: diag::note_explicit_instantiation_candidate));
11036
11037 if (Result == TemplateMatches.end())
11038 return true;
11039
11040 // Ignore access control bits, we don't need them for redeclaration checking.
11041 Specialization = cast<FunctionDecl>(Val: *Result);
11042 }
11043
11044 // C++11 [except.spec]p4
11045 // In an explicit instantiation an exception-specification may be specified,
11046 // but is not required.
11047 // If an exception-specification is specified in an explicit instantiation
11048 // directive, it shall be compatible with the exception-specifications of
11049 // other declarations of that function.
11050 if (auto *FPT = R->getAs<FunctionProtoType>())
11051 if (FPT->hasExceptionSpec()) {
11052 unsigned DiagID =
11053 diag::err_mismatched_exception_spec_explicit_instantiation;
11054 if (getLangOpts().MicrosoftExt)
11055 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11056 bool Result = CheckEquivalentExceptionSpec(
11057 DiagID: PDiag(DiagID) << Specialization->getType(),
11058 NoteID: PDiag(DiagID: diag::note_explicit_instantiation_here),
11059 Old: Specialization->getType()->getAs<FunctionProtoType>(),
11060 OldLoc: Specialization->getLocation(), New: FPT, NewLoc: D.getBeginLoc());
11061 // In Microsoft mode, mismatching exception specifications just cause a
11062 // warning.
11063 if (!getLangOpts().MicrosoftExt && Result)
11064 return true;
11065 }
11066
11067 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11068 Diag(Loc: D.getIdentifierLoc(),
11069 DiagID: diag::err_explicit_instantiation_member_function_not_instantiated)
11070 << Specialization
11071 << (Specialization->getTemplateSpecializationKind() ==
11072 TSK_ExplicitSpecialization);
11073 Diag(Loc: Specialization->getLocation(), DiagID: diag::note_explicit_instantiation_here);
11074 return true;
11075 }
11076
11077 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11078 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11079 PrevDecl = Specialization;
11080
11081 if (PrevDecl) {
11082 bool HasNoEffect = false;
11083 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK,
11084 PrevDecl,
11085 PrevTSK: PrevDecl->getTemplateSpecializationKind(),
11086 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
11087 HasNoEffect))
11088 return true;
11089
11090 if (HasNoEffect) {
11091 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11092 if (HasExplicitTemplateArgs)
11093 ArgsAsWritten =
11094 ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
11095 addExplicitInstantiationDecl(
11096 Context, CurContext, Spec: Specialization, ExternLoc, TemplateLoc,
11097 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11098 NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
11099 return (Decl *)nullptr;
11100 }
11101 }
11102
11103 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11104 // functions
11105 // valarray<size_t>::valarray(size_t) and
11106 // valarray<size_t>::~valarray()
11107 // that it declared to have internal linkage with the internal_linkage
11108 // attribute. Ignore the explicit instantiation declaration in this case.
11109 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11110 TSK == TSK_ExplicitInstantiationDeclaration) {
11111 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getDeclContext()))
11112 if (RD->getIdentifier() && RD->getIdentifier()->isStr(Str: "valarray") &&
11113 RD->isInStdNamespace())
11114 return (Decl*) nullptr;
11115 }
11116
11117 ProcessDeclAttributeList(S, D: Specialization, AttrList: D.getDeclSpec().getAttributes());
11118 ProcessAPINotes(D: Specialization);
11119
11120 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11121 // instantiation declarations.
11122 if (TSK == TSK_ExplicitInstantiationDefinition &&
11123 Specialization->hasAttr<DLLImportAttr>() &&
11124 Context.getTargetInfo().getCXXABI().isMicrosoft())
11125 TSK = TSK_ExplicitInstantiationDeclaration;
11126
11127 Specialization->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
11128 if (Specialization->isDefined()) {
11129 // Let the ASTConsumer know that this function has been explicitly
11130 // instantiated now, and its linkage might have changed.
11131 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Specialization));
11132 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11133 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11134 // be explicitly instantiated.
11135 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getParent());
11136 RD && RD->isLambda()) {
11137 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_lambda_explicit_temp_spec)
11138 << /*instantiation*/ 1;
11139 Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here) << RD;
11140 return (Decl *)nullptr;
11141 }
11142 InstantiateFunctionDefinition(PointOfInstantiation: D.getIdentifierLoc(), Function: Specialization);
11143 }
11144
11145 // C++0x [temp.explicit]p2:
11146 // If the explicit instantiation is for a member function, a member class
11147 // or a static data member of a class template specialization, the name of
11148 // the class template specialization in the qualified-id for the member
11149 // name shall be a simple-template-id.
11150 //
11151 // C++98 has the same restriction, just worded differently.
11152 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11153 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11154 D.getCXXScopeSpec().isSet() &&
11155 !ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()))
11156 Diag(Loc: D.getIdentifierLoc(),
11157 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
11158 << Specialization << D.getCXXScopeSpec().getRange();
11159
11160 CheckExplicitInstantiation(
11161 S&: *this,
11162 D: FunTmpl ? (NamedDecl *)FunTmpl
11163 : Specialization->getInstantiatedFromMemberFunction(),
11164 InstLoc: D.getIdentifierLoc(), WasQualifiedName: D.getCXXScopeSpec().isSet(), TSK);
11165
11166 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11167 if (HasExplicitTemplateArgs)
11168 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
11169 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
11170 TemplateLoc,
11171 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context),
11172 ArgsAsWritten, NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
11173 return (Decl *)nullptr;
11174}
11175
11176TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11177 const CXXScopeSpec &SS,
11178 const IdentifierInfo *Name,
11179 SourceLocation TagLoc,
11180 SourceLocation NameLoc) {
11181 // This has to hold, because SS is expected to be defined.
11182 assert(Name && "Expected a name in a dependent tag");
11183
11184 NestedNameSpecifier NNS = SS.getScopeRep();
11185 if (!NNS)
11186 return true;
11187
11188 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
11189
11190 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11191 Diag(Loc: NameLoc, DiagID: diag::err_dependent_tag_decl)
11192 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11193 return true;
11194 }
11195
11196 // Create the resulting type.
11197 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
11198 QualType Result = Context.getDependentNameType(Keyword: Kwd, NNS, Name);
11199
11200 // Create type-source location information for this type.
11201 TypeLocBuilder TLB;
11202 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: Result);
11203 TL.setElaboratedKeywordLoc(TagLoc);
11204 TL.setQualifierLoc(SS.getWithLocInContext(Context));
11205 TL.setNameLoc(NameLoc);
11206 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
11207}
11208
11209TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11210 const CXXScopeSpec &SS,
11211 const IdentifierInfo &II,
11212 SourceLocation IdLoc,
11213 ImplicitTypenameContext IsImplicitTypename) {
11214 if (SS.isInvalid())
11215 return true;
11216
11217 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11218 DiagCompat(Loc: TypenameLoc, CompatDiagId: diag_compat::typename_outside_of_template)
11219 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11220
11221 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11222 TypeSourceInfo *TSI = nullptr;
11223 QualType T =
11224 CheckTypenameType(Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11225 : ElaboratedTypeKeyword::None,
11226 KeywordLoc: TypenameLoc, QualifierLoc, II, IILoc: IdLoc, TSI: &TSI,
11227 /*DeducedTSTContext=*/true);
11228 if (T.isNull())
11229 return true;
11230 return CreateParsedType(T, TInfo: TSI);
11231}
11232
11233TypeResult
11234Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11235 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11236 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11237 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11238 ASTTemplateArgsPtr TemplateArgsIn,
11239 SourceLocation RAngleLoc) {
11240 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11241 Diag(Loc: TypenameLoc, DiagID: getLangOpts().CPlusPlus11
11242 ? diag::compat_cxx11_typename_outside_of_template
11243 : diag::compat_pre_cxx11_typename_outside_of_template)
11244 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11245
11246 // Strangely, non-type results are not ignored by this lookup, so the
11247 // program is ill-formed if it finds an injected-class-name.
11248 if (TypenameLoc.isValid()) {
11249 auto *LookupRD =
11250 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: false));
11251 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11252 Diag(Loc: TemplateIILoc,
11253 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
11254 << TemplateII << 0 /*injected-class-name used as template name*/
11255 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11256 }
11257 }
11258
11259 // Translate the parser's template argument list in our AST format.
11260 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11261 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11262
11263 QualType T = CheckTemplateIdType(
11264 Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11265 : ElaboratedTypeKeyword::None,
11266 Name: TemplateIn.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
11267 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11268 if (T.isNull())
11269 return true;
11270
11271 // Provide source-location information for the template specialization type.
11272 TypeLocBuilder Builder;
11273 TemplateSpecializationTypeLoc SpecTL
11274 = Builder.push<TemplateSpecializationTypeLoc>(T);
11275 SpecTL.set(ElaboratedKeywordLoc: TypenameLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
11276 NameLoc: TemplateIILoc, TAL: TemplateArgs);
11277 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11278 return CreateParsedType(T, TInfo: TSI);
11279}
11280
11281/// Determine whether this failed name lookup should be treated as being
11282/// disabled by a usage of std::enable_if.
11283static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
11284 SourceRange &CondRange, Expr *&Cond) {
11285 // We must be looking for a ::type...
11286 if (!II.isStr(Str: "type"))
11287 return false;
11288
11289 // ... within an explicitly-written template specialization...
11290 if (NNS.getNestedNameSpecifier().getKind() != NestedNameSpecifier::Kind::Type)
11291 return false;
11292
11293 // FIXME: Look through sugar.
11294 auto EnableIfTSTLoc =
11295 NNS.castAsTypeLoc().getAs<TemplateSpecializationTypeLoc>();
11296 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11297 return false;
11298 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11299
11300 // ... which names a complete class template declaration...
11301 const TemplateDecl *EnableIfDecl =
11302 EnableIfTST->getTemplateName().getAsTemplateDecl();
11303 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11304 return false;
11305
11306 // ... called "enable_if".
11307 const IdentifierInfo *EnableIfII =
11308 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11309 if (!EnableIfII || !EnableIfII->isStr(Str: "enable_if"))
11310 return false;
11311
11312 // Assume the first template argument is the condition.
11313 CondRange = EnableIfTSTLoc.getArgLoc(i: 0).getSourceRange();
11314
11315 // Dig out the condition.
11316 Cond = nullptr;
11317 if (EnableIfTSTLoc.getArgLoc(i: 0).getArgument().getKind()
11318 != TemplateArgument::Expression)
11319 return true;
11320
11321 Cond = EnableIfTSTLoc.getArgLoc(i: 0).getSourceExpression();
11322
11323 // Ignore Boolean literals; they add no value.
11324 if (isa<CXXBoolLiteralExpr>(Val: Cond->IgnoreParenCasts()))
11325 Cond = nullptr;
11326
11327 return true;
11328}
11329
11330QualType
11331Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11332 SourceLocation KeywordLoc,
11333 NestedNameSpecifierLoc QualifierLoc,
11334 const IdentifierInfo &II,
11335 SourceLocation IILoc,
11336 TypeSourceInfo **TSI,
11337 bool DeducedTSTContext) {
11338 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11339 DeducedTSTContext);
11340 if (T.isNull())
11341 return QualType();
11342
11343 TypeLocBuilder TLB;
11344 if (isa<DependentNameType>(Val: T)) {
11345 auto TL = TLB.push<DependentNameTypeLoc>(T);
11346 TL.setElaboratedKeywordLoc(KeywordLoc);
11347 TL.setQualifierLoc(QualifierLoc);
11348 TL.setNameLoc(IILoc);
11349 } else if (isa<DeducedTemplateSpecializationType>(Val: T)) {
11350 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
11351 TL.setElaboratedKeywordLoc(KeywordLoc);
11352 TL.setQualifierLoc(QualifierLoc);
11353 TL.setNameLoc(IILoc);
11354 } else if (isa<TemplateTypeParmType>(Val: T)) {
11355 // FIXME: There might be a 'typename' keyword here, but we just drop it
11356 // as it can't be represented.
11357 assert(!QualifierLoc);
11358 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11359 } else if (isa<TagType>(Val: T)) {
11360 auto TL = TLB.push<TagTypeLoc>(T);
11361 TL.setElaboratedKeywordLoc(KeywordLoc);
11362 TL.setQualifierLoc(QualifierLoc);
11363 TL.setNameLoc(IILoc);
11364 } else if (isa<TypedefType>(Val: T)) {
11365 TLB.push<TypedefTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11366 } else {
11367 TLB.push<UnresolvedUsingTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11368 }
11369 *TSI = TLB.getTypeSourceInfo(Context, T);
11370 return T;
11371}
11372
11373/// Build the type that describes a C++ typename specifier,
11374/// e.g., "typename T::type".
11375QualType
11376Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11377 SourceLocation KeywordLoc,
11378 NestedNameSpecifierLoc QualifierLoc,
11379 const IdentifierInfo &II,
11380 SourceLocation IILoc, bool DeducedTSTContext) {
11381 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11382
11383 CXXScopeSpec SS;
11384 SS.Adopt(Other: QualifierLoc);
11385
11386 DeclContext *Ctx = nullptr;
11387 if (QualifierLoc) {
11388 Ctx = computeDeclContext(SS);
11389 if (!Ctx) {
11390 // If the nested-name-specifier is dependent and couldn't be
11391 // resolved to a type, build a typename type.
11392 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11393 return Context.getDependentNameType(Keyword,
11394 NNS: QualifierLoc.getNestedNameSpecifier(),
11395 Name: &II);
11396 }
11397
11398 // If the nested-name-specifier refers to the current instantiation,
11399 // the "typename" keyword itself is superfluous. In C++03, the
11400 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11401 // allows such extraneous "typename" keywords, and we retroactively
11402 // apply this DR to C++03 code with only a warning. In any case we continue.
11403
11404 if (RequireCompleteDeclContext(SS, DC: Ctx))
11405 return QualType();
11406 }
11407
11408 DeclarationName Name(&II);
11409 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11410 if (Ctx)
11411 LookupQualifiedName(R&: Result, LookupCtx: Ctx, SS);
11412 else
11413 LookupName(R&: Result, S: CurScope);
11414 unsigned DiagID = 0;
11415 Decl *Referenced = nullptr;
11416 switch (Result.getResultKind()) {
11417 case LookupResultKind::NotFound: {
11418 // If we're looking up 'type' within a template named 'enable_if', produce
11419 // a more specific diagnostic.
11420 SourceRange CondRange;
11421 Expr *Cond = nullptr;
11422 if (Ctx && isEnableIf(NNS: QualifierLoc, II, CondRange, Cond)) {
11423 // If we have a condition, narrow it down to the specific failed
11424 // condition.
11425 if (Cond) {
11426 Expr *FailedCond;
11427 std::string FailedDescription;
11428 std::tie(args&: FailedCond, args&: FailedDescription) =
11429 findFailedBooleanCondition(Cond);
11430
11431 Diag(Loc: FailedCond->getExprLoc(),
11432 DiagID: diag::err_typename_nested_not_found_requirement)
11433 << FailedDescription
11434 << FailedCond->getSourceRange();
11435 return QualType();
11436 }
11437
11438 Diag(Loc: CondRange.getBegin(),
11439 DiagID: diag::err_typename_nested_not_found_enable_if)
11440 << Ctx << CondRange;
11441 return QualType();
11442 }
11443
11444 DiagID = Ctx ? diag::err_typename_nested_not_found
11445 : diag::err_unknown_typename;
11446 break;
11447 }
11448
11449 case LookupResultKind::FoundUnresolvedValue: {
11450 // We found a using declaration that is a value. Most likely, the using
11451 // declaration itself is meant to have the 'typename' keyword.
11452 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11453 IILoc);
11454 Diag(Loc: IILoc, DiagID: diag::err_typename_refers_to_using_value_decl)
11455 << Name << Ctx << FullRange;
11456 if (UnresolvedUsingValueDecl *Using
11457 = dyn_cast<UnresolvedUsingValueDecl>(Val: Result.getRepresentativeDecl())){
11458 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11459 Diag(Loc, DiagID: diag::note_using_value_decl_missing_typename)
11460 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
11461 }
11462 }
11463 // Fall through to create a dependent typename type, from which we can
11464 // recover better.
11465 [[fallthrough]];
11466
11467 case LookupResultKind::NotFoundInCurrentInstantiation:
11468 // Okay, it's a member of an unknown instantiation.
11469 return Context.getDependentNameType(Keyword,
11470 NNS: QualifierLoc.getNestedNameSpecifier(),
11471 Name: &II);
11472
11473 case LookupResultKind::Found:
11474 // FXIME: Missing support for UsingShadowDecl on this path?
11475 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: Result.getFoundDecl())) {
11476 // C++ [class.qual]p2:
11477 // In a lookup in which function names are not ignored and the
11478 // nested-name-specifier nominates a class C, if the name specified
11479 // after the nested-name-specifier, when looked up in C, is the
11480 // injected-class-name of C [...] then the name is instead considered
11481 // to name the constructor of class C.
11482 //
11483 // Unlike in an elaborated-type-specifier, function names are not ignored
11484 // in typename-specifier lookup. However, they are ignored in all the
11485 // contexts where we form a typename type with no keyword (that is, in
11486 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11487 //
11488 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11489 // ignore functions, but that appears to be an oversight.
11490 checkTypeDeclType(LookupCtx: Ctx,
11491 DCK: Keyword == ElaboratedTypeKeyword::Typename
11492 ? DiagCtorKind::Typename
11493 : DiagCtorKind::None,
11494 TD: Type, NameLoc: IILoc);
11495 // FIXME: This appears to be the only case where a template type parameter
11496 // can have an elaborated keyword. We should preserve it somehow.
11497 if (isa<TemplateTypeParmDecl>(Val: Type)) {
11498 assert(Keyword == ElaboratedTypeKeyword::Typename);
11499 assert(!QualifierLoc);
11500 Keyword = ElaboratedTypeKeyword::None;
11501 }
11502 return Context.getTypeDeclType(
11503 Keyword, Qualifier: QualifierLoc.getNestedNameSpecifier(), Decl: Type);
11504 }
11505
11506 // C++ [dcl.type.simple]p2:
11507 // A type-specifier of the form
11508 // typename[opt] nested-name-specifier[opt] template-name
11509 // is a placeholder for a deduced class type [...].
11510 if (getLangOpts().CPlusPlus17) {
11511 if (auto *TD = getAsTypeTemplateDecl(D: Result.getFoundDecl())) {
11512 if (!DeducedTSTContext) {
11513 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11514 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11515 Diag(Loc: IILoc, DiagID: diag::err_dependent_deduced_tst)
11516 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
11517 << QualType(Qualifier.getAsType(), 0);
11518 else
11519 Diag(Loc: IILoc, DiagID: diag::err_deduced_tst)
11520 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD));
11521 NoteTemplateLocation(Decl: *TD);
11522 return QualType();
11523 }
11524 TemplateName Name = Context.getQualifiedTemplateName(
11525 Qualifier: QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11526 Template: TemplateName(TD));
11527 return Context.getDeducedTemplateSpecializationType(
11528 DK: DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11529 Template: Name);
11530 }
11531 }
11532
11533 DiagID = Ctx ? diag::err_typename_nested_not_type
11534 : diag::err_typename_not_type;
11535 Referenced = Result.getFoundDecl();
11536 break;
11537
11538 case LookupResultKind::FoundOverloaded:
11539 DiagID = Ctx ? diag::err_typename_nested_not_type
11540 : diag::err_typename_not_type;
11541 Referenced = *Result.begin();
11542 break;
11543
11544 case LookupResultKind::Ambiguous:
11545 return QualType();
11546 }
11547
11548 // If we get here, it's because name lookup did not find a
11549 // type. Emit an appropriate diagnostic and return an error.
11550 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11551 IILoc);
11552 if (Ctx)
11553 Diag(Loc: IILoc, DiagID) << FullRange << Name << Ctx;
11554 else
11555 Diag(Loc: IILoc, DiagID) << FullRange << Name;
11556 if (Referenced)
11557 Diag(Loc: Referenced->getLocation(),
11558 DiagID: Ctx ? diag::note_typename_member_refers_here
11559 : diag::note_typename_refers_here)
11560 << Name;
11561 return QualType();
11562}
11563
11564namespace {
11565 // See Sema::RebuildTypeInCurrentInstantiation
11566 class CurrentInstantiationRebuilder
11567 : public TreeTransform<CurrentInstantiationRebuilder> {
11568 SourceLocation Loc;
11569 DeclarationName Entity;
11570
11571 public:
11572 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11573
11574 CurrentInstantiationRebuilder(Sema &SemaRef,
11575 SourceLocation Loc,
11576 DeclarationName Entity)
11577 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11578 Loc(Loc), Entity(Entity) { }
11579
11580 /// Determine whether the given type \p T has already been
11581 /// transformed.
11582 ///
11583 /// For the purposes of type reconstruction, a type has already been
11584 /// transformed if it is NULL or if it is not dependent.
11585 bool AlreadyTransformed(QualType T) {
11586 return T.isNull() || !T->isInstantiationDependentType();
11587 }
11588
11589 /// Returns the location of the entity whose type is being
11590 /// rebuilt.
11591 SourceLocation getBaseLocation() { return Loc; }
11592
11593 /// Returns the name of the entity whose type is being rebuilt.
11594 DeclarationName getBaseEntity() { return Entity; }
11595
11596 /// Sets the "base" location and entity when that
11597 /// information is known based on another transformation.
11598 void setBase(SourceLocation Loc, DeclarationName Entity) {
11599 this->Loc = Loc;
11600 this->Entity = Entity;
11601 }
11602
11603 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11604 // Lambdas never need to be transformed.
11605 return E;
11606 }
11607 };
11608} // end anonymous namespace
11609
11610TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11611 SourceLocation Loc,
11612 DeclarationName Name) {
11613 if (!T || !T->getType()->isInstantiationDependentType())
11614 return T;
11615
11616 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11617 return Rebuilder.TransformType(TSI: T);
11618}
11619
11620ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11621 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11622 DeclarationName());
11623 return Rebuilder.TransformExpr(E);
11624}
11625
11626bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11627 if (SS.isInvalid())
11628 return true;
11629
11630 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11631 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11632 DeclarationName());
11633 NestedNameSpecifierLoc Rebuilt
11634 = Rebuilder.TransformNestedNameSpecifierLoc(NNS: QualifierLoc);
11635 if (!Rebuilt)
11636 return true;
11637
11638 SS.Adopt(Other: Rebuilt);
11639 return false;
11640}
11641
11642bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11643 TemplateParameterList *Params) {
11644 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11645 Decl *Param = Params->getParam(Idx: I);
11646
11647 // There is nothing to rebuild in a type parameter.
11648 if (isa<TemplateTypeParmDecl>(Val: Param))
11649 continue;
11650
11651 // Rebuild the template parameter list of a template template parameter.
11652 if (TemplateTemplateParmDecl *TTP
11653 = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) {
11654 if (RebuildTemplateParamsInCurrentInstantiation(
11655 Params: TTP->getTemplateParameters()))
11656 return true;
11657
11658 continue;
11659 }
11660
11661 // Rebuild the type of a non-type template parameter.
11662 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Val: Param);
11663 TypeSourceInfo *NewTSI
11664 = RebuildTypeInCurrentInstantiation(T: NTTP->getTypeSourceInfo(),
11665 Loc: NTTP->getLocation(),
11666 Name: NTTP->getDeclName());
11667 if (!NewTSI)
11668 return true;
11669
11670 if (NewTSI->getType()->isUndeducedType()) {
11671 // C++17 [temp.dep.expr]p3:
11672 // An id-expression is type-dependent if it contains
11673 // - an identifier associated by name lookup with a non-type
11674 // template-parameter declared with a type that contains a
11675 // placeholder type (7.1.7.4),
11676 NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: NewTSI);
11677 }
11678
11679 if (NewTSI != NTTP->getTypeSourceInfo()) {
11680 NTTP->setTypeSourceInfo(NewTSI);
11681 NTTP->setType(NewTSI->getType());
11682 }
11683 }
11684
11685 return false;
11686}
11687
11688std::string
11689Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11690 const TemplateArgumentList &Args) {
11691 return getTemplateArgumentBindingsText(Params, Args: Args.data(), NumArgs: Args.size());
11692}
11693
11694std::string
11695Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11696 const TemplateArgument *Args,
11697 unsigned NumArgs) {
11698 SmallString<128> Str;
11699 llvm::raw_svector_ostream Out(Str);
11700
11701 if (!Params || Params->size() == 0 || NumArgs == 0)
11702 return std::string();
11703
11704 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11705 if (I >= NumArgs)
11706 break;
11707
11708 if (I == 0)
11709 Out << "[with ";
11710 else
11711 Out << ", ";
11712
11713 if (const IdentifierInfo *Id = Params->getParam(Idx: I)->getIdentifier()) {
11714 Out << Id->getName();
11715 } else {
11716 Out << '$' << I;
11717 }
11718
11719 Out << " = ";
11720 Args[I].print(Policy: getPrintingPolicy(), Out,
11721 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
11722 Policy: getPrintingPolicy(), TPL: Params, Idx: I));
11723 }
11724
11725 Out << ']';
11726 return std::string(Out.str());
11727}
11728
11729void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11730 CachedTokens &Toks) {
11731 if (!FD)
11732 return;
11733
11734 auto LPT = std::make_unique<LateParsedTemplate>();
11735
11736 // Take tokens to avoid allocations
11737 LPT->Toks.swap(RHS&: Toks);
11738 LPT->D = FnD;
11739 LPT->FPO = getCurFPFeatures();
11740 LateParsedTemplateMap.insert(KV: std::make_pair(x&: FD, y: std::move(LPT)));
11741
11742 FD->setLateTemplateParsed(true);
11743}
11744
11745void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11746 if (!FD)
11747 return;
11748 FD->setLateTemplateParsed(false);
11749}
11750
11751bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11752 DeclContext *DC = CurContext;
11753
11754 while (DC) {
11755 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
11756 const FunctionDecl *FD = RD->isLocalClass();
11757 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11758 } else if (DC->isTranslationUnit() || DC->isNamespace())
11759 return false;
11760
11761 DC = DC->getParent();
11762 }
11763 return false;
11764}
11765
11766namespace {
11767/// Walk the path from which a declaration was instantiated, and check
11768/// that every explicit specialization along that path is visible. This enforces
11769/// C++ [temp.expl.spec]/6:
11770///
11771/// If a template, a member template or a member of a class template is
11772/// explicitly specialized then that specialization shall be declared before
11773/// the first use of that specialization that would cause an implicit
11774/// instantiation to take place, in every translation unit in which such a
11775/// use occurs; no diagnostic is required.
11776///
11777/// and also C++ [temp.class.spec]/1:
11778///
11779/// A partial specialization shall be declared before the first use of a
11780/// class template specialization that would make use of the partial
11781/// specialization as the result of an implicit or explicit instantiation
11782/// in every translation unit in which such a use occurs; no diagnostic is
11783/// required.
11784class ExplicitSpecializationVisibilityChecker {
11785 Sema &S;
11786 SourceLocation Loc;
11787 llvm::SmallVector<Module *, 8> Modules;
11788 Sema::AcceptableKind Kind;
11789
11790public:
11791 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11792 Sema::AcceptableKind Kind)
11793 : S(S), Loc(Loc), Kind(Kind) {}
11794
11795 void check(NamedDecl *ND) {
11796 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
11797 return checkImpl(Spec: FD);
11798 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
11799 return checkImpl(Spec: RD);
11800 if (auto *VD = dyn_cast<VarDecl>(Val: ND))
11801 return checkImpl(Spec: VD);
11802 if (auto *ED = dyn_cast<EnumDecl>(Val: ND))
11803 return checkImpl(Spec: ED);
11804 }
11805
11806private:
11807 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11808 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11809 : Sema::MissingImportKind::ExplicitSpecialization;
11810 const bool Recover = true;
11811
11812 // If we got a custom set of modules (because only a subset of the
11813 // declarations are interesting), use them, otherwise let
11814 // diagnoseMissingImport intelligently pick some.
11815 if (Modules.empty())
11816 S.diagnoseMissingImport(Loc, Decl: D, MIK: Kind, Recover);
11817 else
11818 S.diagnoseMissingImport(Loc, Decl: D, DeclLoc: D->getLocation(), Modules, MIK: Kind, Recover);
11819 }
11820
11821 bool CheckMemberSpecialization(const NamedDecl *D) {
11822 return Kind == Sema::AcceptableKind::Visible
11823 ? S.hasVisibleMemberSpecialization(D)
11824 : S.hasReachableMemberSpecialization(D);
11825 }
11826
11827 bool CheckExplicitSpecialization(const NamedDecl *D) {
11828 return Kind == Sema::AcceptableKind::Visible
11829 ? S.hasVisibleExplicitSpecialization(D)
11830 : S.hasReachableExplicitSpecialization(D);
11831 }
11832
11833 bool CheckDeclaration(const NamedDecl *D) {
11834 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11835 : S.hasReachableDeclaration(D);
11836 }
11837
11838 // Check a specific declaration. There are three problematic cases:
11839 //
11840 // 1) The declaration is an explicit specialization of a template
11841 // specialization.
11842 // 2) The declaration is an explicit specialization of a member of an
11843 // templated class.
11844 // 3) The declaration is an instantiation of a template, and that template
11845 // is an explicit specialization of a member of a templated class.
11846 //
11847 // We don't need to go any deeper than that, as the instantiation of the
11848 // surrounding class / etc is not triggered by whatever triggered this
11849 // instantiation, and thus should be checked elsewhere.
11850 template<typename SpecDecl>
11851 void checkImpl(SpecDecl *Spec) {
11852 bool IsHiddenExplicitSpecialization = false;
11853 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11854 // Some invalid friend declarations are written as specializations but are
11855 // instantiated implicitly.
11856 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11857 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11858 if (SpecKind == TSK_ExplicitSpecialization) {
11859 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11860 ? !CheckMemberSpecialization(D: Spec)
11861 : !CheckExplicitSpecialization(D: Spec);
11862 } else {
11863 checkInstantiated(Spec);
11864 }
11865
11866 if (IsHiddenExplicitSpecialization)
11867 diagnose(D: Spec->getMostRecentDecl(), IsPartialSpec: false);
11868 }
11869
11870 void checkInstantiated(FunctionDecl *FD) {
11871 if (auto *TD = FD->getPrimaryTemplate())
11872 checkTemplate(TD);
11873 }
11874
11875 void checkInstantiated(CXXRecordDecl *RD) {
11876 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD);
11877 if (!SD)
11878 return;
11879
11880 auto From = SD->getSpecializedTemplateOrPartial();
11881 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11882 checkTemplate(TD);
11883 else if (auto *TD =
11884 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11885 if (!CheckDeclaration(D: TD))
11886 diagnose(D: TD, IsPartialSpec: true);
11887 checkTemplate(TD);
11888 }
11889 }
11890
11891 void checkInstantiated(VarDecl *RD) {
11892 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(Val: RD);
11893 if (!SD)
11894 return;
11895
11896 auto From = SD->getSpecializedTemplateOrPartial();
11897 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11898 checkTemplate(TD);
11899 else if (auto *TD =
11900 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11901 if (!CheckDeclaration(D: TD))
11902 diagnose(D: TD, IsPartialSpec: true);
11903 checkTemplate(TD);
11904 }
11905 }
11906
11907 void checkInstantiated(EnumDecl *FD) {}
11908
11909 template<typename TemplDecl>
11910 void checkTemplate(TemplDecl *TD) {
11911 if (TD->isMemberSpecialization()) {
11912 if (!CheckMemberSpecialization(D: TD))
11913 diagnose(D: TD->getMostRecentDecl(), IsPartialSpec: false);
11914 }
11915 }
11916};
11917} // end anonymous namespace
11918
11919void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11920 if (!getLangOpts().Modules)
11921 return;
11922
11923 ExplicitSpecializationVisibilityChecker(*this, Loc,
11924 Sema::AcceptableKind::Visible)
11925 .check(ND: Spec);
11926}
11927
11928void Sema::checkSpecializationReachability(SourceLocation Loc,
11929 NamedDecl *Spec) {
11930 if (!getLangOpts().CPlusPlusModules)
11931 return checkSpecializationVisibility(Loc, Spec);
11932
11933 ExplicitSpecializationVisibilityChecker(*this, Loc,
11934 Sema::AcceptableKind::Reachable)
11935 .check(ND: Spec);
11936}
11937
11938SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
11939 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11940 return N->getLocation();
11941 if (const auto *FD = dyn_cast<FunctionDecl>(Val: N)) {
11942 if (!FD->isFunctionTemplateSpecialization())
11943 return FD->getLocation();
11944 } else if (!isa<ClassTemplateSpecializationDecl,
11945 VarTemplateSpecializationDecl>(Val: N)) {
11946 return N->getLocation();
11947 }
11948 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11949 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11950 continue;
11951 return CSC.PointOfInstantiation;
11952 }
11953 return N->getLocation();
11954}
11955