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
179Sema::isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword,
180 const UnqualifiedId &Name, ParsedType ObjectTypePtr,
181 bool EnteringContext, TemplateTy &TemplateResult,
182 bool &MemberOfUnknownSpecialization,
183 bool AllowTypoCorrection) {
184 assert(getLangOpts().CPlusPlus && "No template names in C!");
185
186 DeclarationName TName;
187 MemberOfUnknownSpecialization = false;
188
189 switch (Name.getKind()) {
190 case UnqualifiedIdKind::IK_Identifier:
191 TName = DeclarationName(Name.Identifier);
192 break;
193
194 case UnqualifiedIdKind::IK_OperatorFunctionId:
195 TName = Context.DeclarationNames.getCXXOperatorName(
196 Op: Name.OperatorFunctionId.Operator);
197 break;
198
199 case UnqualifiedIdKind::IK_LiteralOperatorId:
200 TName = Context.DeclarationNames.getCXXLiteralOperatorName(II: Name.Identifier);
201 break;
202
203 default:
204 return TNK_Non_template;
205 }
206
207 QualType ObjectType = ObjectTypePtr.get();
208
209 AssumedTemplateKind AssumedTemplate;
210 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
211 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
212 /*RequiredTemplate=*/SourceLocation(),
213 ATK: &AssumedTemplate, AllowTypoCorrection))
214 return TNK_Non_template;
215 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
216
217 if (AssumedTemplate != AssumedTemplateKind::None) {
218 TemplateResult = TemplateTy::make(P: Context.getAssumedTemplateName(Name: TName));
219 // Let the parser know whether we found nothing or found functions; if we
220 // found nothing, we want to more carefully check whether this is actually
221 // a function template name versus some other kind of undeclared identifier.
222 return AssumedTemplate == AssumedTemplateKind::FoundNothing
223 ? TNK_Undeclared_template
224 : TNK_Function_template;
225 }
226
227 if (R.empty())
228 return TNK_Non_template;
229
230 NamedDecl *D = nullptr;
231 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *R.begin());
232 if (R.isAmbiguous()) {
233 // If we got an ambiguity involving a non-function template, treat this
234 // as a template name, and pick an arbitrary template for error recovery.
235 bool AnyFunctionTemplates = false;
236 for (NamedDecl *FoundD : R) {
237 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(D: FoundD)) {
238 if (isa<FunctionTemplateDecl>(Val: FoundTemplate))
239 AnyFunctionTemplates = true;
240 else {
241 D = FoundTemplate;
242 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: FoundD);
243 break;
244 }
245 }
246 }
247
248 // If we didn't find any templates at all, this isn't a template name.
249 // Leave the ambiguity for a later lookup to diagnose.
250 if (!D && !AnyFunctionTemplates) {
251 R.suppressDiagnostics();
252 return TNK_Non_template;
253 }
254
255 // If the only templates were function templates, filter out the rest.
256 // We'll diagnose the ambiguity later.
257 if (!D)
258 FilterAcceptableTemplateNames(R);
259 }
260
261 // At this point, we have either picked a single template name declaration D
262 // or we have a non-empty set of results R containing either one template name
263 // declaration or a set of function templates.
264
265 TemplateName Template;
266 TemplateNameKind TemplateKind;
267
268 unsigned ResultCount = R.end() - R.begin();
269 if (!D && ResultCount > 1) {
270 // We assume that we'll preserve the qualifier from a function
271 // template name in other ways.
272 Template = Context.getOverloadedTemplateName(Begin: R.begin(), End: R.end());
273 TemplateKind = TNK_Function_template;
274
275 // We'll do this lookup again later.
276 R.suppressDiagnostics();
277 } else {
278 if (!D) {
279 D = getAsTemplateNameDecl(D: *R.begin());
280 assert(D && "unambiguous result is not a template name");
281 }
282
283 if (isa<UnresolvedUsingValueDecl>(Val: D)) {
284 // We don't yet know whether this is a template-name or not.
285 MemberOfUnknownSpecialization = true;
286 return TNK_Non_template;
287 }
288
289 TemplateDecl *TD = cast<TemplateDecl>(Val: D);
290 Template =
291 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
292 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
293 if (!SS.isInvalid()) {
294 NestedNameSpecifier Qualifier = SS.getScopeRep();
295 Template = Context.getQualifiedTemplateName(Qualifier, TemplateKeyword: hasTemplateKeyword,
296 Template);
297 }
298
299 if (isa<FunctionTemplateDecl>(Val: TD)) {
300 TemplateKind = TNK_Function_template;
301
302 // We'll do this lookup again later.
303 R.suppressDiagnostics();
304 } else {
305 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
306 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
307 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
308 TemplateKind =
309 isa<TemplateTemplateParmDecl>(Val: TD)
310 ? dyn_cast<TemplateTemplateParmDecl>(Val: TD)->templateParameterKind()
311 : isa<VarTemplateDecl>(Val: TD) ? TNK_Var_template
312 : isa<ConceptDecl>(Val: TD) ? TNK_Concept_template
313 : TNK_Type_template;
314 }
315 }
316
317 if (isPackProducingBuiltinTemplateName(N: Template) && S &&
318 S->getTemplateParamParent() == nullptr)
319 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_builtin_pack_outside_template) << TName;
320 // Recover by returning the template, even though we would never be able to
321 // substitute it.
322
323 TemplateResult = TemplateTy::make(P: Template);
324 return TemplateKind;
325}
326
327bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
328 SourceLocation NameLoc, CXXScopeSpec &SS,
329 ParsedTemplateTy *Template /*=nullptr*/) {
330 // We could use redeclaration lookup here, but we don't need to: the
331 // syntactic form of a deduction guide is enough to identify it even
332 // if we can't look up the template name at all.
333 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
334 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
335 /*EnteringContext*/ false))
336 return false;
337
338 if (R.empty()) return false;
339 if (R.isAmbiguous()) {
340 // FIXME: Diagnose an ambiguity if we find at least one template.
341 R.suppressDiagnostics();
342 return false;
343 }
344
345 // We only treat template-names that name type templates as valid deduction
346 // guide names.
347 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
348 if (!TD || !getAsTypeTemplateDecl(D: TD))
349 return false;
350
351 if (Template) {
352 TemplateName Name = Context.getQualifiedTemplateName(
353 Qualifier: SS.getScopeRep(), /*TemplateKeyword=*/false, Template: TemplateName(TD));
354 *Template = TemplateTy::make(P: Name);
355 }
356 return true;
357}
358
359bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
360 SourceLocation IILoc,
361 Scope *S,
362 const CXXScopeSpec *SS,
363 TemplateTy &SuggestedTemplate,
364 TemplateNameKind &SuggestedKind) {
365 // We can't recover unless there's a dependent scope specifier preceding the
366 // template name.
367 // FIXME: Typo correction?
368 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(SS: *SS) ||
369 computeDeclContext(SS: *SS))
370 return false;
371
372 // The code is missing a 'template' keyword prior to the dependent template
373 // name.
374 SuggestedTemplate = TemplateTy::make(P: Context.getDependentTemplateName(
375 Name: {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
376 Diag(Loc: IILoc, DiagID: diag::err_template_kw_missing)
377 << SuggestedTemplate.get()
378 << FixItHint::CreateInsertion(InsertionLoc: IILoc, Code: "template ");
379 SuggestedKind = TNK_Dependent_template_name;
380 return true;
381}
382
383bool Sema::LookupTemplateName(LookupResult &Found, Scope *S, CXXScopeSpec &SS,
384 QualType ObjectType, bool EnteringContext,
385 RequiredTemplateKind RequiredTemplate,
386 AssumedTemplateKind *ATK,
387 bool AllowTypoCorrection) {
388 if (ATK)
389 *ATK = AssumedTemplateKind::None;
390
391 if (SS.isInvalid())
392 return true;
393
394 Found.setTemplateNameLookup(true);
395
396 // Determine where to perform name lookup
397 DeclContext *LookupCtx = nullptr;
398 bool IsDependent = false;
399 if (!ObjectType.isNull()) {
400 // This nested-name-specifier occurs in a member access expression, e.g.,
401 // x->B::f, and we are looking into the type of the object.
402 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
403 LookupCtx = computeDeclContext(T: ObjectType);
404 IsDependent = !LookupCtx && ObjectType->isDependentType();
405 assert((IsDependent || !ObjectType->isIncompleteType() ||
406 !ObjectType->getAs<TagType>() ||
407 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
408 "Caller should have completed object type");
409
410 // Template names cannot appear inside an Objective-C class or object type
411 // or a vector type.
412 //
413 // FIXME: This is wrong. For example:
414 //
415 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
416 // Vec<int> vi;
417 // vi.Vec<int>::~Vec<int>();
418 //
419 // ... should be accepted but we will not treat 'Vec' as a template name
420 // here. The right thing to do would be to check if the name is a valid
421 // vector component name, and look up a template name if not. And similarly
422 // for lookups into Objective-C class and object types, where the same
423 // problem can arise.
424 if (ObjectType->isObjCObjectOrInterfaceType() ||
425 ObjectType->isVectorType()) {
426 Found.clear();
427 return false;
428 }
429 } else if (SS.isNotEmpty()) {
430 // This nested-name-specifier occurs after another nested-name-specifier,
431 // so long into the context associated with the prior nested-name-specifier.
432 LookupCtx = computeDeclContext(SS, EnteringContext);
433 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
434
435 // The declaration context must be complete.
436 if (LookupCtx && RequireCompleteDeclContext(SS, DC: LookupCtx))
437 return true;
438 }
439
440 bool ObjectTypeSearchedInScope = false;
441 bool AllowFunctionTemplatesInLookup = true;
442 if (LookupCtx) {
443 // Perform "qualified" name lookup into the declaration context we
444 // computed, which is either the type of the base of a member access
445 // expression or the declaration context associated with a prior
446 // nested-name-specifier.
447 LookupQualifiedName(R&: Found, LookupCtx);
448
449 // FIXME: The C++ standard does not clearly specify what happens in the
450 // case where the object type is dependent, and implementations vary. In
451 // Clang, we treat a name after a . or -> as a template-name if lookup
452 // finds a non-dependent member or member of the current instantiation that
453 // is a type template, or finds no such members and lookup in the context
454 // of the postfix-expression finds a type template. In the latter case, the
455 // name is nonetheless dependent, and we may resolve it to a member of an
456 // unknown specialization when we come to instantiate the template.
457 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
458 }
459
460 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
461 // C++ [basic.lookup.classref]p1:
462 // In a class member access expression (5.2.5), if the . or -> token is
463 // immediately followed by an identifier followed by a <, the
464 // identifier must be looked up to determine whether the < is the
465 // beginning of a template argument list (14.2) or a less-than operator.
466 // The identifier is first looked up in the class of the object
467 // expression. If the identifier is not found, it is then looked up in
468 // the context of the entire postfix-expression and shall name a class
469 // template.
470 if (S)
471 LookupName(R&: Found, S);
472
473 if (!ObjectType.isNull()) {
474 // FIXME: We should filter out all non-type templates here, particularly
475 // variable templates and concepts. But the exclusion of alias templates
476 // and template template parameters is a wording defect.
477 AllowFunctionTemplatesInLookup = false;
478 ObjectTypeSearchedInScope = true;
479 }
480
481 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
482 }
483
484 if (Found.isAmbiguous())
485 return false;
486
487 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
488 !RequiredTemplate.hasTemplateKeyword()) {
489 // C++2a [temp.names]p2:
490 // A name is also considered to refer to a template if it is an
491 // unqualified-id followed by a < and name lookup finds either one or more
492 // functions or finds nothing.
493 //
494 // To keep our behavior consistent, we apply the "finds nothing" part in
495 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
496 // successfully form a call to an undeclared template-id.
497 bool AllFunctions =
498 getLangOpts().CPlusPlus20 && llvm::all_of(Range&: Found, P: [](NamedDecl *ND) {
499 return isa<FunctionDecl>(Val: ND->getUnderlyingDecl());
500 });
501 if (AllFunctions || (Found.empty() && !IsDependent)) {
502 // If lookup found any functions, or if this is a name that can only be
503 // used for a function, then strongly assume this is a function
504 // template-id.
505 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
506 ? AssumedTemplateKind::FoundNothing
507 : AssumedTemplateKind::FoundFunctions;
508 Found.clear();
509 return false;
510 }
511 }
512
513 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
514 // If we did not find any names, and this is not a disambiguation, attempt
515 // to correct any typos.
516 DeclarationName Name = Found.getLookupName();
517 Found.clear();
518
519 class TemplateNameLookupValidatorCCC final
520 : public QualifiedLookupValidatorCCC {
521 public:
522 using QualifiedLookupValidatorCCC::QualifiedLookupValidatorCCC;
523
524 bool ValidateCandidate(const TypoCorrection &Candidate) final {
525 if (const NamedDecl *ND = Candidate.getCorrectionDecl();
526 !ND || !isa<TemplateDecl>(Val: ND))
527 return false;
528 return QualifiedLookupValidatorCCC::ValidateCandidate(Candidate);
529 }
530
531 std::unique_ptr<CorrectionCandidateCallback> clone() final {
532 return std::make_unique<TemplateNameLookupValidatorCCC>(args&: *this);
533 }
534 };
535
536 TemplateNameLookupValidatorCCC FilterCCC(!SS.isEmpty());
537 FilterCCC.WantTypeSpecifiers = false;
538 FilterCCC.WantExpressionKeywords = false;
539 FilterCCC.WantRemainingKeywords = false;
540 FilterCCC.WantCXXNamedCasts = true;
541 if (TypoCorrection Corrected = CorrectTypo(
542 Typo: Found.getLookupNameInfo(), LookupKind: Found.getLookupKind(), S, SS: &SS, CCC&: FilterCCC,
543 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
544 if (auto *ND = Corrected.getFoundDecl())
545 Found.addDecl(D: ND);
546 FilterAcceptableTemplateNames(R&: Found);
547 if (Found.isAmbiguous()) {
548 Found.clear();
549 } else if (!Found.empty()) {
550 // Do not erase the typo-corrected result to avoid duplicated
551 // diagnostics.
552 AllowFunctionTemplatesInLookup = true;
553 Found.setLookupName(Corrected.getCorrection());
554 if (LookupCtx) {
555 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
556 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
557 Name.getAsString() == CorrectedStr;
558 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_template_suggest)
559 << Name << LookupCtx << DroppedSpecifier
560 << SS.getRange());
561 } else {
562 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_template_suggest) << Name);
563 }
564
565 if (Corrected.WillReplaceSpecifier()) {
566 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
567 // In order to be valid, a non-empty CXXScopeSpec needs a source
568 // range.
569 SS.MakeTrivial(Context, Qualifier: NNS,
570 R: NNS ? Found.getNameLoc() : SourceRange());
571 }
572 }
573 }
574 }
575
576 NamedDecl *ExampleLookupResult =
577 Found.empty() ? nullptr : Found.getRepresentativeDecl();
578 FilterAcceptableTemplateNames(R&: Found, AllowFunctionTemplates: AllowFunctionTemplatesInLookup);
579 if (Found.empty()) {
580 if (IsDependent) {
581 Found.setNotFoundInCurrentInstantiation();
582 return false;
583 }
584
585 // If a 'template' keyword was used, a lookup that finds only non-template
586 // names is an error.
587 if (ExampleLookupResult && RequiredTemplate) {
588 Diag(Loc: Found.getNameLoc(), DiagID: diag::err_template_kw_refers_to_non_template)
589 << Found.getLookupName() << SS.getRange()
590 << RequiredTemplate.hasTemplateKeyword()
591 << RequiredTemplate.getTemplateKeywordLoc();
592 Diag(Loc: ExampleLookupResult->getUnderlyingDecl()->getLocation(),
593 DiagID: diag::note_template_kw_refers_to_non_template)
594 << Found.getLookupName();
595 return true;
596 }
597
598 return false;
599 }
600
601 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
602 !getLangOpts().CPlusPlus11) {
603 // C++03 [basic.lookup.classref]p1:
604 // [...] If the lookup in the class of the object expression finds a
605 // template, the name is also looked up in the context of the entire
606 // postfix-expression and [...]
607 //
608 // Note: C++11 does not perform this second lookup.
609 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
610 LookupOrdinaryName);
611 FoundOuter.setTemplateNameLookup(true);
612 LookupName(R&: FoundOuter, S);
613 // FIXME: We silently accept an ambiguous lookup here, in violation of
614 // [basic.lookup]/1.
615 FilterAcceptableTemplateNames(R&: FoundOuter, /*AllowFunctionTemplates=*/false);
616
617 NamedDecl *OuterTemplate;
618 if (FoundOuter.empty()) {
619 // - if the name is not found, the name found in the class of the
620 // object expression is used, otherwise
621 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
622 !(OuterTemplate =
623 getAsTemplateNameDecl(D: FoundOuter.getFoundDecl()))) {
624 // - if the name is found in the context of the entire
625 // postfix-expression and does not name a class template, the name
626 // found in the class of the object expression is used, otherwise
627 FoundOuter.clear();
628 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
629 // - if the name found is a class template, it must refer to the same
630 // entity as the one found in the class of the object expression,
631 // otherwise the program is ill-formed.
632 if (!Found.isSingleResult() ||
633 getAsTemplateNameDecl(D: Found.getFoundDecl())->getCanonicalDecl() !=
634 OuterTemplate->getCanonicalDecl()) {
635 Diag(Loc: Found.getNameLoc(),
636 DiagID: diag::ext_nested_name_member_ref_lookup_ambiguous)
637 << Found.getLookupName()
638 << ObjectType;
639 Diag(Loc: Found.getRepresentativeDecl()->getLocation(),
640 DiagID: diag::note_ambig_member_ref_object_type)
641 << ObjectType;
642 Diag(Loc: FoundOuter.getFoundDecl()->getLocation(),
643 DiagID: diag::note_ambig_member_ref_scope);
644
645 // Recover by taking the template that we found in the object
646 // expression's type.
647 }
648 }
649 }
650
651 return false;
652}
653
654void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
655 SourceLocation Less,
656 SourceLocation Greater) {
657 if (TemplateName.isInvalid())
658 return;
659
660 DeclarationNameInfo NameInfo;
661 CXXScopeSpec SS;
662 LookupNameKind LookupKind;
663
664 DeclContext *LookupCtx = nullptr;
665 NamedDecl *Found = nullptr;
666 bool MissingTemplateKeyword = false;
667
668 // Figure out what name we looked up.
669 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: TemplateName.get())) {
670 NameInfo = DRE->getNameInfo();
671 SS.Adopt(Other: DRE->getQualifierLoc());
672 LookupKind = LookupOrdinaryName;
673 Found = DRE->getFoundDecl();
674 } else if (auto *ME = dyn_cast<MemberExpr>(Val: TemplateName.get())) {
675 NameInfo = ME->getMemberNameInfo();
676 SS.Adopt(Other: ME->getQualifierLoc());
677 LookupKind = LookupMemberName;
678 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
679 Found = ME->getMemberDecl();
680 } else if (auto *DSDRE =
681 dyn_cast<DependentScopeDeclRefExpr>(Val: TemplateName.get())) {
682 NameInfo = DSDRE->getNameInfo();
683 SS.Adopt(Other: DSDRE->getQualifierLoc());
684 MissingTemplateKeyword = true;
685 } else if (auto *DSME =
686 dyn_cast<CXXDependentScopeMemberExpr>(Val: TemplateName.get())) {
687 NameInfo = DSME->getMemberNameInfo();
688 SS.Adopt(Other: DSME->getQualifierLoc());
689 MissingTemplateKeyword = true;
690 } else {
691 llvm_unreachable("unexpected kind of potential template name");
692 }
693
694 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
695 // was missing.
696 if (MissingTemplateKeyword) {
697 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_template_kw_missing)
698 << NameInfo.getName() << SourceRange(Less, Greater);
699 return;
700 }
701
702 // Try to correct the name by looking for templates and C++ named casts.
703 struct TemplateCandidateFilter : CorrectionCandidateCallback {
704 Sema &S;
705 TemplateCandidateFilter(Sema &S) : S(S) {
706 WantTypeSpecifiers = false;
707 WantExpressionKeywords = false;
708 WantRemainingKeywords = false;
709 WantCXXNamedCasts = true;
710 };
711 bool ValidateCandidate(const TypoCorrection &Candidate) override {
712 if (auto *ND = Candidate.getCorrectionDecl())
713 return S.getAsTemplateNameDecl(D: ND);
714 return Candidate.isKeyword();
715 }
716
717 std::unique_ptr<CorrectionCandidateCallback> clone() override {
718 return std::make_unique<TemplateCandidateFilter>(args&: *this);
719 }
720 };
721
722 DeclarationName Name = NameInfo.getName();
723 TemplateCandidateFilter CCC(*this);
724 if (TypoCorrection Corrected =
725 CorrectTypo(Typo: NameInfo, LookupKind, S, SS: &SS, CCC,
726 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
727 auto *ND = Corrected.getFoundDecl();
728 if (ND)
729 ND = getAsTemplateNameDecl(D: ND);
730 if (ND || Corrected.isKeyword()) {
731 if (LookupCtx) {
732 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
733 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
734 Name.getAsString() == CorrectedStr;
735 diagnoseTypo(Correction: Corrected,
736 TypoDiag: PDiag(DiagID: diag::err_non_template_in_member_template_id_suggest)
737 << Name << LookupCtx << DroppedSpecifier
738 << SS.getRange(), ErrorRecovery: false);
739 } else {
740 diagnoseTypo(Correction: Corrected,
741 TypoDiag: PDiag(DiagID: diag::err_non_template_in_template_id_suggest)
742 << Name, ErrorRecovery: false);
743 }
744 if (Found)
745 Diag(Loc: Found->getLocation(),
746 DiagID: diag::note_non_template_in_template_id_found);
747 return;
748 }
749 }
750
751 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_non_template_in_template_id)
752 << Name << SourceRange(Less, Greater);
753 if (Found)
754 Diag(Loc: Found->getLocation(), DiagID: diag::note_non_template_in_template_id_found);
755}
756
757ExprResult
758Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
759 SourceLocation TemplateKWLoc,
760 const DeclarationNameInfo &NameInfo,
761 bool isAddressOfOperand,
762 const TemplateArgumentListInfo *TemplateArgs) {
763 if (SS.isEmpty()) {
764 // FIXME: This codepath is only used by dependent unqualified names
765 // (e.g. a dependent conversion-function-id, or operator= once we support
766 // it). It doesn't quite do the right thing, and it will silently fail if
767 // getCurrentThisType() returns null.
768 QualType ThisType = getCurrentThisType();
769 if (ThisType.isNull())
770 return ExprError();
771
772 return CXXDependentScopeMemberExpr::Create(
773 Ctx: Context, /*Base=*/nullptr, BaseType: ThisType,
774 /*IsArrow=*/!Context.getLangOpts().HLSL,
775 /*OperatorLoc=*/SourceLocation(),
776 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
777 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
778 }
779 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
780}
781
782ExprResult
783Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
784 SourceLocation TemplateKWLoc,
785 const DeclarationNameInfo &NameInfo,
786 const TemplateArgumentListInfo *TemplateArgs) {
787 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
788 if (!SS.isValid())
789 return CreateRecoveryExpr(
790 Begin: SS.getBeginLoc(),
791 End: TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), SubExprs: {});
792
793 return DependentScopeDeclRefExpr::Create(
794 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
795 TemplateArgs);
796}
797
798ExprResult
799Sema::BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
800 QualType ParamType, SourceLocation Loc,
801 TemplateArgument Arg,
802 UnsignedOrNone PackIndex, bool Final) {
803 // The template argument itself might be an expression, in which case we just
804 // return that expression. This happens when substituting into an alias
805 // template.
806 Expr *Replacement;
807 if (Arg.getKind() == TemplateArgument::Expression) {
808 Replacement = Arg.getAsExpr();
809 } else {
810 ExprResult result =
811 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
812 if (result.isInvalid())
813 return ExprError();
814 Replacement = result.get();
815 }
816 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
817 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
818 AssociatedDecl, ParamType, Index, PackIndex, Final);
819}
820
821bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
822 NamedDecl *Instantiation,
823 bool InstantiatedFromMember,
824 const NamedDecl *Pattern,
825 const NamedDecl *PatternDef,
826 TemplateSpecializationKind TSK,
827 bool Complain, bool *Unreachable) {
828 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
829 isa<VarDecl>(Instantiation));
830
831 bool IsEntityBeingDefined = false;
832 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(Val: PatternDef))
833 IsEntityBeingDefined = TD->isBeingDefined();
834
835 if (PatternDef && !IsEntityBeingDefined) {
836 NamedDecl *SuggestedDef = nullptr;
837 if (!hasReachableDefinition(D: const_cast<NamedDecl *>(PatternDef),
838 Suggested: &SuggestedDef,
839 /*OnlyNeedComplete*/ false)) {
840 if (Unreachable)
841 *Unreachable = true;
842 // If we're allowed to diagnose this and recover, do so.
843 bool Recover = Complain && !isSFINAEContext();
844 if (Complain)
845 diagnoseMissingImport(Loc: PointOfInstantiation, Decl: SuggestedDef,
846 MIK: Sema::MissingImportKind::Definition, Recover);
847 return !Recover;
848 }
849 return false;
850 }
851
852 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
853 return true;
854
855 CanQualType InstantiationTy;
856 if (TagDecl *TD = dyn_cast<TagDecl>(Val: Instantiation))
857 InstantiationTy = Context.getCanonicalTagType(TD);
858 if (PatternDef) {
859 Diag(Loc: PointOfInstantiation,
860 DiagID: diag::err_template_instantiate_within_definition)
861 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
862 << InstantiationTy;
863 // Not much point in noting the template declaration here, since
864 // we're lexically inside it.
865 Instantiation->setInvalidDecl();
866 } else if (InstantiatedFromMember) {
867 if (isa<FunctionDecl>(Val: Instantiation)) {
868 Diag(Loc: PointOfInstantiation,
869 DiagID: diag::err_explicit_instantiation_undefined_member)
870 << /*member function*/ 1 << Instantiation->getDeclName()
871 << Instantiation->getDeclContext();
872 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
873 } else {
874 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
875 Diag(Loc: PointOfInstantiation,
876 DiagID: diag::err_implicit_instantiate_member_undefined)
877 << InstantiationTy;
878 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_member_declared_at);
879 }
880 } else {
881 if (isa<FunctionDecl>(Val: Instantiation)) {
882 Diag(Loc: PointOfInstantiation,
883 DiagID: diag::err_explicit_instantiation_undefined_func_template)
884 << Pattern;
885 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
886 } else if (isa<TagDecl>(Val: Instantiation)) {
887 Diag(Loc: PointOfInstantiation, DiagID: diag::err_template_instantiate_undefined)
888 << (TSK != TSK_ImplicitInstantiation)
889 << InstantiationTy;
890 NoteTemplateLocation(Decl: *Pattern);
891 } else {
892 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
893 if (isa<VarTemplateSpecializationDecl>(Val: Instantiation)) {
894 Diag(Loc: PointOfInstantiation,
895 DiagID: diag::err_explicit_instantiation_undefined_var_template)
896 << Instantiation;
897 Instantiation->setInvalidDecl();
898 } else
899 Diag(Loc: PointOfInstantiation,
900 DiagID: diag::err_explicit_instantiation_undefined_member)
901 << /*static data member*/ 2 << Instantiation->getDeclName()
902 << Instantiation->getDeclContext();
903 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
904 }
905 }
906
907 // In general, Instantiation isn't marked invalid to get more than one
908 // error for multiple undefined instantiations. But the code that does
909 // explicit declaration -> explicit definition conversion can't handle
910 // invalid declarations, so mark as invalid in that case.
911 if (TSK == TSK_ExplicitInstantiationDeclaration)
912 Instantiation->setInvalidDecl();
913 return true;
914}
915
916void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
917 bool SupportedForCompatibility) {
918 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
919
920 // C++23 [temp.local]p6:
921 // The name of a template-parameter shall not be bound to any following.
922 // declaration whose locus is contained by the scope to which the
923 // template-parameter belongs.
924 //
925 // When MSVC compatibility is enabled, the diagnostic is always a warning
926 // by default. Otherwise, it an error unless SupportedForCompatibility is
927 // true, in which case it is a default-to-error warning.
928 unsigned DiagId =
929 getLangOpts().MSVCCompat
930 ? diag::ext_template_param_shadow
931 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
932 : diag::err_template_param_shadow);
933 const auto *ND = cast<NamedDecl>(Val: PrevDecl);
934 Diag(Loc, DiagID: DiagId) << ND->getDeclName();
935 NoteTemplateParameterLocation(Decl: *ND);
936}
937
938TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
939 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(Val: D)) {
940 D = Temp->getTemplatedDecl();
941 return Temp;
942 }
943 return nullptr;
944}
945
946ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
947 SourceLocation EllipsisLoc) const {
948 assert(Kind == Template &&
949 "Only template template arguments can be pack expansions here");
950 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
951 "Template template argument pack expansion without packs");
952 ParsedTemplateArgument Result(*this);
953 Result.EllipsisLoc = EllipsisLoc;
954 return Result;
955}
956
957static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
958 const ParsedTemplateArgument &Arg) {
959
960 switch (Arg.getKind()) {
961 case ParsedTemplateArgument::Type: {
962 TypeSourceInfo *TSI;
963 QualType T = SemaRef.GetTypeFromParser(Ty: Arg.getAsType(), TInfo: &TSI);
964 if (!TSI)
965 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc: Arg.getNameLoc());
966 return TemplateArgumentLoc(TemplateArgument(T), TSI);
967 }
968
969 case ParsedTemplateArgument::NonType: {
970 Expr *E = Arg.getAsExpr();
971 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
972 }
973
974 case ParsedTemplateArgument::Template: {
975 TemplateName Template = Arg.getAsTemplate().get();
976 TemplateArgument TArg;
977 if (Arg.getEllipsisLoc().isValid())
978 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
979 else
980 TArg = Template;
981 return TemplateArgumentLoc(
982 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
983 Arg.getScopeSpec().getWithLocInContext(Context&: SemaRef.Context),
984 Arg.getNameLoc(), Arg.getEllipsisLoc());
985 }
986 }
987
988 llvm_unreachable("Unhandled parsed template argument");
989}
990
991void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
992 TemplateArgumentListInfo &TemplateArgs) {
993 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
994 TemplateArgs.addArgument(Loc: translateTemplateArgument(SemaRef&: *this,
995 Arg: TemplateArgsIn[I]));
996}
997
998static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
999 SourceLocation Loc,
1000 const IdentifierInfo *Name) {
1001 NamedDecl *PrevDecl =
1002 SemaRef.LookupSingleName(S, Name, Loc, NameKind: Sema::LookupOrdinaryName,
1003 Redecl: RedeclarationKind::ForVisibleRedeclaration);
1004 if (PrevDecl && PrevDecl->isTemplateParameter())
1005 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
1006}
1007
1008ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
1009 TypeSourceInfo *TInfo;
1010 QualType T = GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TInfo);
1011 if (T.isNull())
1012 return ParsedTemplateArgument();
1013 assert(TInfo && "template argument with no location");
1014
1015 // If we might have formed a deduced template specialization type, convert
1016 // it to a template template argument.
1017 if (getLangOpts().CPlusPlus17) {
1018 TypeLoc TL = TInfo->getTypeLoc();
1019 SourceLocation EllipsisLoc;
1020 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1021 EllipsisLoc = PET.getEllipsisLoc();
1022 TL = PET.getPatternLoc();
1023 }
1024
1025 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1026 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1027 CXXScopeSpec SS;
1028 SS.Adopt(Other: DTST.getQualifierLoc());
1029 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1030 TemplateTy::make(P: Name),
1031 DTST.getTemplateNameLoc());
1032 if (EllipsisLoc.isValid())
1033 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1034 return Result;
1035 }
1036 }
1037
1038 // This is a normal type template argument. Note, if the type template
1039 // argument is an injected-class-name for a template, it has a dual nature
1040 // and can be used as either a type or a template. We handle that in
1041 // convertTypeTemplateArgumentToTemplate.
1042 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1043 ParsedType.get().getAsOpaquePtr(),
1044 TInfo->getTypeLoc().getBeginLoc());
1045}
1046
1047NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1048 SourceLocation EllipsisLoc,
1049 SourceLocation KeyLoc,
1050 IdentifierInfo *ParamName,
1051 SourceLocation ParamNameLoc,
1052 unsigned Depth, unsigned Position,
1053 SourceLocation EqualLoc,
1054 ParsedType DefaultArg,
1055 bool HasTypeConstraint) {
1056 assert(S->isTemplateParamScope() &&
1057 "Template type parameter not in template parameter scope!");
1058
1059 bool IsParameterPack = EllipsisLoc.isValid();
1060 TemplateTypeParmDecl *Param
1061 = TemplateTypeParmDecl::Create(C: Context, DC: Context.getTranslationUnitDecl(),
1062 KeyLoc, NameLoc: ParamNameLoc, D: Depth, P: Position,
1063 Id: ParamName, Typename, ParameterPack: IsParameterPack,
1064 HasTypeConstraint);
1065 Param->setAccess(AS_public);
1066
1067 if (Param->isParameterPack())
1068 if (auto *CSI = getEnclosingLambdaOrBlock())
1069 CSI->LocalPacks.push_back(Elt: Param);
1070
1071 if (ParamName) {
1072 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: ParamNameLoc, Name: ParamName);
1073
1074 // Add the template parameter into the current scope.
1075 S->AddDecl(D: Param);
1076 IdResolver.AddDecl(D: Param);
1077 }
1078
1079 // C++0x [temp.param]p9:
1080 // A default template-argument may be specified for any kind of
1081 // template-parameter that is not a template parameter pack.
1082 if (DefaultArg && IsParameterPack) {
1083 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1084 DefaultArg = nullptr;
1085 }
1086
1087 // Handle the default argument, if provided.
1088 if (DefaultArg) {
1089 TypeSourceInfo *DefaultTInfo;
1090 GetTypeFromParser(Ty: DefaultArg, TInfo: &DefaultTInfo);
1091
1092 assert(DefaultTInfo && "expected source information for type");
1093
1094 // Check for unexpanded parameter packs.
1095 if (DiagnoseUnexpandedParameterPack(Loc: ParamNameLoc, T: DefaultTInfo,
1096 UPPC: UPPC_DefaultArgument))
1097 return Param;
1098
1099 // Check the template argument itself.
1100 if (CheckTemplateArgument(Arg: DefaultTInfo)) {
1101 Param->setInvalidDecl();
1102 return Param;
1103 }
1104
1105 Param->setDefaultArgument(
1106 C: Context, DefArg: TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1107 }
1108
1109 return Param;
1110}
1111
1112/// Convert the parser's template argument list representation into our form.
1113static TemplateArgumentListInfo
1114makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1115 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1116 TemplateId.RAngleLoc);
1117 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1118 TemplateId.NumArgs);
1119 S.translateTemplateArguments(TemplateArgsIn: TemplateArgsPtr, TemplateArgs);
1120 return TemplateArgs;
1121}
1122
1123bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1124
1125 TemplateName TN = TypeConstr->Template.get();
1126 NamedDecl *CD = nullptr;
1127 bool IsTypeConcept = false;
1128 bool RequiresArguments = false;
1129 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: TN.getAsTemplateDecl())) {
1130 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1131 RequiresArguments =
1132 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1133 CD = TTP;
1134 } else {
1135 CD = TN.getAsTemplateDecl();
1136 IsTypeConcept = cast<ConceptDecl>(Val: CD)->isTypeConcept();
1137 RequiresArguments = cast<ConceptDecl>(Val: CD)
1138 ->getTemplateParameters()
1139 ->getMinRequiredArguments() > 1;
1140 }
1141
1142 // C++2a [temp.param]p4:
1143 // [...] The concept designated by a type-constraint shall be a type
1144 // concept ([temp.concept]).
1145 if (!IsTypeConcept) {
1146 Diag(Loc: TypeConstr->TemplateNameLoc,
1147 DiagID: diag::err_type_constraint_non_type_concept);
1148 return true;
1149 }
1150
1151 if (CheckConceptUseInDefinition(Concept: CD, Loc: TypeConstr->TemplateNameLoc))
1152 return true;
1153
1154 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1155
1156 if (!WereArgsSpecified && RequiresArguments) {
1157 Diag(Loc: TypeConstr->TemplateNameLoc,
1158 DiagID: diag::err_type_constraint_missing_arguments)
1159 << CD;
1160 return true;
1161 }
1162 return false;
1163}
1164
1165bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1166 TemplateIdAnnotation *TypeConstr,
1167 TemplateTypeParmDecl *ConstrainedParameter,
1168 SourceLocation EllipsisLoc) {
1169 return BuildTypeConstraint(SS, TypeConstraint: TypeConstr, ConstrainedParameter, EllipsisLoc,
1170 AllowUnexpandedPack: false);
1171}
1172
1173bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1174 TemplateIdAnnotation *TypeConstr,
1175 TemplateTypeParmDecl *ConstrainedParameter,
1176 SourceLocation EllipsisLoc,
1177 bool AllowUnexpandedPack) {
1178
1179 if (CheckTypeConstraint(TypeConstr))
1180 return true;
1181
1182 TemplateName TN = TypeConstr->Template.get();
1183 TemplateDecl *CD = cast<TemplateDecl>(Val: TN.getAsTemplateDecl());
1184 UsingShadowDecl *USD = TN.getAsUsingShadowDecl();
1185
1186 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1187 TypeConstr->TemplateNameLoc);
1188
1189 TemplateArgumentListInfo TemplateArgs;
1190 if (TypeConstr->LAngleLoc.isValid()) {
1191 TemplateArgs =
1192 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TypeConstr);
1193
1194 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1195 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1196 if (DiagnoseUnexpandedParameterPack(Arg, UPPC: UPPC_TypeConstraint))
1197 return true;
1198 }
1199 }
1200 }
1201 return AttachTypeConstraint(
1202 NS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1203 NameInfo: ConceptName, NamedConcept: CD, /*FoundDecl=*/USD ? cast<NamedDecl>(Val: USD) : CD,
1204 TemplateArgs: TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1205 ConstrainedParameter, EllipsisLoc);
1206}
1207
1208template <typename ArgumentLocAppender>
1209static ExprResult formImmediatelyDeclaredConstraint(
1210 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1211 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1212 SourceLocation RAngleLoc, QualType ConstrainedType,
1213 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1214 SourceLocation EllipsisLoc) {
1215
1216 TemplateArgumentListInfo ConstraintArgs;
1217 ConstraintArgs.addArgument(
1218 Loc: S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(ConstrainedType),
1219 /*NTTPType=*/QualType(), Loc: ParamNameLoc));
1220
1221 ConstraintArgs.setRAngleLoc(RAngleLoc);
1222 ConstraintArgs.setLAngleLoc(LAngleLoc);
1223 Appender(ConstraintArgs);
1224
1225 // C++2a [temp.param]p4:
1226 // [...] This constraint-expression E is called the immediately-declared
1227 // constraint of T. [...]
1228 CXXScopeSpec SS;
1229 SS.Adopt(Other: NS);
1230 ExprResult ImmediatelyDeclaredConstraint;
1231 if (auto *CD = dyn_cast<ConceptDecl>(Val: NamedConcept)) {
1232 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1233 SS, /*TemplateKWLoc=*/SourceLocation(), ConceptNameInfo: NameInfo,
1234 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, NamedConcept: CD, TemplateArgs: &ConstraintArgs,
1235 /*DoCheckConstraintSatisfaction=*/
1236 !S.inParameterMappingSubstitution());
1237 }
1238 // We have a template template parameter
1239 else {
1240 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(Val: NamedConcept);
1241 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1242 SS, NameInfo, Template: CDT, TemplateLoc: SourceLocation(), TemplateArgs: &ConstraintArgs);
1243 }
1244 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1245 return ImmediatelyDeclaredConstraint;
1246
1247 // C++2a [temp.param]p4:
1248 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1249 //
1250 // We have the following case:
1251 //
1252 // template<typename T> concept C1 = true;
1253 // template<C1... T> struct s1;
1254 //
1255 // The constraint: (C1<T> && ...)
1256 //
1257 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1258 // any unqualified lookups for 'operator&&' here.
1259 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/Callee: nullptr,
1260 /*LParenLoc=*/SourceLocation(),
1261 LHS: ImmediatelyDeclaredConstraint.get(), Operator: BO_LAnd,
1262 EllipsisLoc, /*RHS=*/nullptr,
1263 /*RParenLoc=*/SourceLocation(),
1264 /*NumExpansions=*/std::nullopt);
1265}
1266
1267bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1268 DeclarationNameInfo NameInfo,
1269 TemplateDecl *NamedConcept,
1270 NamedDecl *FoundDecl,
1271 const TemplateArgumentListInfo *TemplateArgs,
1272 TemplateTypeParmDecl *ConstrainedParameter,
1273 SourceLocation EllipsisLoc) {
1274 // C++2a [temp.param]p4:
1275 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1276 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1277 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1278 TemplateArgs ? ASTTemplateArgumentListInfo::Create(C: Context,
1279 List: *TemplateArgs) : nullptr;
1280
1281 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1282
1283 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1284 S&: *this, NS, NameInfo, NamedConcept, FoundDecl,
1285 LAngleLoc: TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1286 RAngleLoc: TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1287 ConstrainedType: ParamAsArgument, ParamNameLoc: ConstrainedParameter->getLocation(),
1288 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1289 if (TemplateArgs)
1290 for (const auto &ArgLoc : TemplateArgs->arguments())
1291 ConstraintArgs.addArgument(Loc: ArgLoc);
1292 },
1293 EllipsisLoc);
1294 if (ImmediatelyDeclaredConstraint.isInvalid())
1295 return true;
1296
1297 auto *CL = ConceptReference::Create(C: Context, /*NNS=*/NS,
1298 /*TemplateKWLoc=*/SourceLocation{},
1299 /*ConceptNameInfo=*/NameInfo,
1300 /*FoundDecl=*/FoundDecl,
1301 /*NamedConcept=*/NamedConcept,
1302 /*ArgsWritten=*/ArgsAsWritten);
1303 ConstrainedParameter->setTypeConstraint(
1304 CR: CL, ImmediatelyDeclaredConstraint: ImmediatelyDeclaredConstraint.get(), ArgPackSubstIndex: std::nullopt);
1305 return false;
1306}
1307
1308bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1309 NonTypeTemplateParmDecl *NewConstrainedParm,
1310 NonTypeTemplateParmDecl *OrigConstrainedParm,
1311 SourceLocation EllipsisLoc) {
1312 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1313 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1314 Diag(Loc: NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1315 DiagID: diag::err_unsupported_placeholder_constraint)
1316 << NewConstrainedParm->getTypeSourceInfo()
1317 ->getTypeLoc()
1318 .getSourceRange();
1319 NewConstrainedParm->setType(TL.getType());
1320 return true;
1321 }
1322 // FIXME: Concepts: This should be the type of the placeholder, but this is
1323 // unclear in the wording right now.
1324 DeclRefExpr *Ref =
1325 BuildDeclRefExpr(D: OrigConstrainedParm, Ty: OrigConstrainedParm->getType(),
1326 VK: VK_PRValue, Loc: OrigConstrainedParm->getLocation());
1327 if (!Ref)
1328 return true;
1329 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1330 S&: *this, NS: TL.getNestedNameSpecifierLoc(), NameInfo: TL.getConceptNameInfo(),
1331 NamedConcept: TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), LAngleLoc: TL.getLAngleLoc(),
1332 RAngleLoc: TL.getRAngleLoc(), ConstrainedType: BuildDecltypeType(E: Ref),
1333 ParamNameLoc: OrigConstrainedParm->getLocation(),
1334 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1335 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1336 ConstraintArgs.addArgument(Loc: TL.getArgLoc(i: I));
1337 },
1338 EllipsisLoc);
1339 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1340 !ImmediatelyDeclaredConstraint.isUsable())
1341 return true;
1342
1343 NewConstrainedParm->setPlaceholderTypeConstraint(
1344 ImmediatelyDeclaredConstraint.get());
1345 return false;
1346}
1347
1348QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1349 SourceLocation Loc) {
1350 if (TSI->getType()->isUndeducedType()) {
1351 // C++17 [temp.dep.expr]p3:
1352 // An id-expression is type-dependent if it contains
1353 // - an identifier associated by name lookup with a non-type
1354 // template-parameter declared with a type that contains a
1355 // placeholder type (7.1.7.4),
1356 TypeSourceInfo *NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSI);
1357 if (!NewTSI)
1358 return QualType();
1359 TSI = NewTSI;
1360 }
1361
1362 return CheckNonTypeTemplateParameterType(T: TSI->getType(), Loc);
1363}
1364
1365bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1366 if (T->isDependentType())
1367 return false;
1368
1369 if (RequireCompleteType(Loc, T, DiagID: diag::err_template_nontype_parm_incomplete))
1370 return true;
1371
1372 if (T->isStructuralType())
1373 return false;
1374
1375 // Structural types are required to be object types or lvalue references.
1376 if (T->isRValueReferenceType()) {
1377 Diag(Loc, DiagID: diag::err_template_nontype_parm_rvalue_ref) << T;
1378 return true;
1379 }
1380
1381 // Don't mention structural types in our diagnostic prior to C++20. Also,
1382 // there's not much more we can say about non-scalar non-class types --
1383 // because we can't see functions or arrays here, those can only be language
1384 // extensions.
1385 if (!getLangOpts().CPlusPlus20 ||
1386 (!T->isScalarType() && !T->isRecordType())) {
1387 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_type) << T;
1388 return true;
1389 }
1390
1391 // Structural types are required to be literal types.
1392 if (RequireLiteralType(Loc, T, DiagID: diag::err_template_nontype_parm_not_literal))
1393 return true;
1394
1395 Diag(Loc, DiagID: diag::err_template_nontype_parm_not_structural) << T;
1396
1397 // Drill down into the reason why the class is non-structural.
1398 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1399 // All members are required to be public and non-mutable, and can't be of
1400 // rvalue reference type. Check these conditions first to prefer a "local"
1401 // reason over a more distant one.
1402 for (const FieldDecl *FD : RD->fields()) {
1403 if (FD->getAccess() != AS_public) {
1404 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_non_public) << T << 0;
1405 return true;
1406 }
1407 if (FD->isMutable()) {
1408 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_mutable_field) << T;
1409 return true;
1410 }
1411 if (FD->getType()->isRValueReferenceType()) {
1412 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_rvalue_ref_field)
1413 << T;
1414 return true;
1415 }
1416 }
1417
1418 // All bases are required to be public.
1419 for (const auto &BaseSpec : RD->bases()) {
1420 if (BaseSpec.getAccessSpecifier() != AS_public) {
1421 Diag(Loc: BaseSpec.getBaseTypeLoc(), DiagID: diag::note_not_structural_non_public)
1422 << T << 1;
1423 return true;
1424 }
1425 }
1426
1427 // All subobjects are required to be of structural types.
1428 SourceLocation SubLoc;
1429 QualType SubType;
1430 int Kind = -1;
1431
1432 for (const FieldDecl *FD : RD->fields()) {
1433 QualType T = Context.getBaseElementType(QT: FD->getType());
1434 if (!T->isStructuralType()) {
1435 SubLoc = FD->getLocation();
1436 SubType = T;
1437 Kind = 0;
1438 break;
1439 }
1440 }
1441
1442 if (Kind == -1) {
1443 for (const auto &BaseSpec : RD->bases()) {
1444 QualType T = BaseSpec.getType();
1445 if (!T->isStructuralType()) {
1446 SubLoc = BaseSpec.getBaseTypeLoc();
1447 SubType = T;
1448 Kind = 1;
1449 break;
1450 }
1451 }
1452 }
1453
1454 assert(Kind != -1 && "couldn't find reason why type is not structural");
1455 Diag(Loc: SubLoc, DiagID: diag::note_not_structural_subobject)
1456 << T << Kind << SubType;
1457 T = SubType;
1458 RD = T->getAsCXXRecordDecl();
1459 }
1460
1461 return true;
1462}
1463
1464QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1465 SourceLocation Loc) {
1466 // We don't allow variably-modified types as the type of non-type template
1467 // parameters.
1468 if (T->isVariablyModifiedType()) {
1469 Diag(Loc, DiagID: diag::err_variably_modified_nontype_template_param)
1470 << T;
1471 return QualType();
1472 }
1473
1474 if (T->isBlockPointerType()) {
1475 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_type) << T;
1476 return QualType();
1477 }
1478
1479 // C++ [temp.param]p4:
1480 //
1481 // A non-type template-parameter shall have one of the following
1482 // (optionally cv-qualified) types:
1483 //
1484 // -- integral or enumeration type,
1485 if (T->isIntegralOrEnumerationType() ||
1486 // -- pointer to object or pointer to function,
1487 T->isPointerType() ||
1488 // -- lvalue reference to object or lvalue reference to function,
1489 T->isLValueReferenceType() ||
1490 // -- pointer to member,
1491 T->isMemberPointerType() ||
1492 // -- std::nullptr_t, or
1493 T->isNullPtrType() ||
1494 // -- a type that contains a placeholder type.
1495 T->isUndeducedType()) {
1496 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1497 // are ignored when determining its type.
1498 return T.getUnqualifiedType();
1499 }
1500
1501 // C++ [temp.param]p8:
1502 //
1503 // A non-type template-parameter of type "array of T" or
1504 // "function returning T" is adjusted to be of type "pointer to
1505 // T" or "pointer to function returning T", respectively.
1506 if (T->isArrayType() || T->isFunctionType())
1507 return Context.getDecayedType(T);
1508
1509 // If T is a dependent type, we can't do the check now, so we
1510 // assume that it is well-formed. Note that stripping off the
1511 // qualifiers here is not really correct if T turns out to be
1512 // an array type, but we'll recompute the type everywhere it's
1513 // used during instantiation, so that should be OK. (Using the
1514 // qualified type is equally wrong.)
1515 if (T->isDependentType())
1516 return T.getUnqualifiedType();
1517
1518 // C++20 [temp.param]p6:
1519 // -- a structural type
1520 if (RequireStructuralType(T, Loc))
1521 return QualType();
1522
1523 if (!getLangOpts().CPlusPlus20) {
1524 // FIXME: Consider allowing structural types as an extension in C++17. (In
1525 // earlier language modes, the template argument evaluation rules are too
1526 // inflexible.)
1527 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_structural_type) << T;
1528 return QualType();
1529 }
1530
1531 Diag(Loc, DiagID: diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1532 return T.getUnqualifiedType();
1533}
1534
1535NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1536 unsigned Depth,
1537 unsigned Position,
1538 SourceLocation EqualLoc,
1539 Expr *Default) {
1540 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1541
1542 // Check that we have valid decl-specifiers specified.
1543 auto CheckValidDeclSpecifiers = [this, &D] {
1544 // C++ [temp.param]
1545 // p1
1546 // template-parameter:
1547 // ...
1548 // parameter-declaration
1549 // p2
1550 // ... A storage class shall not be specified in a template-parameter
1551 // declaration.
1552 // [dcl.typedef]p1:
1553 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1554 // of a parameter-declaration
1555 const DeclSpec &DS = D.getDeclSpec();
1556 auto EmitDiag = [this](SourceLocation Loc) {
1557 Diag(Loc, DiagID: diag::err_invalid_decl_specifier_in_nontype_parm)
1558 << FixItHint::CreateRemoval(RemoveRange: Loc);
1559 };
1560 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1561 EmitDiag(DS.getStorageClassSpecLoc());
1562
1563 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1564 EmitDiag(DS.getThreadStorageClassSpecLoc());
1565
1566 // [dcl.inline]p1:
1567 // The inline specifier can be applied only to the declaration or
1568 // definition of a variable or function.
1569
1570 if (DS.isInlineSpecified())
1571 EmitDiag(DS.getInlineSpecLoc());
1572
1573 // [dcl.constexpr]p1:
1574 // The constexpr specifier shall be applied only to the definition of a
1575 // variable or variable template or the declaration of a function or
1576 // function template.
1577
1578 if (DS.hasConstexprSpecifier())
1579 EmitDiag(DS.getConstexprSpecLoc());
1580
1581 // [dcl.fct.spec]p1:
1582 // Function-specifiers can be used only in function declarations.
1583
1584 if (DS.isVirtualSpecified())
1585 EmitDiag(DS.getVirtualSpecLoc());
1586
1587 if (DS.hasExplicitSpecifier())
1588 EmitDiag(DS.getExplicitSpecLoc());
1589
1590 if (DS.isNoreturnSpecified())
1591 EmitDiag(DS.getNoreturnSpecLoc());
1592 };
1593
1594 CheckValidDeclSpecifiers();
1595
1596 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1597 if (isa<AutoType>(Val: T))
1598 Diag(Loc: D.getIdentifierLoc(),
1599 DiagID: diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1600 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1601
1602 assert(S->isTemplateParamScope() &&
1603 "Non-type template parameter not in template parameter scope!");
1604 bool Invalid = false;
1605
1606 QualType T = CheckNonTypeTemplateParameterType(TSI&: TInfo, Loc: D.getIdentifierLoc());
1607 if (T.isNull()) {
1608 T = Context.IntTy; // Recover with an 'int' type.
1609 Invalid = true;
1610 }
1611
1612 CheckFunctionOrTemplateParamDeclarator(S, D);
1613
1614 const IdentifierInfo *ParamName = D.getIdentifier();
1615 bool IsParameterPack = D.hasEllipsis();
1616 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1617 C: Context, DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
1618 IdLoc: D.getIdentifierLoc(), D: Depth, P: Position, Id: ParamName, T, ParameterPack: IsParameterPack,
1619 TInfo);
1620 Param->setAccess(AS_public);
1621
1622 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1623 if (TL.isConstrained()) {
1624 if (D.getEllipsisLoc().isInvalid() &&
1625 T->containsUnexpandedParameterPack()) {
1626 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1627 for (auto &Loc :
1628 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1629 Invalid |= DiagnoseUnexpandedParameterPack(
1630 Arg: Loc, UPPC: UnexpandedParameterPackContext::UPPC_TypeConstraint);
1631 }
1632 if (!Invalid &&
1633 AttachTypeConstraint(TL, NewConstrainedParm: Param, OrigConstrainedParm: Param, EllipsisLoc: D.getEllipsisLoc()))
1634 Invalid = true;
1635 }
1636
1637 if (Invalid)
1638 Param->setInvalidDecl();
1639
1640 if (Param->isParameterPack())
1641 if (auto *CSI = getEnclosingLambdaOrBlock())
1642 CSI->LocalPacks.push_back(Elt: Param);
1643
1644 if (ParamName) {
1645 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: D.getIdentifierLoc(),
1646 Name: ParamName);
1647
1648 // Add the template parameter into the current scope.
1649 S->AddDecl(D: Param);
1650 IdResolver.AddDecl(D: Param);
1651 }
1652
1653 // C++0x [temp.param]p9:
1654 // A default template-argument may be specified for any kind of
1655 // template-parameter that is not a template parameter pack.
1656 if (Default && IsParameterPack) {
1657 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1658 Default = nullptr;
1659 }
1660
1661 // Check the well-formedness of the default template argument, if provided.
1662 if (Default) {
1663 // Check for unexpanded parameter packs.
1664 if (DiagnoseUnexpandedParameterPack(E: Default, UPPC: UPPC_DefaultArgument))
1665 return Param;
1666
1667 Param->setDefaultArgument(
1668 C: Context, DefArg: getTrivialTemplateArgumentLoc(
1669 Arg: TemplateArgument(Default, /*IsCanonical=*/false),
1670 NTTPType: QualType(), Loc: SourceLocation()));
1671 }
1672
1673 return Param;
1674}
1675
1676/// ActOnTemplateTemplateParameter - Called when a C++ template template
1677/// parameter (e.g. T in template <template \<typename> class T> class array)
1678/// has been parsed. S is the current scope.
1679NamedDecl *Sema::ActOnTemplateTemplateParameter(
1680 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1681 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1682 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1683 unsigned Position, SourceLocation EqualLoc,
1684 ParsedTemplateArgument Default) {
1685 assert(S->isTemplateParamScope() &&
1686 "Template template parameter not in template parameter scope!");
1687
1688 bool IsParameterPack = EllipsisLoc.isValid();
1689
1690 SourceLocation Loc = NameLoc.isInvalid() ? TmpLoc : NameLoc;
1691 if (Params->size() == 0) {
1692 Diag(Loc, DiagID: diag::err_template_template_parm_no_parms)
1693 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1694
1695 // Recover as if there was a type template parameter pack.
1696 SmallVector<NamedDecl *, 4> ParamDecls;
1697 ParamDecls.push_back(Elt: TemplateTypeParmDecl::Create(
1698 C: Context, DC: Context.getTranslationUnitDecl(), KeyLoc: Loc, NameLoc: SourceLocation(),
1699 D: Depth + 1, P: 0, /*Id=*/nullptr,
1700 /*Typename=*/false, /*ParameterPack=*/true));
1701 Params = TemplateParameterList::Create(
1702 C: Context, TemplateLoc: Params->getTemplateLoc(), LAngleLoc: Params->getLAngleLoc(), Params: ParamDecls,
1703 RAngleLoc: Params->getRAngleLoc(), RequiresClause: Params->getRequiresClause());
1704 }
1705
1706 bool Invalid = false;
1707 if (CheckTemplateParameterList(
1708 NewParams: Params,
1709 /*OldParams=*/nullptr,
1710 TPC: IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1711 Invalid = true;
1712
1713 // Construct the parameter object.
1714 TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(
1715 C: Context, DC: Context.getTranslationUnitDecl(), L: Loc, D: Depth, P: Position,
1716 ParameterPack: IsParameterPack, Id: Name, ParameterKind: Kind, Typename, Params);
1717 Param->setAccess(AS_public);
1718
1719 if (Param->isParameterPack())
1720 if (auto *LSI = getEnclosingLambdaOrBlock())
1721 LSI->LocalPacks.push_back(Elt: Param);
1722
1723 // If the template template parameter has a name, then link the identifier
1724 // into the scope and lookup mechanisms.
1725 if (Name) {
1726 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: NameLoc, Name);
1727
1728 S->AddDecl(D: Param);
1729 IdResolver.AddDecl(D: Param);
1730 }
1731
1732 if (Invalid)
1733 Param->setInvalidDecl();
1734
1735 // C++0x [temp.param]p9:
1736 // A default template-argument may be specified for any kind of
1737 // template-parameter that is not a template parameter pack.
1738 if (IsParameterPack && !Default.isInvalid()) {
1739 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1740 Default = ParsedTemplateArgument();
1741 }
1742
1743 if (!Default.isInvalid()) {
1744 // Check only that we have a template template argument. We don't want to
1745 // try to check well-formedness now, because our template template parameter
1746 // might have dependent types in its template parameters, which we wouldn't
1747 // be able to match now.
1748 //
1749 // If none of the template template parameter's template arguments mention
1750 // other template parameters, we could actually perform more checking here.
1751 // However, it isn't worth doing.
1752 TemplateArgumentLoc DefaultArg = translateTemplateArgument(SemaRef&: *this, Arg: Default);
1753 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1754 Diag(Loc: DefaultArg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
1755 << DefaultArg.getSourceRange();
1756 return Param;
1757 }
1758
1759 TemplateName Name =
1760 DefaultArg.getArgument().getAsTemplateOrTemplatePattern();
1761 TemplateDecl *Template = Name.getAsTemplateDecl();
1762 if (Template &&
1763 !CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg: DefaultArg)) {
1764 return Param;
1765 }
1766
1767 // Check for unexpanded parameter packs.
1768 if (DiagnoseUnexpandedParameterPack(Loc: DefaultArg.getLocation(),
1769 Template: DefaultArg.getArgument().getAsTemplate(),
1770 UPPC: UPPC_DefaultArgument))
1771 return Param;
1772
1773 Param->setDefaultArgument(C: Context, DefArg: DefaultArg);
1774 }
1775
1776 return Param;
1777}
1778
1779namespace {
1780class ConstraintRefersToContainingTemplateChecker
1781 : public ConstDynamicRecursiveASTVisitor {
1782 using inherited = ConstDynamicRecursiveASTVisitor;
1783 bool Result = false;
1784 const FunctionDecl *Friend = nullptr;
1785 unsigned TemplateDepth = 0;
1786
1787 // Check a record-decl that we've seen to see if it is a lexical parent of the
1788 // Friend, likely because it was referred to without its template arguments.
1789 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1790 CheckingRD = CheckingRD->getMostRecentDecl();
1791 if (!CheckingRD->isTemplated())
1792 return true;
1793
1794 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1795 DC && !DC->isFileContext(); DC = DC->getParent())
1796 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
1797 if (CheckingRD == RD->getMostRecentDecl()) {
1798 Result = true;
1799 return false;
1800 }
1801
1802 return true;
1803 }
1804
1805 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1806 if (D->getDepth() < TemplateDepth)
1807 Result = true;
1808
1809 // Necessary because the type of the NTTP might be what refers to the parent
1810 // constriant.
1811 return TraverseType(T: D->getType());
1812 }
1813
1814public:
1815 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1816 unsigned TemplateDepth)
1817 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1818
1819 bool getResult() const { return Result; }
1820
1821 // This should be the only template parm type that we have to deal with.
1822 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1823 // FunctionParmPackExpr are all partially substituted, which cannot happen
1824 // with concepts at this point in translation.
1825 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1826 if (Type->getDecl()->getDepth() < TemplateDepth) {
1827 Result = true;
1828 return false;
1829 }
1830 return true;
1831 }
1832
1833 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1834 return TraverseDecl(D: E->getDecl());
1835 }
1836
1837 bool TraverseTypedefType(const TypedefType *TT,
1838 bool /*TraverseQualifier*/) override {
1839 return TraverseType(T: TT->desugar());
1840 }
1841
1842 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1843 // We don't care about TypeLocs. So traverse Types instead.
1844 return TraverseType(T: TL.getType(), TraverseQualifier);
1845 }
1846
1847 bool VisitTagType(const TagType *T) override {
1848 return TraverseDecl(D: T->getDecl());
1849 }
1850
1851 bool TraverseDecl(const Decl *D) override {
1852 assert(D);
1853 // FIXME : This is possibly an incomplete list, but it is unclear what other
1854 // Decl kinds could be used to refer to the template parameters. This is a
1855 // best guess so far based on examples currently available, but the
1856 // unreachable should catch future instances/cases.
1857 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
1858 return TraverseType(T: TD->getUnderlyingType());
1859 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Val: D))
1860 return CheckNonTypeTemplateParmDecl(D: NTTPD);
1861 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
1862 return TraverseType(T: VD->getType());
1863 if (isa<TemplateDecl>(Val: D))
1864 return true;
1865 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1866 return CheckIfContainingRecord(CheckingRD: RD);
1867
1868 if (isa<NamedDecl, RequiresExprBodyDecl>(Val: D)) {
1869 // No direct types to visit here I believe.
1870 } else
1871 llvm_unreachable("Don't know how to handle this declaration type yet");
1872 return true;
1873 }
1874};
1875} // namespace
1876
1877bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1878 const FunctionDecl *Friend, unsigned TemplateDepth,
1879 const Expr *Constraint) {
1880 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1881 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1882 Checker.TraverseStmt(S: Constraint);
1883 return Checker.getResult();
1884}
1885
1886TemplateParameterList *
1887Sema::ActOnTemplateParameterList(unsigned Depth,
1888 SourceLocation ExportLoc,
1889 SourceLocation TemplateLoc,
1890 SourceLocation LAngleLoc,
1891 ArrayRef<NamedDecl *> Params,
1892 SourceLocation RAngleLoc,
1893 Expr *RequiresClause) {
1894 if (ExportLoc.isValid())
1895 Diag(Loc: ExportLoc, DiagID: diag::warn_template_export_unsupported);
1896
1897 for (NamedDecl *P : Params)
1898 warnOnReservedIdentifier(D: P);
1899
1900 return TemplateParameterList::Create(C: Context, TemplateLoc, LAngleLoc,
1901 Params: llvm::ArrayRef(Params), RAngleLoc,
1902 RequiresClause);
1903}
1904
1905static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1906 const CXXScopeSpec &SS) {
1907 if (SS.isSet())
1908 T->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
1909}
1910
1911// Returns the template parameter list with all default template argument
1912// information.
1913TemplateParameterList *Sema::GetTemplateParameterList(TemplateDecl *TD) {
1914 // Make sure we get the template parameter list from the most
1915 // recent declaration, since that is the only one that is guaranteed to
1916 // have all the default template argument information.
1917 Decl *D = TD->getMostRecentDecl();
1918 // C++11 N3337 [temp.param]p12:
1919 // A default template argument shall not be specified in a friend class
1920 // template declaration.
1921 //
1922 // Skip past friend *declarations* because they are not supposed to contain
1923 // default template arguments. Moreover, these declarations may introduce
1924 // template parameters living in different template depths than the
1925 // corresponding template parameters in TD, causing unmatched constraint
1926 // substitution.
1927 //
1928 // FIXME: Diagnose such cases within a class template:
1929 // template <class T>
1930 // struct S {
1931 // template <class = void> friend struct C;
1932 // };
1933 // template struct S<int>;
1934 while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1935 D->getPreviousDecl())
1936 D = D->getPreviousDecl();
1937 return cast<TemplateDecl>(Val: D)->getTemplateParameters();
1938}
1939
1940DeclResult Sema::CheckClassTemplate(
1941 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1942 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1943 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1944 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1945 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1946 TemplateParameterList **OuterTemplateParamLists,
1947 bool IsMemberSpecialization, SkipBodyInfo *SkipBody) {
1948 assert(TemplateParams && TemplateParams->size() > 0 &&
1949 "No template parameters");
1950 assert(TUK != TagUseKind::Reference &&
1951 "Can only declare or define class templates");
1952 bool Invalid = false;
1953
1954 // Check that we can declare a template here.
1955 if (CheckTemplateDeclScope(S, TemplateParams))
1956 return true;
1957
1958 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
1959 assert(Kind != TagTypeKind::Enum &&
1960 "can't build template of enumerated type");
1961
1962 // There is no such thing as an unnamed class template.
1963 if (!Name) {
1964 Diag(Loc: KWLoc, DiagID: diag::err_template_unnamed_class);
1965 return true;
1966 }
1967
1968 // Find any previous declaration with this name. For a friend with no
1969 // scope explicitly specified, we only look for tag declarations (per
1970 // C++11 [basic.lookup.elab]p2).
1971 DeclContext *SemanticContext;
1972 LookupResult Previous(*this, Name, NameLoc,
1973 (SS.isEmpty() && TUK == TagUseKind::Friend)
1974 ? LookupTagName
1975 : LookupOrdinaryName,
1976 forRedeclarationInCurContext());
1977 if (SS.isNotEmpty() && !SS.isInvalid()) {
1978 SemanticContext = computeDeclContext(SS, EnteringContext: true);
1979 if (!SemanticContext) {
1980 // FIXME: Horrible, horrible hack! We can't currently represent this
1981 // in the AST, and historically we have just ignored such friend
1982 // class templates, so don't complain here.
1983 Diag(Loc: NameLoc, DiagID: TUK == TagUseKind::Friend
1984 ? diag::warn_template_qualified_friend_ignored
1985 : diag::err_template_qualified_declarator_no_match)
1986 << SS.getScopeRep() << SS.getRange();
1987 return TUK != TagUseKind::Friend;
1988 }
1989
1990 if (RequireCompleteDeclContext(SS, DC: SemanticContext))
1991 return true;
1992
1993 // If we're adding a template to a dependent context, we may need to
1994 // rebuilding some of the types used within the template parameter list,
1995 // now that we know what the current instantiation is.
1996 if (SemanticContext->isDependentContext()) {
1997 ContextRAII SavedContext(*this, SemanticContext);
1998 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
1999 Invalid = true;
2000 }
2001
2002 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference &&
2003 diagnoseQualifiedDeclaration(SS, DC: SemanticContext, Name, Loc: NameLoc,
2004 /*TemplateId=*/nullptr,
2005 IsMemberSpecialization))
2006 return true;
2007
2008 LookupQualifiedName(R&: Previous, LookupCtx: SemanticContext);
2009 } else {
2010 SemanticContext = CurContext;
2011
2012 // C++14 [class.mem]p14:
2013 // If T is the name of a class, then each of the following shall have a
2014 // name different from T:
2015 // -- every member template of class T
2016 if (TUK != TagUseKind::Friend &&
2017 DiagnoseClassNameShadow(DC: SemanticContext,
2018 Info: DeclarationNameInfo(Name, NameLoc)))
2019 return true;
2020
2021 LookupName(R&: Previous, S);
2022 }
2023
2024 if (Previous.isAmbiguous())
2025 return true;
2026
2027 // Let the template parameter scope enter the lookup chain of the current
2028 // class template. For example, given
2029 //
2030 // namespace ns {
2031 // template <class> bool Param = false;
2032 // template <class T> struct N;
2033 // }
2034 //
2035 // template <class Param> struct ns::N { void foo(Param); };
2036 //
2037 // When we reference Param inside the function parameter list, our name lookup
2038 // chain for it should be like:
2039 // FunctionScope foo
2040 // -> RecordScope N
2041 // -> TemplateParamScope (where we will find Param)
2042 // -> NamespaceScope ns
2043 //
2044 // See also CppLookupName().
2045 if (S->isTemplateParamScope())
2046 EnterTemplatedContext(S, DC: SemanticContext);
2047
2048 NamedDecl *PrevDecl = nullptr;
2049 if (Previous.begin() != Previous.end())
2050 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2051
2052 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2053 // Maybe we will complain about the shadowed template parameter.
2054 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl);
2055 // Just pretend that we didn't see the previous declaration.
2056 PrevDecl = nullptr;
2057 }
2058
2059 // If there is a previous declaration with the same name, check
2060 // whether this is a valid redeclaration.
2061 ClassTemplateDecl *PrevClassTemplate =
2062 dyn_cast_or_null<ClassTemplateDecl>(Val: PrevDecl);
2063
2064 // We may have found the injected-class-name of a class template,
2065 // class template partial specialization, or class template specialization.
2066 // In these cases, grab the template that is being defined or specialized.
2067 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(Val: PrevDecl) &&
2068 cast<CXXRecordDecl>(Val: PrevDecl)->isInjectedClassName()) {
2069 PrevDecl = cast<CXXRecordDecl>(Val: PrevDecl->getDeclContext());
2070 PrevClassTemplate
2071 = cast<CXXRecordDecl>(Val: PrevDecl)->getDescribedClassTemplate();
2072 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(Val: PrevDecl)) {
2073 PrevClassTemplate
2074 = cast<ClassTemplateSpecializationDecl>(Val: PrevDecl)
2075 ->getSpecializedTemplate();
2076 }
2077 }
2078
2079 if (TUK == TagUseKind::Friend) {
2080 // C++ [namespace.memdef]p3:
2081 // [...] When looking for a prior declaration of a class or a function
2082 // declared as a friend, and when the name of the friend class or
2083 // function is neither a qualified name nor a template-id, scopes outside
2084 // the innermost enclosing namespace scope are not considered.
2085 if (!SS.isSet()) {
2086 DeclContext *OutermostContext = CurContext;
2087 while (!OutermostContext->isFileContext())
2088 OutermostContext = OutermostContext->getLookupParent();
2089
2090 if (PrevDecl &&
2091 (OutermostContext->Equals(DC: PrevDecl->getDeclContext()) ||
2092 OutermostContext->Encloses(DC: PrevDecl->getDeclContext()))) {
2093 SemanticContext = PrevDecl->getDeclContext();
2094 } else {
2095 // Declarations in outer scopes don't matter. However, the outermost
2096 // context we computed is the semantic context for our new
2097 // declaration.
2098 PrevDecl = PrevClassTemplate = nullptr;
2099 SemanticContext = OutermostContext;
2100
2101 // Check that the chosen semantic context doesn't already contain a
2102 // declaration of this name as a non-tag type.
2103 Previous.clear(Kind: LookupOrdinaryName);
2104 DeclContext *LookupContext = SemanticContext;
2105 while (LookupContext->isTransparentContext())
2106 LookupContext = LookupContext->getLookupParent();
2107 LookupQualifiedName(R&: Previous, LookupCtx: LookupContext);
2108
2109 if (Previous.isAmbiguous())
2110 return true;
2111
2112 if (Previous.begin() != Previous.end())
2113 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2114 }
2115 }
2116 } else if (PrevDecl && !isDeclInScope(D: Previous.getRepresentativeDecl(),
2117 Ctx: SemanticContext, S, AllowInlineNamespace: SS.isValid()))
2118 PrevDecl = PrevClassTemplate = nullptr;
2119
2120 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2121 Val: PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2122 if (SS.isEmpty() &&
2123 !(PrevClassTemplate &&
2124 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2125 DC: SemanticContext->getRedeclContext()))) {
2126 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
2127 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
2128 DiagID: diag::note_using_decl_target);
2129 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
2130 // Recover by ignoring the old declaration.
2131 PrevDecl = PrevClassTemplate = nullptr;
2132 }
2133 }
2134
2135 if (PrevClassTemplate) {
2136 // Ensure that the template parameter lists are compatible. Skip this check
2137 // for a friend in a dependent context: the template parameter list itself
2138 // could be dependent.
2139 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2140 !TemplateParameterListsAreEqual(
2141 NewInstFrom: TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2142 : CurContext,
2143 CurContext, KWLoc),
2144 New: TemplateParams, OldInstFrom: PrevClassTemplate,
2145 Old: PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2146 Kind: TPL_TemplateMatch))
2147 return true;
2148
2149 // C++ [temp.class]p4:
2150 // In a redeclaration, partial specialization, explicit
2151 // specialization or explicit instantiation of a class template,
2152 // the class-key shall agree in kind with the original class
2153 // template declaration (7.1.5.3).
2154 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2155 if (!isAcceptableTagRedeclaration(
2156 Previous: PrevRecordDecl, NewTag: Kind, isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc, Name)) {
2157 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
2158 << Name
2159 << FixItHint::CreateReplacement(RemoveRange: KWLoc, Code: PrevRecordDecl->getKindName());
2160 Diag(Loc: PrevRecordDecl->getLocation(), DiagID: diag::note_previous_use);
2161 Kind = PrevRecordDecl->getTagKind();
2162 }
2163
2164 // Check for redefinition of this class template.
2165 if (TUK == TagUseKind::Definition) {
2166 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2167 // If we have a prior definition that is not visible, treat this as
2168 // simply making that previous definition visible.
2169 NamedDecl *Hidden = nullptr;
2170 bool HiddenDefVisible = false;
2171 if (SkipBody &&
2172 isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible)) {
2173 SkipBody->ShouldSkip = true;
2174 SkipBody->Previous = Def;
2175 if (!HiddenDefVisible && Hidden) {
2176 auto *Tmpl =
2177 cast<CXXRecordDecl>(Val: Hidden)->getDescribedClassTemplate();
2178 assert(Tmpl && "original definition of a class template is not a "
2179 "class template?");
2180 makeMergedDefinitionVisible(ND: Hidden);
2181 makeMergedDefinitionVisible(ND: Tmpl);
2182 }
2183 } else {
2184 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
2185 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
2186 // FIXME: Would it make sense to try to "forget" the previous
2187 // definition, as part of error recovery?
2188 return true;
2189 }
2190 }
2191 }
2192 } else if (PrevDecl) {
2193 // C++ [temp]p5:
2194 // A class template shall not have the same name as any other
2195 // template, class, function, object, enumeration, enumerator,
2196 // namespace, or type in the same scope (3.3), except as specified
2197 // in (14.5.4).
2198 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
2199 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
2200 return true;
2201 }
2202
2203 // Check the template parameter list of this declaration, possibly
2204 // merging in the template parameter list from the previous class
2205 // template declaration. Skip this check for a friend in a dependent
2206 // context, because the template parameter list might be dependent.
2207 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2208 CheckTemplateParameterList(
2209 NewParams: TemplateParams,
2210 OldParams: PrevClassTemplate ? GetTemplateParameterList(TD: PrevClassTemplate)
2211 : nullptr,
2212 TPC: (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2213 SemanticContext->isDependentContext())
2214 ? TPC_ClassTemplateMember
2215 : TUK == TagUseKind::Friend ? TPC_FriendClassTemplate
2216 : TPC_Other,
2217 SkipBody))
2218 Invalid = true;
2219
2220 if (SS.isSet()) {
2221 // If the name of the template was qualified, we must be defining the
2222 // template out-of-line.
2223 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate)
2224 return Diag(Loc: NameLoc, DiagID: TUK == TagUseKind::Friend
2225 ? diag::err_friend_decl_does_not_match
2226 : diag::err_member_decl_does_not_match)
2227 << Name << SemanticContext << /*IsDefinition*/ true
2228 << SS.getRange();
2229 }
2230
2231 // If this is a templated friend in a dependent context we should not put it
2232 // on the redecl chain. In some cases, the templated friend can be the most
2233 // recent declaration tricking the template instantiator to make substitutions
2234 // there.
2235 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2236 bool ShouldAddRedecl =
2237 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2238
2239 CXXRecordDecl *NewClass = CXXRecordDecl::Create(
2240 C: Context, TK: Kind, DC: SemanticContext, StartLoc: KWLoc, IdLoc: NameLoc, Id: Name,
2241 PrevDecl: PrevClassTemplate && ShouldAddRedecl
2242 ? PrevClassTemplate->getTemplatedDecl()
2243 : nullptr);
2244 SetNestedNameSpecifier(S&: *this, T: NewClass, SS);
2245 if (NumOuterTemplateParamLists > 0)
2246 NewClass->setTemplateParameterListsInfo(
2247 Context,
2248 TPLists: llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2249
2250 // Add alignment attributes if necessary; these attributes are checked when
2251 // the ASTContext lays out the structure.
2252 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2253 if (LangOpts.HLSL)
2254 NewClass->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
2255 AddAlignmentAttributesForRecord(RD: NewClass);
2256 AddMsStructLayoutForRecord(RD: NewClass);
2257 }
2258
2259 ClassTemplateDecl *NewTemplate
2260 = ClassTemplateDecl::Create(C&: Context, DC: SemanticContext, L: NameLoc,
2261 Name: DeclarationName(Name), Params: TemplateParams,
2262 Decl: NewClass);
2263
2264 if (ShouldAddRedecl)
2265 NewTemplate->setPreviousDecl(PrevClassTemplate);
2266
2267 NewClass->setDescribedClassTemplate(NewTemplate);
2268
2269 if (ModulePrivateLoc.isValid())
2270 NewTemplate->setModulePrivate();
2271
2272 if (IsMemberSpecialization) {
2273 assert(PrevClassTemplate &&
2274 "Member specialization without a primary template?");
2275 NewTemplate->setMemberSpecialization();
2276 }
2277
2278 // Set the access specifier.
2279 if (!Invalid && TUK != TagUseKind::Friend &&
2280 NewTemplate->getDeclContext()->isRecord())
2281 SetMemberAccessSpecifier(MemberDecl: NewTemplate, PrevMemberDecl: PrevClassTemplate, LexicalAS: AS);
2282
2283 // Set the lexical context of these templates
2284 NewClass->setLexicalDeclContext(CurContext);
2285 NewTemplate->setLexicalDeclContext(CurContext);
2286
2287 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2288 NewClass->startDefinition();
2289
2290 ProcessDeclAttributeList(S, D: NewClass, AttrList: Attr);
2291
2292 if (PrevClassTemplate) {
2293 mergeDeclAttributes(New: NewTemplate, Old: PrevClassTemplate);
2294 mergeDeclAttributes(New: NewClass, Old: PrevClassTemplate->getTemplatedDecl());
2295 }
2296
2297 AddPushedVisibilityAttribute(RD: NewClass);
2298 inferGslOwnerPointerAttribute(Record: NewClass);
2299 inferNullableClassAttribute(CRD: NewClass);
2300
2301 if (TUK != TagUseKind::Friend) {
2302 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2303 Scope *Outer = S;
2304 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2305 Outer = Outer->getParent();
2306 PushOnScopeChains(D: NewTemplate, S: Outer);
2307 } else {
2308 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2309 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2310 NewClass->setAccess(PrevClassTemplate->getAccess());
2311 }
2312
2313 NewTemplate->setObjectOfFriendDecl();
2314
2315 // Friend templates are visible in fairly strange ways.
2316 if (!CurContext->isDependentContext()) {
2317 DeclContext *DC = SemanticContext->getRedeclContext();
2318 DC->makeDeclVisibleInContext(D: NewTemplate);
2319 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2320 PushOnScopeChains(D: NewTemplate, S: EnclosingScope,
2321 /* AddToContext = */ false);
2322 }
2323
2324 FriendDecl *Friend = FriendDecl::Create(
2325 C&: Context, DC: CurContext, L: NewClass->getLocation(), Friend_: NewTemplate, FriendL: FriendLoc);
2326 Friend->setAccess(AS_public);
2327 CurContext->addDecl(D: Friend);
2328 }
2329
2330 if (PrevClassTemplate)
2331 CheckRedeclarationInModule(New: NewTemplate, Old: PrevClassTemplate);
2332
2333 if (Invalid) {
2334 NewTemplate->setInvalidDecl();
2335 NewClass->setInvalidDecl();
2336 }
2337
2338 ActOnDocumentableDecl(D: NewTemplate);
2339
2340 if (SkipBody && SkipBody->ShouldSkip)
2341 return SkipBody->Previous;
2342
2343 return NewTemplate;
2344}
2345
2346/// Diagnose the presence of a default template argument on a
2347/// template parameter, which is ill-formed in certain contexts.
2348///
2349/// \returns true if the default template argument should be dropped.
2350static bool DiagnoseDefaultTemplateArgument(Sema &S,
2351 Sema::TemplateParamListContext TPC,
2352 SourceLocation ParamLoc,
2353 SourceRange DefArgRange) {
2354 switch (TPC) {
2355 case Sema::TPC_Other:
2356 case Sema::TPC_TemplateTemplateParameterPack:
2357 return false;
2358
2359 case Sema::TPC_FunctionTemplate:
2360 case Sema::TPC_FriendFunctionTemplateDefinition:
2361 // C++ [temp.param]p9:
2362 // A default template-argument shall not be specified in a
2363 // function template declaration or a function template
2364 // definition [...]
2365 // If a friend function template declaration specifies a default
2366 // template-argument, that declaration shall be a definition and shall be
2367 // the only declaration of the function template in the translation unit.
2368 // (C++98/03 doesn't have this wording; see DR226).
2369 S.DiagCompat(Loc: ParamLoc, CompatDiagId: diag_compat::templ_default_in_function_templ)
2370 << DefArgRange;
2371 return false;
2372
2373 case Sema::TPC_ClassTemplateMember:
2374 // C++0x [temp.param]p9:
2375 // A default template-argument shall not be specified in the
2376 // template-parameter-lists of the definition of a member of a
2377 // class template that appears outside of the member's class.
2378 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_template_member)
2379 << DefArgRange;
2380 return true;
2381
2382 case Sema::TPC_FriendClassTemplate:
2383 case Sema::TPC_FriendFunctionTemplate:
2384 // C++ [temp.param]p9:
2385 // A default template-argument shall not be specified in a
2386 // friend template declaration.
2387 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_friend_template)
2388 << DefArgRange;
2389 return true;
2390
2391 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2392 // for friend function templates if there is only a single
2393 // declaration (and it is a definition). Strange!
2394 }
2395
2396 llvm_unreachable("Invalid TemplateParamListContext!");
2397}
2398
2399/// Check for unexpanded parameter packs within the template parameters
2400/// of a template template parameter, recursively.
2401static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2402 TemplateTemplateParmDecl *TTP) {
2403 // A template template parameter which is a parameter pack is also a pack
2404 // expansion.
2405 if (TTP->isParameterPack())
2406 return false;
2407
2408 TemplateParameterList *Params = TTP->getTemplateParameters();
2409 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2410 NamedDecl *P = Params->getParam(Idx: I);
2411 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: P)) {
2412 if (!TTP->isParameterPack())
2413 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2414 if (TC->hasExplicitTemplateArgs())
2415 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2416 if (S.DiagnoseUnexpandedParameterPack(Arg: ArgLoc,
2417 UPPC: Sema::UPPC_TypeConstraint))
2418 return true;
2419 continue;
2420 }
2421
2422 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) {
2423 if (!NTTP->isParameterPack() &&
2424 S.DiagnoseUnexpandedParameterPack(Loc: NTTP->getLocation(),
2425 T: NTTP->getTypeSourceInfo(),
2426 UPPC: Sema::UPPC_NonTypeTemplateParameterType))
2427 return true;
2428
2429 continue;
2430 }
2431
2432 if (TemplateTemplateParmDecl *InnerTTP
2433 = dyn_cast<TemplateTemplateParmDecl>(Val: P))
2434 if (DiagnoseUnexpandedParameterPacks(S, TTP: InnerTTP))
2435 return true;
2436 }
2437
2438 return false;
2439}
2440
2441bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2442 TemplateParameterList *OldParams,
2443 TemplateParamListContext TPC,
2444 SkipBodyInfo *SkipBody) {
2445 bool Invalid = false;
2446
2447 // C++ [temp.param]p10:
2448 // The set of default template-arguments available for use with a
2449 // template declaration or definition is obtained by merging the
2450 // default arguments from the definition (if in scope) and all
2451 // declarations in scope in the same way default function
2452 // arguments are (8.3.6).
2453 bool SawDefaultArgument = false;
2454 SourceLocation PreviousDefaultArgLoc;
2455
2456 // Dummy initialization to avoid warnings.
2457 TemplateParameterList::iterator OldParam = NewParams->end();
2458 if (OldParams)
2459 OldParam = OldParams->begin();
2460
2461 bool RemoveDefaultArguments = false;
2462 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2463 NewParamEnd = NewParams->end();
2464 NewParam != NewParamEnd; ++NewParam) {
2465 // Whether we've seen a duplicate default argument in the same translation
2466 // unit.
2467 bool RedundantDefaultArg = false;
2468 // Whether we've found inconsis inconsitent default arguments in different
2469 // translation unit.
2470 bool InconsistentDefaultArg = false;
2471 // The name of the module which contains the inconsistent default argument.
2472 std::string PrevModuleName;
2473
2474 SourceLocation OldDefaultLoc;
2475 SourceLocation NewDefaultLoc;
2476
2477 // Variable used to diagnose missing default arguments
2478 bool MissingDefaultArg = false;
2479
2480 // Variable used to diagnose non-final parameter packs
2481 bool SawParameterPack = false;
2482
2483 if (TemplateTypeParmDecl *NewTypeParm
2484 = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam)) {
2485 // Check the presence of a default argument here.
2486 if (NewTypeParm->hasDefaultArgument() &&
2487 DiagnoseDefaultTemplateArgument(
2488 S&: *this, TPC, ParamLoc: NewTypeParm->getLocation(),
2489 DefArgRange: NewTypeParm->getDefaultArgument().getSourceRange()))
2490 NewTypeParm->removeDefaultArgument();
2491
2492 // Merge default arguments for template type parameters.
2493 TemplateTypeParmDecl *OldTypeParm
2494 = OldParams? cast<TemplateTypeParmDecl>(Val: *OldParam) : nullptr;
2495 if (NewTypeParm->isParameterPack()) {
2496 assert(!NewTypeParm->hasDefaultArgument() &&
2497 "Parameter packs can't have a default argument!");
2498 SawParameterPack = true;
2499 } else if (OldTypeParm && hasVisibleDefaultArgument(D: OldTypeParm) &&
2500 NewTypeParm->hasDefaultArgument() &&
2501 (!SkipBody || !SkipBody->ShouldSkip)) {
2502 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2503 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2504 SawDefaultArgument = true;
2505
2506 if (!OldTypeParm->getOwningModule())
2507 RedundantDefaultArg = true;
2508 else if (!getASTContext().isSameDefaultTemplateArgument(X: OldTypeParm,
2509 Y: NewTypeParm)) {
2510 InconsistentDefaultArg = true;
2511 PrevModuleName =
2512 OldTypeParm->getImportedOwningModule()->getFullModuleName();
2513 }
2514 PreviousDefaultArgLoc = NewDefaultLoc;
2515 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2516 // Merge the default argument from the old declaration to the
2517 // new declaration.
2518 NewTypeParm->setInheritedDefaultArgument(C: Context, Prev: OldTypeParm);
2519 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2520 } else if (NewTypeParm->hasDefaultArgument()) {
2521 SawDefaultArgument = true;
2522 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2523 } else if (SawDefaultArgument)
2524 MissingDefaultArg = true;
2525 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2526 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam)) {
2527 // Check for unexpanded parameter packs, except in a template template
2528 // parameter pack, as in those any unexpanded packs should be expanded
2529 // along with the parameter itself.
2530 if (TPC != TPC_TemplateTemplateParameterPack &&
2531 !NewNonTypeParm->isParameterPack() &&
2532 DiagnoseUnexpandedParameterPack(Loc: NewNonTypeParm->getLocation(),
2533 T: NewNonTypeParm->getTypeSourceInfo(),
2534 UPPC: UPPC_NonTypeTemplateParameterType)) {
2535 Invalid = true;
2536 continue;
2537 }
2538
2539 // Check the presence of a default argument here.
2540 if (NewNonTypeParm->hasDefaultArgument() &&
2541 DiagnoseDefaultTemplateArgument(
2542 S&: *this, TPC, ParamLoc: NewNonTypeParm->getLocation(),
2543 DefArgRange: NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2544 NewNonTypeParm->removeDefaultArgument();
2545 }
2546
2547 // Merge default arguments for non-type template parameters
2548 NonTypeTemplateParmDecl *OldNonTypeParm
2549 = OldParams? cast<NonTypeTemplateParmDecl>(Val: *OldParam) : nullptr;
2550 if (NewNonTypeParm->isParameterPack()) {
2551 assert(!NewNonTypeParm->hasDefaultArgument() &&
2552 "Parameter packs can't have a default argument!");
2553 if (!NewNonTypeParm->isPackExpansion())
2554 SawParameterPack = true;
2555 } else if (OldNonTypeParm && hasVisibleDefaultArgument(D: OldNonTypeParm) &&
2556 NewNonTypeParm->hasDefaultArgument() &&
2557 (!SkipBody || !SkipBody->ShouldSkip)) {
2558 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2559 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2560 SawDefaultArgument = true;
2561 if (!OldNonTypeParm->getOwningModule())
2562 RedundantDefaultArg = true;
2563 else if (!getASTContext().isSameDefaultTemplateArgument(
2564 X: OldNonTypeParm, Y: NewNonTypeParm)) {
2565 InconsistentDefaultArg = true;
2566 PrevModuleName =
2567 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2568 }
2569 PreviousDefaultArgLoc = NewDefaultLoc;
2570 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2571 // Merge the default argument from the old declaration to the
2572 // new declaration.
2573 NewNonTypeParm->setInheritedDefaultArgument(C: Context, Parm: OldNonTypeParm);
2574 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2575 } else if (NewNonTypeParm->hasDefaultArgument()) {
2576 SawDefaultArgument = true;
2577 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2578 } else if (SawDefaultArgument)
2579 MissingDefaultArg = true;
2580 } else {
2581 TemplateTemplateParmDecl *NewTemplateParm
2582 = cast<TemplateTemplateParmDecl>(Val: *NewParam);
2583
2584 // Check for unexpanded parameter packs, recursively.
2585 if (::DiagnoseUnexpandedParameterPacks(S&: *this, TTP: NewTemplateParm)) {
2586 Invalid = true;
2587 continue;
2588 }
2589
2590 // Check the presence of a default argument here.
2591 if (NewTemplateParm->hasDefaultArgument() &&
2592 DiagnoseDefaultTemplateArgument(S&: *this, TPC,
2593 ParamLoc: NewTemplateParm->getLocation(),
2594 DefArgRange: NewTemplateParm->getDefaultArgument().getSourceRange()))
2595 NewTemplateParm->removeDefaultArgument();
2596
2597 // Merge default arguments for template template parameters
2598 TemplateTemplateParmDecl *OldTemplateParm
2599 = OldParams? cast<TemplateTemplateParmDecl>(Val: *OldParam) : nullptr;
2600 if (NewTemplateParm->isParameterPack()) {
2601 assert(!NewTemplateParm->hasDefaultArgument() &&
2602 "Parameter packs can't have a default argument!");
2603 if (!NewTemplateParm->isPackExpansion())
2604 SawParameterPack = true;
2605 } else if (OldTemplateParm &&
2606 hasVisibleDefaultArgument(D: OldTemplateParm) &&
2607 NewTemplateParm->hasDefaultArgument() &&
2608 (!SkipBody || !SkipBody->ShouldSkip)) {
2609 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2610 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2611 SawDefaultArgument = true;
2612 if (!OldTemplateParm->getOwningModule())
2613 RedundantDefaultArg = true;
2614 else if (!getASTContext().isSameDefaultTemplateArgument(
2615 X: OldTemplateParm, Y: NewTemplateParm)) {
2616 InconsistentDefaultArg = true;
2617 PrevModuleName =
2618 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2619 }
2620 PreviousDefaultArgLoc = NewDefaultLoc;
2621 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2622 // Merge the default argument from the old declaration to the
2623 // new declaration.
2624 NewTemplateParm->setInheritedDefaultArgument(C: Context, Prev: OldTemplateParm);
2625 PreviousDefaultArgLoc
2626 = OldTemplateParm->getDefaultArgument().getLocation();
2627 } else if (NewTemplateParm->hasDefaultArgument()) {
2628 SawDefaultArgument = true;
2629 PreviousDefaultArgLoc
2630 = NewTemplateParm->getDefaultArgument().getLocation();
2631 } else if (SawDefaultArgument)
2632 MissingDefaultArg = true;
2633 }
2634
2635 // C++11 [temp.param]p11:
2636 // If a template parameter of a primary class template or alias template
2637 // is a template parameter pack, it shall be the last template parameter.
2638 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2639 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2640 Diag(Loc: (*NewParam)->getLocation(),
2641 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
2642 Invalid = true;
2643 }
2644
2645 // [basic.def.odr]/13:
2646 // There can be more than one definition of a
2647 // ...
2648 // default template argument
2649 // ...
2650 // in a program provided that each definition appears in a different
2651 // translation unit and the definitions satisfy the [same-meaning
2652 // criteria of the ODR].
2653 //
2654 // Simply, the design of modules allows the definition of template default
2655 // argument to be repeated across translation unit. Note that the ODR is
2656 // checked elsewhere. But it is still not allowed to repeat template default
2657 // argument in the same translation unit.
2658 if (RedundantDefaultArg) {
2659 Diag(Loc: NewDefaultLoc, DiagID: diag::err_template_param_default_arg_redefinition);
2660 Diag(Loc: OldDefaultLoc, DiagID: diag::note_template_param_prev_default_arg);
2661 Invalid = true;
2662 } else if (InconsistentDefaultArg) {
2663 // We could only diagnose about the case that the OldParam is imported.
2664 // The case NewParam is imported should be handled in ASTReader.
2665 Diag(Loc: NewDefaultLoc,
2666 DiagID: diag::err_template_param_default_arg_inconsistent_redefinition);
2667 Diag(Loc: OldDefaultLoc,
2668 DiagID: diag::note_template_param_prev_default_arg_in_other_module)
2669 << PrevModuleName;
2670 Invalid = true;
2671 } else if (MissingDefaultArg &&
2672 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2673 TPC == TPC_FriendClassTemplate)) {
2674 // C++ 23[temp.param]p14:
2675 // If a template-parameter of a class template, variable template, or
2676 // alias template has a default template argument, each subsequent
2677 // template-parameter shall either have a default template argument
2678 // supplied or be a template parameter pack.
2679 Diag(Loc: (*NewParam)->getLocation(),
2680 DiagID: diag::err_template_param_default_arg_missing);
2681 Diag(Loc: PreviousDefaultArgLoc, DiagID: diag::note_template_param_prev_default_arg);
2682 Invalid = true;
2683 RemoveDefaultArguments = true;
2684 }
2685
2686 // If we have an old template parameter list that we're merging
2687 // in, move on to the next parameter.
2688 if (OldParams)
2689 ++OldParam;
2690 }
2691
2692 // We were missing some default arguments at the end of the list, so remove
2693 // all of the default arguments.
2694 if (RemoveDefaultArguments) {
2695 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2696 NewParamEnd = NewParams->end();
2697 NewParam != NewParamEnd; ++NewParam) {
2698 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam))
2699 TTP->removeDefaultArgument();
2700 else if (NonTypeTemplateParmDecl *NTTP
2701 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam))
2702 NTTP->removeDefaultArgument();
2703 else
2704 cast<TemplateTemplateParmDecl>(Val: *NewParam)->removeDefaultArgument();
2705 }
2706 }
2707
2708 return Invalid;
2709}
2710
2711namespace {
2712
2713/// A class which looks for a use of a certain level of template
2714/// parameter.
2715struct DependencyChecker : DynamicRecursiveASTVisitor {
2716 unsigned Depth;
2717
2718 // Whether we're looking for a use of a template parameter that makes the
2719 // overall construct type-dependent / a dependent type. This is strictly
2720 // best-effort for now; we may fail to match at all for a dependent type
2721 // in some cases if this is set.
2722 bool IgnoreNonTypeDependent;
2723
2724 bool Match;
2725 SourceLocation MatchLoc;
2726
2727 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2728 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2729 Match(false) {}
2730
2731 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2732 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2733 NamedDecl *ND = Params->getParam(Idx: 0);
2734 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(Val: ND)) {
2735 Depth = PD->getDepth();
2736 } else if (NonTypeTemplateParmDecl *PD =
2737 dyn_cast<NonTypeTemplateParmDecl>(Val: ND)) {
2738 Depth = PD->getDepth();
2739 } else {
2740 Depth = cast<TemplateTemplateParmDecl>(Val: ND)->getDepth();
2741 }
2742 }
2743
2744 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2745 if (ParmDepth >= Depth) {
2746 Match = true;
2747 MatchLoc = Loc;
2748 return true;
2749 }
2750 return false;
2751 }
2752
2753 bool TraverseStmt(Stmt *S) override {
2754 // Prune out non-type-dependent expressions if requested. This can
2755 // sometimes result in us failing to find a template parameter reference
2756 // (if a value-dependent expression creates a dependent type), but this
2757 // mode is best-effort only.
2758 if (auto *E = dyn_cast_or_null<Expr>(Val: S))
2759 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2760 return true;
2761 return DynamicRecursiveASTVisitor::TraverseStmt(S);
2762 }
2763
2764 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2765 if (IgnoreNonTypeDependent && !TL.isNull() &&
2766 !TL.getType()->isDependentType())
2767 return true;
2768 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2769 }
2770
2771 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2772 return !Matches(ParmDepth: TL.getTypePtr()->getDepth(), Loc: TL.getNameLoc());
2773 }
2774
2775 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2776 // For a best-effort search, keep looking until we find a location.
2777 return IgnoreNonTypeDependent || !Matches(ParmDepth: T->getDepth());
2778 }
2779
2780 bool TraverseTemplateName(TemplateName N) override {
2781 if (TemplateTemplateParmDecl *PD =
2782 dyn_cast_or_null<TemplateTemplateParmDecl>(Val: N.getAsTemplateDecl()))
2783 if (Matches(ParmDepth: PD->getDepth()))
2784 return false;
2785 return DynamicRecursiveASTVisitor::TraverseTemplateName(Template: N);
2786 }
2787
2788 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2789 if (NonTypeTemplateParmDecl *PD =
2790 dyn_cast<NonTypeTemplateParmDecl>(Val: E->getDecl()))
2791 if (Matches(ParmDepth: PD->getDepth(), Loc: E->getExprLoc()))
2792 return false;
2793 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(S: E);
2794 }
2795
2796 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2797 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2798 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2799 if (Matches(ParmDepth: TTP->getDepth(), Loc: ULE->getExprLoc()))
2800 return false;
2801 }
2802 for (auto &TLoc : ULE->template_arguments())
2803 DynamicRecursiveASTVisitor::TraverseTemplateArgumentLoc(ArgLoc: TLoc);
2804 }
2805 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(S: ULE);
2806 }
2807
2808 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2809 return TraverseType(T: T->getReplacementType());
2810 }
2811
2812 bool VisitSubstTemplateTypeParmPackType(
2813 SubstTemplateTypeParmPackType *T) override {
2814 return TraverseTemplateArgument(Arg: T->getArgumentPack());
2815 }
2816
2817 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2818 bool TraverseQualifier) override {
2819 // An InjectedClassNameType will never have a dependent template name,
2820 // so no need to traverse it.
2821 return TraverseTemplateArguments(
2822 Args: T->getTemplateArgs(Ctx: T->getDecl()->getASTContext()));
2823 }
2824};
2825} // end anonymous namespace
2826
2827/// Determines whether a given type depends on the given parameter
2828/// list.
2829static bool
2830DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2831 if (!Params->size())
2832 return false;
2833
2834 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2835 Checker.TraverseType(T);
2836 return Checker.Match;
2837}
2838
2839// Find the source range corresponding to the named type in the given
2840// nested-name-specifier, if any.
2841static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2842 QualType T,
2843 const CXXScopeSpec &SS) {
2844 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2845 for (;;) {
2846 NestedNameSpecifier NNS = NNSLoc.getNestedNameSpecifier();
2847 if (NNS.getKind() != NestedNameSpecifier::Kind::Type)
2848 break;
2849 if (Context.hasSameUnqualifiedType(T1: T, T2: QualType(NNS.getAsType(), 0)))
2850 return NNSLoc.castAsTypeLoc().getSourceRange();
2851 // FIXME: This will always be empty.
2852 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2853 }
2854
2855 return SourceRange();
2856}
2857
2858TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2859 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2860 TemplateIdAnnotation *TemplateId,
2861 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2862 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2863 IsMemberSpecialization = false;
2864 Invalid = false;
2865
2866 // The sequence of nested types to which we will match up the template
2867 // parameter lists. We first build this list by starting with the type named
2868 // by the nested-name-specifier and walking out until we run out of types.
2869 SmallVector<QualType, 4> NestedTypes;
2870 QualType T;
2871 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2872 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2873 if (CXXRecordDecl *Record =
2874 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: true)))
2875 T = Context.getCanonicalTagType(TD: Record);
2876 else
2877 T = QualType(Qualifier.getAsType(), 0);
2878 }
2879
2880 // If we found an explicit specialization that prevents us from needing
2881 // 'template<>' headers, this will be set to the location of that
2882 // explicit specialization.
2883 SourceLocation ExplicitSpecLoc;
2884
2885 while (!T.isNull()) {
2886 NestedTypes.push_back(Elt: T);
2887
2888 // Retrieve the parent of a record type.
2889 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2890 // If this type is an explicit specialization, we're done.
2891 if (ClassTemplateSpecializationDecl *Spec
2892 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
2893 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Spec) &&
2894 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2895 ExplicitSpecLoc = Spec->getLocation();
2896 break;
2897 }
2898 } else if (Record->getTemplateSpecializationKind()
2899 == TSK_ExplicitSpecialization) {
2900 ExplicitSpecLoc = Record->getLocation();
2901 break;
2902 }
2903
2904 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Record->getParent()))
2905 T = Context.getTypeDeclType(Decl: Parent);
2906 else
2907 T = QualType();
2908 continue;
2909 }
2910
2911 if (const TemplateSpecializationType *TST
2912 = T->getAs<TemplateSpecializationType>()) {
2913 TemplateName Name = TST->getTemplateName();
2914 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2915 // Look one step prior in a dependent template specialization type.
2916 if (NestedNameSpecifier NNS = DTS->getQualifier();
2917 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2918 T = QualType(NNS.getAsType(), 0);
2919 else
2920 T = QualType();
2921 continue;
2922 }
2923 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2924 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Template->getDeclContext()))
2925 T = Context.getTypeDeclType(Decl: Parent);
2926 else
2927 T = QualType();
2928 continue;
2929 }
2930 }
2931
2932 // Look one step prior in a dependent name type.
2933 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2934 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2935 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2936 T = QualType(NNS.getAsType(), 0);
2937 else
2938 T = QualType();
2939 continue;
2940 }
2941
2942 // Retrieve the parent of an enumeration type.
2943 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2944 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2945 // check here.
2946 EnumDecl *Enum = EnumT->getDecl();
2947
2948 // Get to the parent type.
2949 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Enum->getParent()))
2950 T = Context.getCanonicalTypeDeclType(TD: Parent);
2951 else
2952 T = QualType();
2953 continue;
2954 }
2955
2956 T = QualType();
2957 }
2958 // Reverse the nested types list, since we want to traverse from the outermost
2959 // to the innermost while checking template-parameter-lists.
2960 std::reverse(first: NestedTypes.begin(), last: NestedTypes.end());
2961
2962 // C++0x [temp.expl.spec]p17:
2963 // A member or a member template may be nested within many
2964 // enclosing class templates. In an explicit specialization for
2965 // such a member, the member declaration shall be preceded by a
2966 // template<> for each enclosing class template that is
2967 // explicitly specialized.
2968 bool SawNonEmptyTemplateParameterList = false;
2969
2970 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2971 if (SawNonEmptyTemplateParameterList) {
2972 if (!SuppressDiagnostic)
2973 Diag(Loc: DeclLoc, DiagID: diag::err_specialize_member_of_template)
2974 << !Recovery << Range;
2975 Invalid = true;
2976 IsMemberSpecialization = false;
2977 return true;
2978 }
2979
2980 return false;
2981 };
2982
2983 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2984 // Check that we can have an explicit specialization here.
2985 if (CheckExplicitSpecialization(Range, true))
2986 return true;
2987
2988 // We don't have a template header, but we should.
2989 SourceLocation ExpectedTemplateLoc;
2990 if (!ParamLists.empty())
2991 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2992 else
2993 ExpectedTemplateLoc = DeclStartLoc;
2994
2995 if (!SuppressDiagnostic)
2996 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_header)
2997 << Range
2998 << FixItHint::CreateInsertion(InsertionLoc: ExpectedTemplateLoc, Code: "template<> ");
2999 return false;
3000 };
3001
3002 unsigned ParamIdx = 0;
3003 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3004 ++TypeIdx) {
3005 T = NestedTypes[TypeIdx];
3006
3007 // Whether we expect a 'template<>' header.
3008 bool NeedEmptyTemplateHeader = false;
3009
3010 // Whether we expect a template header with parameters.
3011 bool NeedNonemptyTemplateHeader = false;
3012
3013 // For a dependent type, the set of template parameters that we
3014 // expect to see.
3015 TemplateParameterList *ExpectedTemplateParams = nullptr;
3016
3017 // C++0x [temp.expl.spec]p15:
3018 // A member or a member template may be nested within many enclosing
3019 // class templates. In an explicit specialization for such a member, the
3020 // member declaration shall be preceded by a template<> for each
3021 // enclosing class template that is explicitly specialized.
3022 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3023 if (ClassTemplatePartialSpecializationDecl *Partial
3024 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Record)) {
3025 ExpectedTemplateParams = Partial->getTemplateParameters();
3026 NeedNonemptyTemplateHeader = true;
3027 } else if (Record->isDependentType()) {
3028 if (Record->getDescribedClassTemplate()) {
3029 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3030 ->getTemplateParameters();
3031 NeedNonemptyTemplateHeader = true;
3032 }
3033 } else if (ClassTemplateSpecializationDecl *Spec
3034 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
3035 // C++0x [temp.expl.spec]p4:
3036 // Members of an explicitly specialized class template are defined
3037 // in the same manner as members of normal classes, and not using
3038 // the template<> syntax.
3039 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3040 NeedEmptyTemplateHeader = true;
3041 else
3042 continue;
3043 } else if (Record->getTemplateSpecializationKind()) {
3044 if (Record->getTemplateSpecializationKind()
3045 != TSK_ExplicitSpecialization &&
3046 TypeIdx == NumTypes - 1)
3047 IsMemberSpecialization = true;
3048
3049 continue;
3050 }
3051 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3052 TemplateName Name = TST->getTemplateName();
3053 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3054 ExpectedTemplateParams = Template->getTemplateParameters();
3055 NeedNonemptyTemplateHeader = true;
3056 } else if (Name.getAsDeducedTemplateName()) {
3057 // FIXME: We actually could/should check the template arguments here
3058 // against the corresponding template parameter list.
3059 NeedNonemptyTemplateHeader = false;
3060 }
3061 }
3062
3063 // C++ [temp.expl.spec]p16:
3064 // In an explicit specialization declaration for a member of a class
3065 // template or a member template that appears in namespace scope, the
3066 // member template and some of its enclosing class templates may remain
3067 // unspecialized, except that the declaration shall not explicitly
3068 // specialize a class member template if its enclosing class templates
3069 // are not explicitly specialized as well.
3070 if (ParamIdx < ParamLists.size()) {
3071 if (ParamLists[ParamIdx]->size() == 0) {
3072 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3073 false))
3074 return nullptr;
3075 } else
3076 SawNonEmptyTemplateParameterList = true;
3077 }
3078
3079 if (NeedEmptyTemplateHeader) {
3080 // If we're on the last of the types, and we need a 'template<>' header
3081 // here, then it's a member specialization.
3082 if (TypeIdx == NumTypes - 1)
3083 IsMemberSpecialization = true;
3084
3085 if (ParamIdx < ParamLists.size()) {
3086 if (ParamLists[ParamIdx]->size() > 0) {
3087 // The header has template parameters when it shouldn't. Complain.
3088 if (!SuppressDiagnostic)
3089 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3090 DiagID: diag::err_template_param_list_matches_nontemplate)
3091 << T
3092 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3093 ParamLists[ParamIdx]->getRAngleLoc())
3094 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3095 Invalid = true;
3096 return nullptr;
3097 }
3098
3099 // Consume this template header.
3100 ++ParamIdx;
3101 continue;
3102 }
3103
3104 if (!IsFriend)
3105 if (DiagnoseMissingExplicitSpecialization(
3106 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3107 return nullptr;
3108
3109 continue;
3110 }
3111
3112 if (NeedNonemptyTemplateHeader) {
3113 // In friend declarations we can have template-ids which don't
3114 // depend on the corresponding template parameter lists. But
3115 // assume that empty parameter lists are supposed to match this
3116 // template-id.
3117 if (IsFriend && T->isDependentType()) {
3118 if (ParamIdx < ParamLists.size() &&
3119 DependsOnTemplateParameters(T, Params: ParamLists[ParamIdx]))
3120 ExpectedTemplateParams = nullptr;
3121 else
3122 continue;
3123 }
3124
3125 if (ParamIdx < ParamLists.size()) {
3126 // Check the template parameter list, if we can.
3127 if (ExpectedTemplateParams &&
3128 !TemplateParameterListsAreEqual(New: ParamLists[ParamIdx],
3129 Old: ExpectedTemplateParams,
3130 Complain: !SuppressDiagnostic, Kind: TPL_TemplateMatch))
3131 Invalid = true;
3132
3133 if (!Invalid &&
3134 CheckTemplateParameterList(NewParams: ParamLists[ParamIdx], OldParams: nullptr,
3135 TPC: TPC_ClassTemplateMember))
3136 Invalid = true;
3137
3138 ++ParamIdx;
3139 continue;
3140 }
3141
3142 if (!SuppressDiagnostic)
3143 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_template_parameters)
3144 << T
3145 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3146 Invalid = true;
3147 continue;
3148 }
3149 }
3150
3151 // If there were at least as many template-ids as there were template
3152 // parameter lists, then there are no template parameter lists remaining for
3153 // the declaration itself.
3154 if (ParamIdx >= ParamLists.size()) {
3155 if (TemplateId && !IsFriend) {
3156 // We don't have a template header for the declaration itself, but we
3157 // should.
3158 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3159 TemplateId->RAngleLoc));
3160
3161 // Fabricate an empty template parameter list for the invented header.
3162 return TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(),
3163 LAngleLoc: SourceLocation(), Params: {},
3164 RAngleLoc: SourceLocation(), RequiresClause: nullptr);
3165 }
3166
3167 return nullptr;
3168 }
3169
3170 // If there were too many template parameter lists, complain about that now.
3171 if (ParamIdx < ParamLists.size() - 1) {
3172 bool HasAnyExplicitSpecHeader = false;
3173 bool AllExplicitSpecHeaders = true;
3174 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3175 if (ParamLists[I]->size() == 0)
3176 HasAnyExplicitSpecHeader = true;
3177 else
3178 AllExplicitSpecHeaders = false;
3179 }
3180
3181 if (!SuppressDiagnostic)
3182 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3183 DiagID: AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3184 : diag::err_template_spec_extra_headers)
3185 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3186 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3187
3188 // If there was a specialization somewhere, such that 'template<>' is
3189 // not required, and there were any 'template<>' headers, note where the
3190 // specialization occurred.
3191 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3192 !SuppressDiagnostic)
3193 Diag(Loc: ExplicitSpecLoc,
3194 DiagID: diag::note_explicit_template_spec_does_not_need_header)
3195 << NestedTypes.back();
3196
3197 // We have a template parameter list with no corresponding scope, which
3198 // means that the resulting template declaration can't be instantiated
3199 // properly (we'll end up with dependent nodes when we shouldn't).
3200 if (!AllExplicitSpecHeaders)
3201 Invalid = true;
3202 }
3203
3204 // C++ [temp.expl.spec]p16:
3205 // In an explicit specialization declaration for a member of a class
3206 // template or a member template that ap- pears in namespace scope, the
3207 // member template and some of its enclosing class templates may remain
3208 // unspecialized, except that the declaration shall not explicitly
3209 // specialize a class member template if its en- closing class templates
3210 // are not explicitly specialized as well.
3211 if (ParamLists.back()->size() == 0 &&
3212 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3213 false))
3214 return nullptr;
3215
3216 // Return the last template parameter list, which corresponds to the
3217 // entity being declared.
3218 return ParamLists.back();
3219}
3220
3221void Sema::NoteAllFoundTemplates(TemplateName Name) {
3222 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3223 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_declared_here)
3224 << (isa<FunctionTemplateDecl>(Val: Template)
3225 ? 0
3226 : isa<ClassTemplateDecl>(Val: Template)
3227 ? 1
3228 : isa<VarTemplateDecl>(Val: Template)
3229 ? 2
3230 : isa<TypeAliasTemplateDecl>(Val: Template) ? 3 : 4)
3231 << Template->getDeclName();
3232 return;
3233 }
3234
3235 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3236 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3237 IEnd = OST->end();
3238 I != IEnd; ++I)
3239 Diag(Loc: (*I)->getLocation(), DiagID: diag::note_template_declared_here)
3240 << 0 << (*I)->getDeclName();
3241
3242 return;
3243 }
3244}
3245
3246static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword,
3247 TemplateName BaseTemplate,
3248 SourceLocation TemplateLoc,
3249 ArrayRef<TemplateArgument> Ts) {
3250 auto lookUpCommonType = [&](TemplateArgument T1,
3251 TemplateArgument T2) -> QualType {
3252 // Don't bother looking for other specializations if both types are
3253 // builtins - users aren't allowed to specialize for them
3254 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3255 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3256 Ts: {T1, T2});
3257
3258 TemplateArgumentListInfo Args;
3259 Args.addArgument(Loc: TemplateArgumentLoc(
3260 T1, S.Context.getTrivialTypeSourceInfo(T: T1.getAsType())));
3261 Args.addArgument(Loc: TemplateArgumentLoc(
3262 T2, S.Context.getTrivialTypeSourceInfo(T: T2.getAsType())));
3263
3264 EnterExpressionEvaluationContext UnevaluatedContext(
3265 S, Sema::ExpressionEvaluationContext::Unevaluated);
3266 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3267 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3268
3269 QualType BaseTemplateInst = S.CheckTemplateIdType(
3270 Keyword, Template: BaseTemplate, TemplateLoc, TemplateArgs&: Args,
3271 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3272
3273 if (SFINAE.hasErrorOccurred())
3274 return QualType();
3275
3276 return BaseTemplateInst;
3277 };
3278
3279 // Note A: For the common_type trait applied to a template parameter pack T of
3280 // types, the member type shall be either defined or not present as follows:
3281 switch (Ts.size()) {
3282
3283 // If sizeof...(T) is zero, there shall be no member type.
3284 case 0:
3285 return QualType();
3286
3287 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3288 // pack T. The member typedef-name type shall denote the same type, if any, as
3289 // common_type_t<T0, T0>; otherwise there shall be no member type.
3290 case 1:
3291 return lookUpCommonType(Ts[0], Ts[0]);
3292
3293 // If sizeof...(T) is two, let the first and second types constituting T be
3294 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3295 // as decay_t<T1> and decay_t<T2>, respectively.
3296 case 2: {
3297 QualType T1 = Ts[0].getAsType();
3298 QualType T2 = Ts[1].getAsType();
3299 QualType D1 = S.BuiltinDecay(BaseType: T1, Loc: {});
3300 QualType D2 = S.BuiltinDecay(BaseType: T2, Loc: {});
3301
3302 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3303 // the same type, if any, as common_type_t<D1, D2>.
3304 if (!S.Context.hasSameType(T1, T2: D1) || !S.Context.hasSameType(T1: T2, T2: D2))
3305 return lookUpCommonType(D1, D2);
3306
3307 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3308 // denotes a valid type, let C denote that type.
3309 {
3310 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3311 EnterExpressionEvaluationContext UnevaluatedContext(
3312 S, Sema::ExpressionEvaluationContext::Unevaluated);
3313 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3314 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3315
3316 // false
3317 OpaqueValueExpr CondExpr(SourceLocation(), S.Context.BoolTy,
3318 VK_PRValue);
3319 ExprResult Cond = &CondExpr;
3320
3321 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3322 if (ConstRefQual) {
3323 D1.addConst();
3324 D2.addConst();
3325 }
3326
3327 // declval<D1>()
3328 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3329 ExprResult LHS = &LHSExpr;
3330
3331 // declval<D2>()
3332 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3333 ExprResult RHS = &RHSExpr;
3334
3335 ExprValueKind VK = VK_PRValue;
3336 ExprObjectKind OK = OK_Ordinary;
3337
3338 // decltype(false ? declval<D1>() : declval<D2>())
3339 QualType Result =
3340 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc: TemplateLoc);
3341
3342 if (Result.isNull() || SFINAE.hasErrorOccurred())
3343 return QualType();
3344
3345 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3346 return S.BuiltinDecay(BaseType: Result, Loc: TemplateLoc);
3347 };
3348
3349 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3350 return Res;
3351
3352 // Let:
3353 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3354 // COND-RES(X, Y) be
3355 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3356
3357 // C++20 only
3358 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3359 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3360 if (!S.Context.getLangOpts().CPlusPlus20)
3361 return QualType();
3362 return CheckConditionalOperands(true);
3363 }
3364 }
3365
3366 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3367 // denote the first, second, and (pack of) remaining types constituting T. Let
3368 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3369 // a type C, the member typedef-name type shall denote the same type, if any,
3370 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3371 default: {
3372 QualType Result = Ts.front().getAsType();
3373 for (auto T : llvm::drop_begin(RangeOrContainer&: Ts)) {
3374 Result = lookUpCommonType(Result, T.getAsType());
3375 if (Result.isNull())
3376 return QualType();
3377 }
3378 return Result;
3379 }
3380 }
3381}
3382
3383static bool isInVkNamespace(const RecordType *RT) {
3384 DeclContext *DC = RT->getDecl()->getDeclContext();
3385 if (!DC)
3386 return false;
3387
3388 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: DC);
3389 if (!ND)
3390 return false;
3391
3392 return ND->getQualifiedNameAsString() == "hlsl::vk";
3393}
3394
3395static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3396 QualType OperandArg,
3397 SourceLocation Loc) {
3398 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3399 bool Literal = false;
3400 SourceLocation LiteralLoc;
3401 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3402 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3403 assert(SpecDecl);
3404
3405 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3406 QualType ConstantType = LiteralArgs[0].getAsType();
3407 RT = ConstantType->getAsCanonical<RecordType>();
3408 Literal = true;
3409 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3410 }
3411
3412 if (RT && isInVkNamespace(RT) &&
3413 RT->getDecl()->getName() == "integral_constant") {
3414 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3415 assert(SpecDecl);
3416
3417 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3418
3419 QualType ConstantType = ConstantArgs[0].getAsType();
3420 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3421
3422 if (Literal)
3423 return SpirvOperand::createLiteral(Val: Value);
3424 return SpirvOperand::createConstant(ResultType: ConstantType, Val: Value);
3425 } else if (Literal) {
3426 SemaRef.Diag(Loc: LiteralLoc, DiagID: diag::err_hlsl_vk_literal_must_contain_constant);
3427 return SpirvOperand();
3428 }
3429 }
3430 if (SemaRef.RequireCompleteType(Loc, T: OperandArg,
3431 DiagID: diag::err_call_incomplete_argument))
3432 return SpirvOperand();
3433 return SpirvOperand::createType(T: OperandArg);
3434}
3435
3436static QualType checkBuiltinTemplateIdType(
3437 Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD,
3438 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3439 TemplateArgumentListInfo &TemplateArgs) {
3440 ASTContext &Context = SemaRef.getASTContext();
3441
3442 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3443 "Builtin template arguments do not match its parameters");
3444
3445 switch (BTD->getBuiltinTemplateKind()) {
3446 case BTK__make_integer_seq: {
3447 // Specializations of __make_integer_seq<S, T, N> are treated like
3448 // S<T, 0, ..., N-1>.
3449
3450 QualType OrigType = Converted[1].getAsType();
3451 // C++14 [inteseq.intseq]p1:
3452 // T shall be an integer type.
3453 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Ctx: Context)) {
3454 SemaRef.Diag(Loc: TemplateArgs[1].getLocation(),
3455 DiagID: diag::err_integer_sequence_integral_element_type);
3456 return QualType();
3457 }
3458
3459 TemplateArgument NumArgsArg = Converted[2];
3460 if (NumArgsArg.isDependent())
3461 return QualType();
3462
3463 TemplateArgumentListInfo SyntheticTemplateArgs;
3464 // The type argument, wrapped in substitution sugar, gets reused as the
3465 // first template argument in the synthetic template argument list.
3466 SyntheticTemplateArgs.addArgument(
3467 Loc: TemplateArgumentLoc(TemplateArgument(OrigType),
3468 SemaRef.Context.getTrivialTypeSourceInfo(
3469 T: OrigType, Loc: TemplateArgs[1].getLocation())));
3470
3471 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3472 // Expand N into 0 ... N-1.
3473 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3474 I < NumArgs; ++I) {
3475 TemplateArgument TA(Context, I, OrigType);
3476 SyntheticTemplateArgs.addArgument(Loc: SemaRef.getTrivialTemplateArgumentLoc(
3477 Arg: TA, NTTPType: OrigType, Loc: TemplateArgs[2].getLocation()));
3478 }
3479 } else {
3480 // C++14 [inteseq.make]p1:
3481 // If N is negative the program is ill-formed.
3482 SemaRef.Diag(Loc: TemplateArgs[2].getLocation(),
3483 DiagID: diag::err_integer_sequence_negative_length);
3484 return QualType();
3485 }
3486
3487 // The first template argument will be reused as the template decl that
3488 // our synthetic template arguments will be applied to.
3489 return SemaRef.CheckTemplateIdType(Keyword, Template: Converted[0].getAsTemplate(),
3490 TemplateLoc, TemplateArgs&: SyntheticTemplateArgs,
3491 /*Scope=*/nullptr,
3492 /*ForNestedNameSpecifier=*/false);
3493 }
3494
3495 case BTK__type_pack_element: {
3496 // Specializations of
3497 // __type_pack_element<Index, T_1, ..., T_N>
3498 // are treated like T_Index.
3499 assert(Converted.size() == 2 &&
3500 "__type_pack_element should be given an index and a parameter pack");
3501
3502 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3503 if (IndexArg.isDependent() || Ts.isDependent())
3504 return QualType();
3505
3506 llvm::APSInt Index = IndexArg.getAsIntegral();
3507 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3508 "type std::size_t, and hence be non-negative");
3509 // If the Index is out of bounds, the program is ill-formed.
3510 if (Index >= Ts.pack_size()) {
3511 SemaRef.Diag(Loc: TemplateArgs[0].getLocation(),
3512 DiagID: diag::err_type_pack_element_out_of_bounds);
3513 return QualType();
3514 }
3515
3516 // We simply return the type at index `Index`.
3517 int64_t N = Index.getExtValue();
3518 return Ts.getPackAsArray()[N].getAsType();
3519 }
3520
3521 case BTK__builtin_common_type: {
3522 assert(Converted.size() == 4);
3523 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3524 return QualType();
3525
3526 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3527 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3528 if (auto CT = builtinCommonTypeImpl(S&: SemaRef, Keyword, BaseTemplate,
3529 TemplateLoc, Ts);
3530 !CT.isNull()) {
3531 TemplateArgumentListInfo TAs;
3532 TAs.addArgument(Loc: TemplateArgumentLoc(
3533 TemplateArgument(CT), SemaRef.Context.getTrivialTypeSourceInfo(
3534 T: CT, Loc: TemplateArgs[1].getLocation())));
3535 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3536 return SemaRef.CheckTemplateIdType(Keyword, Template: HasTypeMember, TemplateLoc,
3537 TemplateArgs&: TAs, /*Scope=*/nullptr,
3538 /*ForNestedNameSpecifier=*/false);
3539 }
3540 QualType HasNoTypeMember = Converted[2].getAsType();
3541 return HasNoTypeMember;
3542 }
3543
3544 case BTK__hlsl_spirv_type: {
3545 assert(Converted.size() == 4);
3546
3547 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3548 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_hlsl_spirv_only) << BTD;
3549 }
3550
3551 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3552 return QualType();
3553
3554 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3555 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3556 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3557
3558 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3559
3560 llvm::SmallVector<SpirvOperand> Operands;
3561
3562 for (auto &OperandTA : OperandArgs) {
3563 QualType OperandArg = OperandTA.getAsType();
3564 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3565 Loc: TemplateArgs[3].getLocation());
3566 if (!Operand.isValid())
3567 return QualType();
3568 Operands.push_back(Elt: Operand);
3569 }
3570
3571 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3572 }
3573 case BTK__builtin_dedup_pack: {
3574 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3575 "a parameter pack");
3576 TemplateArgument Ts = Converted[0];
3577 // Delay the computation until we can compute the final result. We choose
3578 // not to remove the duplicates upfront before substitution to keep the code
3579 // simple.
3580 if (Ts.isDependent())
3581 return QualType();
3582 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3583 llvm::SmallVector<TemplateArgument> OutArgs;
3584 llvm::SmallDenseSet<QualType> Seen;
3585 // Synthesize a new template argument list, removing duplicates.
3586 for (auto T : Ts.getPackAsArray()) {
3587 assert(T.getKind() == clang::TemplateArgument::Type);
3588 if (!Seen.insert(V: T.getAsType().getCanonicalType()).second)
3589 continue;
3590 OutArgs.push_back(Elt: T);
3591 }
3592 return Context.getSubstBuiltinTemplatePack(
3593 ArgPack: TemplateArgument::CreatePackCopy(Context, Args: OutArgs));
3594 }
3595 }
3596 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3597}
3598
3599/// Determine whether this alias template is "enable_if_t".
3600/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3601static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3602 return AliasTemplate->getName() == "enable_if_t" ||
3603 AliasTemplate->getName() == "__enable_if_t";
3604}
3605
3606/// Collect all of the separable terms in the given condition, which
3607/// might be a conjunction.
3608///
3609/// FIXME: The right answer is to convert the logical expression into
3610/// disjunctive normal form, so we can find the first failed term
3611/// within each possible clause.
3612static void collectConjunctionTerms(Expr *Clause,
3613 SmallVectorImpl<Expr *> &Terms) {
3614 if (auto BinOp = dyn_cast<BinaryOperator>(Val: Clause->IgnoreParenImpCasts())) {
3615 if (BinOp->getOpcode() == BO_LAnd) {
3616 collectConjunctionTerms(Clause: BinOp->getLHS(), Terms);
3617 collectConjunctionTerms(Clause: BinOp->getRHS(), Terms);
3618 return;
3619 }
3620 }
3621
3622 Terms.push_back(Elt: Clause);
3623}
3624
3625// The ranges-v3 library uses an odd pattern of a top-level "||" with
3626// a left-hand side that is value-dependent but never true. Identify
3627// the idiom and ignore that term.
3628static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3629 // Top-level '||'.
3630 auto *BinOp = dyn_cast<BinaryOperator>(Val: Cond->IgnoreParenImpCasts());
3631 if (!BinOp) return Cond;
3632
3633 if (BinOp->getOpcode() != BO_LOr) return Cond;
3634
3635 // With an inner '==' that has a literal on the right-hand side.
3636 Expr *LHS = BinOp->getLHS();
3637 auto *InnerBinOp = dyn_cast<BinaryOperator>(Val: LHS->IgnoreParenImpCasts());
3638 if (!InnerBinOp) return Cond;
3639
3640 if (InnerBinOp->getOpcode() != BO_EQ ||
3641 !isa<IntegerLiteral>(Val: InnerBinOp->getRHS()))
3642 return Cond;
3643
3644 // If the inner binary operation came from a macro expansion named
3645 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3646 // of the '||', which is the real, user-provided condition.
3647 SourceLocation Loc = InnerBinOp->getExprLoc();
3648 if (!Loc.isMacroID()) return Cond;
3649
3650 StringRef MacroName = PP.getImmediateMacroName(Loc);
3651 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3652 return BinOp->getRHS();
3653
3654 return Cond;
3655}
3656
3657namespace {
3658
3659// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3660// within failing boolean expression, such as substituting template parameters
3661// for actual types.
3662class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3663public:
3664 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3665 : Policy(P) {}
3666
3667 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3668 const auto *DR = dyn_cast<DeclRefExpr>(Val: E);
3669 if (DR && DR->getQualifier()) {
3670 // If this is a qualified name, expand the template arguments in nested
3671 // qualifiers.
3672 DR->getQualifier().print(OS, Policy, ResolveTemplateArguments: true);
3673 // Then print the decl itself.
3674 const ValueDecl *VD = DR->getDecl();
3675 OS << *VD;
3676 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) {
3677 // This is a template variable, print the expanded template arguments.
3678 printTemplateArgumentList(
3679 OS, Args: IV->getTemplateArgs().asArray(), Policy,
3680 TPL: IV->getSpecializedTemplate()->getTemplateParameters());
3681 }
3682 return true;
3683 }
3684 return false;
3685 }
3686
3687private:
3688 const PrintingPolicy Policy;
3689};
3690
3691} // end anonymous namespace
3692
3693std::pair<Expr *, std::string>
3694Sema::findFailedBooleanCondition(Expr *Cond) {
3695 Cond = lookThroughRangesV3Condition(PP, Cond);
3696
3697 // Separate out all of the terms in a conjunction.
3698 SmallVector<Expr *, 4> Terms;
3699 collectConjunctionTerms(Clause: Cond, Terms);
3700
3701 // Determine which term failed.
3702 Expr *FailedCond = nullptr;
3703 for (Expr *Term : Terms) {
3704 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3705
3706 // Literals are uninteresting.
3707 if (isa<CXXBoolLiteralExpr>(Val: TermAsWritten) ||
3708 isa<IntegerLiteral>(Val: TermAsWritten))
3709 continue;
3710
3711 // The initialization of the parameter from the argument is
3712 // a constant-evaluated context.
3713 EnterExpressionEvaluationContext ConstantEvaluated(
3714 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3715
3716 bool Succeeded;
3717 if (Term->EvaluateAsBooleanCondition(Result&: Succeeded, Ctx: Context) &&
3718 !Succeeded) {
3719 FailedCond = TermAsWritten;
3720 break;
3721 }
3722 }
3723 if (!FailedCond)
3724 FailedCond = Cond->IgnoreParenImpCasts();
3725
3726 std::string Description;
3727 {
3728 llvm::raw_string_ostream Out(Description);
3729 PrintingPolicy Policy = getPrintingPolicy();
3730 Policy.PrintAsCanonical = true;
3731 FailedBooleanConditionPrinterHelper Helper(Policy);
3732 FailedCond->printPretty(OS&: Out, Helper: &Helper, Policy, Indentation: 0, NewlineSymbol: "\n", Context: nullptr);
3733 }
3734 return { FailedCond, Description };
3735}
3736
3737static TemplateName
3738resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope,
3739 const AssumedTemplateStorage *ATN,
3740 SourceLocation NameLoc) {
3741 // We assumed this undeclared identifier to be an (ADL-only) function
3742 // template name, but it was used in a context where a type was required.
3743 // Try to typo-correct it now.
3744 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3745 struct CandidateCallback : CorrectionCandidateCallback {
3746 bool ValidateCandidate(const TypoCorrection &TC) override {
3747 return TC.getCorrectionDecl() &&
3748 getAsTypeTemplateDecl(D: TC.getCorrectionDecl());
3749 }
3750 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3751 return std::make_unique<CandidateCallback>(args&: *this);
3752 }
3753 } FilterCCC;
3754
3755 TypoCorrection Corrected =
3756 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Scope,
3757 /*SS=*/nullptr, CCC&: FilterCCC, Mode: CorrectTypoKind::ErrorRecovery);
3758 if (Corrected && Corrected.getFoundDecl()) {
3759 S.diagnoseTypo(Correction: Corrected, TypoDiag: S.PDiag(DiagID: diag::err_no_template_suggest)
3760 << ATN->getDeclName());
3761 return S.Context.getQualifiedTemplateName(
3762 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3763 Template: TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()));
3764 }
3765
3766 return TemplateName();
3767}
3768
3769QualType Sema::CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
3770 TemplateName Name,
3771 SourceLocation TemplateLoc,
3772 TemplateArgumentListInfo &TemplateArgs,
3773 Scope *Scope, bool ForNestedNameSpecifier) {
3774 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3775
3776 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3777 if (!Template) {
3778 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3779 Template = S->getParameterPack();
3780 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3781 if (DTN->getName().getIdentifier())
3782 // When building a template-id where the template-name is dependent,
3783 // assume the template is a type template. Either our assumption is
3784 // correct, or the code is ill-formed and will be diagnosed when the
3785 // dependent name is substituted.
3786 return Context.getTemplateSpecializationType(Keyword, T: Name,
3787 SpecifiedArgs: TemplateArgs.arguments(),
3788 /*CanonicalArgs=*/{});
3789 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3790 if (TemplateName CorrectedName = ::resolveAssumedTemplateNameAsType(
3791 S&: *this, Scope, ATN, NameLoc: TemplateLoc);
3792 CorrectedName.isNull()) {
3793 Diag(Loc: TemplateLoc, DiagID: diag::err_no_template) << ATN->getDeclName();
3794 return QualType();
3795 } else {
3796 Name = CorrectedName;
3797 Template = Name.getAsTemplateDecl();
3798 }
3799 }
3800 }
3801 if (!Template ||
3802 isa<FunctionTemplateDecl, VarTemplateDecl, ConceptDecl>(Val: Template)) {
3803 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3804 if (ForNestedNameSpecifier)
3805 Diag(Loc: TemplateLoc, DiagID: diag::err_non_type_template_in_nested_name_specifier)
3806 << isa_and_nonnull<VarTemplateDecl>(Val: Template) << Name << R;
3807 else
3808 Diag(Loc: TemplateLoc, DiagID: diag::err_template_id_not_a_type) << Name << R;
3809 NoteAllFoundTemplates(Name);
3810 return QualType();
3811 }
3812
3813 // Check that the template argument list is well-formed for this
3814 // template.
3815 CheckTemplateArgumentInfo CTAI;
3816 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3817 DefaultArgs, /*PartialTemplateArgs=*/false,
3818 CTAI,
3819 /*UpdateArgsWithConversions=*/true))
3820 return QualType();
3821
3822 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3823 // and there are no diagnsotics currently implemented for TemplateDecls,
3824 // so avoid doing it for now.
3825 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Template, /*OdrUse=*/MightBeOdrUse: false);
3826
3827 QualType CanonType;
3828
3829 if (isa<TemplateTemplateParmDecl>(Val: Template)) {
3830 // We might have a substituted template template parameter pack. If so,
3831 // build a template specialization type for it.
3832 } else if (TypeAliasTemplateDecl *AliasTemplate =
3833 dyn_cast<TypeAliasTemplateDecl>(Val: Template)) {
3834
3835 // C++0x [dcl.type.elab]p2:
3836 // If the identifier resolves to a typedef-name or the simple-template-id
3837 // resolves to an alias template specialization, the
3838 // elaborated-type-specifier is ill-formed.
3839 if (Keyword != ElaboratedTypeKeyword::None &&
3840 Keyword != ElaboratedTypeKeyword::Typename) {
3841 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_tag_reference_non_tag)
3842 << AliasTemplate << NonTagKind::TypeAliasTemplate
3843 << KeywordHelpers::getTagTypeKindForKeyword(Keyword);
3844 SemaRef.Diag(Loc: AliasTemplate->getLocation(), DiagID: diag::note_declared_at);
3845 }
3846
3847 // Find the canonical type for this type alias template specialization.
3848 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3849
3850 // Diagnose uses of the pattern of this template.
3851 (void)DiagnoseUseOfDecl(D: Pattern, Locs: TemplateLoc);
3852 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Pattern, /*OdrUse=*/MightBeOdrUse: false);
3853
3854 if (Pattern->isInvalidDecl())
3855 return QualType();
3856
3857 // Only substitute for the innermost template argument list.
3858 MultiLevelTemplateArgumentList TemplateArgLists;
3859 TemplateArgLists.addOuterTemplateArguments(AssociatedDecl: Template, Args: CTAI.SugaredConverted,
3860 /*Final=*/true);
3861 TemplateArgLists.addOuterRetainedLevels(
3862 Num: AliasTemplate->getTemplateParameters()->getDepth());
3863
3864 LocalInstantiationScope Scope(*this);
3865
3866 // FIXME: The TemplateArgs passed here are not used for the context note,
3867 // nor they should, because this note will be pointing to the specialization
3868 // anyway. These arguments are needed for a hack for instantiating lambdas
3869 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3870 // arguments will be used for collating the template arguments needed to
3871 // instantiate the lambda.
3872 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3873 /*Entity=*/AliasTemplate,
3874 /*TemplateArgs=*/CTAI.SugaredConverted);
3875 if (Inst.isInvalid())
3876 return QualType();
3877
3878 std::optional<ContextRAII> SavedContext;
3879 if (!AliasTemplate->getDeclContext()->isFileContext())
3880 SavedContext.emplace(args&: *this, args: AliasTemplate->getDeclContext());
3881
3882 CanonType =
3883 SubstType(T: Pattern->getUnderlyingType(), TemplateArgs: TemplateArgLists,
3884 Loc: AliasTemplate->getLocation(), Entity: AliasTemplate->getDeclName());
3885 if (CanonType.isNull()) {
3886 // If this was enable_if and we failed to find the nested type
3887 // within enable_if in a SFINAE context, dig out the specific
3888 // enable_if condition that failed and present that instead.
3889 if (isEnableIfAliasTemplate(AliasTemplate)) {
3890 if (SFINAETrap *Trap = getSFINAEContext();
3891 TemplateDeductionInfo *DeductionInfo =
3892 Trap ? Trap->getDeductionInfo() : nullptr) {
3893 if (DeductionInfo->hasSFINAEDiagnostic() &&
3894 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3895 diag::err_typename_nested_not_found_enable_if &&
3896 TemplateArgs[0].getArgument().getKind() ==
3897 TemplateArgument::Expression) {
3898 Expr *FailedCond;
3899 std::string FailedDescription;
3900 std::tie(args&: FailedCond, args&: FailedDescription) =
3901 findFailedBooleanCondition(Cond: TemplateArgs[0].getSourceExpression());
3902
3903 // Remove the old SFINAE diagnostic.
3904 PartialDiagnosticAt OldDiag =
3905 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3906 DeductionInfo->takeSFINAEDiagnostic(PD&: OldDiag);
3907
3908 // Add a new SFINAE diagnostic specifying which condition
3909 // failed.
3910 DeductionInfo->addSFINAEDiagnostic(
3911 Loc: OldDiag.first,
3912 PD: PDiag(DiagID: diag::err_typename_nested_not_found_requirement)
3913 << FailedDescription << FailedCond->getSourceRange());
3914 }
3915 }
3916 }
3917
3918 return QualType();
3919 }
3920 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Val: Template)) {
3921 CanonType = checkBuiltinTemplateIdType(
3922 SemaRef&: *this, Keyword, BTD, Converted: CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3923 } else if (Name.isDependent() ||
3924 TemplateSpecializationType::anyDependentTemplateArguments(
3925 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
3926 // This class template specialization is a dependent
3927 // type. Therefore, its canonical type is another class template
3928 // specialization type that contains all of the converted
3929 // arguments in canonical form. This ensures that, e.g., A<T> and
3930 // A<T, T> have identical types when A is declared as:
3931 //
3932 // template<typename T, typename U = T> struct A;
3933 CanonType = Context.getCanonicalTemplateSpecializationType(
3934 Keyword: ElaboratedTypeKeyword::None,
3935 T: Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3936 CanonicalArgs: CTAI.CanonicalConverted);
3937 assert(CanonType->isCanonicalUnqualified());
3938
3939 // This might work out to be a current instantiation, in which
3940 // case the canonical type needs to be the InjectedClassNameType.
3941 //
3942 // TODO: in theory this could be a simple hashtable lookup; most
3943 // changes to CurContext don't change the set of current
3944 // instantiations.
3945 if (isa<ClassTemplateDecl>(Val: Template)) {
3946 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3947 // If we get out to a namespace, we're done.
3948 if (Ctx->isFileContext()) break;
3949
3950 // If this isn't a record, keep looking.
3951 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Ctx);
3952 if (!Record) continue;
3953
3954 // Look for one of the two cases with InjectedClassNameTypes
3955 // and check whether it's the same template.
3956 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Record) &&
3957 !Record->getDescribedClassTemplate())
3958 continue;
3959
3960 // Fetch the injected class name type and check whether its
3961 // injected type is equal to the type we just built.
3962 CanQualType ICNT = Context.getCanonicalTagType(TD: Record);
3963 CanQualType Injected =
3964 Record->getCanonicalTemplateSpecializationType(Ctx: Context);
3965
3966 if (CanonType != Injected)
3967 continue;
3968
3969 (void)DiagnoseUseOfDecl(D: Record, Locs: TemplateLoc);
3970 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Record, /*OdrUse=*/MightBeOdrUse: false);
3971
3972 // If so, the canonical type of this TST is the injected
3973 // class name type of the record we just found.
3974 CanonType = ICNT;
3975 break;
3976 }
3977 }
3978 } else if (ClassTemplateDecl *ClassTemplate =
3979 dyn_cast<ClassTemplateDecl>(Val: Template)) {
3980 // Find the class template specialization declaration that
3981 // corresponds to these arguments.
3982 void *InsertPos = nullptr;
3983 ClassTemplateSpecializationDecl *Decl =
3984 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
3985 if (!Decl) {
3986 // This is the first time we have referenced this class template
3987 // specialization. Create the canonical declaration and add it to
3988 // the set of specializations.
3989 Decl = ClassTemplateSpecializationDecl::Create(
3990 Context, TK: ClassTemplate->getTemplatedDecl()->getTagKind(),
3991 DC: ClassTemplate->getDeclContext(),
3992 StartLoc: ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3993 IdLoc: ClassTemplate->getLocation(), SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted,
3994 StrictPackMatch: CTAI.StrictPackMatch, PrevDecl: nullptr);
3995 ClassTemplate->AddSpecialization(D: Decl, InsertPos);
3996 if (ClassTemplate->isOutOfLine())
3997 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3998 }
3999
4000 if (Decl->getSpecializationKind() == TSK_Undeclared &&
4001 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4002 NonSFINAEContext _(*this);
4003 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4004 if (!Inst.isInvalid()) {
4005 MultiLevelTemplateArgumentList TemplateArgLists(Template,
4006 CTAI.CanonicalConverted,
4007 /*Final=*/false);
4008 InstantiateAttrsForDecl(TemplateArgs: TemplateArgLists,
4009 Pattern: ClassTemplate->getTemplatedDecl(), Inst: Decl);
4010 }
4011 }
4012
4013 // Diagnose uses of this specialization.
4014 (void)DiagnoseUseOfDecl(D: Decl, Locs: TemplateLoc);
4015 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Decl, /*OdrUse=*/MightBeOdrUse: false);
4016
4017 CanonType = Context.getCanonicalTagType(TD: Decl);
4018 assert(isa<RecordType>(CanonType) &&
4019 "type of non-dependent specialization is not a RecordType");
4020 } else {
4021 llvm_unreachable("Unhandled template kind");
4022 }
4023
4024 // Build the fully-sugared type for this class template
4025 // specialization, which refers back to the class template
4026 // specialization we created or found.
4027 return Context.getTemplateSpecializationType(
4028 Keyword, T: Name, SpecifiedArgs: TemplateArgs.arguments(), CanonicalArgs: CTAI.CanonicalConverted,
4029 Canon: CanonType);
4030}
4031
4032void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
4033 TemplateNameKind &TNK,
4034 SourceLocation NameLoc,
4035 IdentifierInfo *&II) {
4036 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4037
4038 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4039 assert(ATN && "not an assumed template name");
4040 II = ATN->getDeclName().getAsIdentifierInfo();
4041
4042 if (TemplateName Name =
4043 ::resolveAssumedTemplateNameAsType(S&: *this, Scope: S, ATN, NameLoc);
4044 !Name.isNull()) {
4045 // Resolved to a type template name.
4046 ParsedName = TemplateTy::make(P: Name);
4047 TNK = TNK_Type_template;
4048 }
4049}
4050
4051TypeResult Sema::ActOnTemplateIdType(
4052 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4053 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4054 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4055 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4056 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4057 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4058 ImplicitTypenameContext AllowImplicitTypename) {
4059 if (SS.isInvalid())
4060 return true;
4061
4062 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4063 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4064
4065 // C++ [temp.res]p3:
4066 // A qualified-id that refers to a type and in which the
4067 // nested-name-specifier depends on a template-parameter (14.6.2)
4068 // shall be prefixed by the keyword typename to indicate that the
4069 // qualified-id denotes a type, forming an
4070 // elaborated-type-specifier (7.1.5.3).
4071 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4072 // C++2a relaxes some of those restrictions in [temp.res]p5.
4073 QualType DNT = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
4074 NNS: SS.getScopeRep(), Name: TemplateII);
4075 NestedNameSpecifier NNS(DNT.getTypePtr());
4076 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4077 auto DB = DiagCompat(Loc: SS.getBeginLoc(), CompatDiagId: diag_compat::implicit_typename)
4078 << NNS;
4079 if (!getLangOpts().CPlusPlus20)
4080 DB << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "typename ");
4081 } else
4082 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_typename_missing_template) << NNS;
4083
4084 // FIXME: This is not quite correct recovery as we don't transform SS
4085 // into the corresponding dependent form (and we don't diagnose missing
4086 // 'template' keywords within SS as a result).
4087 return ActOnTypenameType(S: nullptr, TypenameLoc: SourceLocation(), SS, TemplateLoc: TemplateKWLoc,
4088 TemplateName: TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4089 TemplateArgs: TemplateArgsIn, RAngleLoc);
4090 }
4091
4092 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4093 // it's not actually allowed to be used as a type in most cases. Because
4094 // we annotate it before we know whether it's valid, we have to check for
4095 // this case here.
4096 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
4097 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4098 Diag(Loc: TemplateIILoc,
4099 DiagID: TemplateKWLoc.isInvalid()
4100 ? diag::err_out_of_line_qualified_id_type_names_constructor
4101 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4102 << TemplateII << 0 /*injected-class-name used as template name*/
4103 << 1 /*if any keyword was present, it was 'template'*/;
4104 }
4105 }
4106
4107 // Translate the parser's template argument list in our AST format.
4108 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4109 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4110
4111 QualType SpecTy = CheckTemplateIdType(
4112 Keyword: ElaboratedKeyword, Name: TemplateD.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
4113 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4114 if (SpecTy.isNull())
4115 return true;
4116
4117 // Build type-source information.
4118 TypeLocBuilder TLB;
4119 TLB.push<TemplateSpecializationTypeLoc>(T: SpecTy).set(
4120 ElaboratedKeywordLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
4121 NameLoc: TemplateIILoc, TAL: TemplateArgs);
4122 return CreateParsedType(T: SpecTy, TInfo: TLB.getTypeSourceInfo(Context, T: SpecTy));
4123}
4124
4125TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4126 TypeSpecifierType TagSpec,
4127 SourceLocation TagLoc,
4128 CXXScopeSpec &SS,
4129 SourceLocation TemplateKWLoc,
4130 TemplateTy TemplateD,
4131 SourceLocation TemplateLoc,
4132 SourceLocation LAngleLoc,
4133 ASTTemplateArgsPtr TemplateArgsIn,
4134 SourceLocation RAngleLoc) {
4135 if (SS.isInvalid())
4136 return TypeResult(true);
4137
4138 // Translate the parser's template argument list in our AST format.
4139 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4140 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4141
4142 // Determine the tag kind
4143 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
4144 ElaboratedTypeKeyword Keyword
4145 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
4146
4147 QualType Result =
4148 CheckTemplateIdType(Keyword, Name: TemplateD.get(), TemplateLoc, TemplateArgs,
4149 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4150 if (Result.isNull())
4151 return TypeResult(true);
4152
4153 // Check the tag kind
4154 if (const RecordType *RT = Result->getAs<RecordType>()) {
4155 RecordDecl *D = RT->getDecl();
4156
4157 IdentifierInfo *Id = D->getIdentifier();
4158 assert(Id && "templated class must have an identifier");
4159
4160 if (!isAcceptableTagRedeclaration(Previous: D, NewTag: TagKind, isDefinition: TUK == TagUseKind::Definition,
4161 NewTagLoc: TagLoc, Name: Id)) {
4162 Diag(Loc: TagLoc, DiagID: diag::err_use_with_wrong_tag)
4163 << Result
4164 << FixItHint::CreateReplacement(RemoveRange: SourceRange(TagLoc), Code: D->getKindName());
4165 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_use);
4166 }
4167 }
4168
4169 // Provide source-location information for the template specialization.
4170 TypeLocBuilder TLB;
4171 TLB.push<TemplateSpecializationTypeLoc>(T: Result).set(
4172 ElaboratedKeywordLoc: TagLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc, NameLoc: TemplateLoc,
4173 TAL: TemplateArgs);
4174 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
4175}
4176
4177static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4178 NamedDecl *PrevDecl,
4179 SourceLocation Loc,
4180 bool IsPartialSpecialization);
4181
4182static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4183
4184static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg,
4185 unsigned Depth,
4186 unsigned Index) {
4187 switch (Arg.getKind()) {
4188 case TemplateArgument::Null:
4189 case TemplateArgument::NullPtr:
4190 case TemplateArgument::Integral:
4191 case TemplateArgument::Declaration:
4192 case TemplateArgument::StructuralValue:
4193 case TemplateArgument::Pack:
4194 case TemplateArgument::TemplateExpansion:
4195 return false;
4196
4197 case TemplateArgument::Type: {
4198 QualType Type = Arg.getAsType();
4199 const TemplateTypeParmType *TPT =
4200 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4201 return TPT && !Type.hasQualifiers() &&
4202 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4203 }
4204
4205 case TemplateArgument::Expression: {
4206 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg.getAsExpr());
4207 if (!DRE || !DRE->getDecl())
4208 return false;
4209 const NonTypeTemplateParmDecl *NTTP =
4210 dyn_cast<NonTypeTemplateParmDecl>(Val: DRE->getDecl());
4211 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4212 }
4213
4214 case TemplateArgument::Template:
4215 const TemplateTemplateParmDecl *TTP =
4216 dyn_cast_or_null<TemplateTemplateParmDecl>(
4217 Val: Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4218 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4219 }
4220 llvm_unreachable("unexpected kind of template argument");
4221}
4222
4223static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4224 TemplateParameterList *SpecParams,
4225 ArrayRef<TemplateArgument> Args) {
4226 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4227 return false;
4228
4229 unsigned Depth = Params->getDepth();
4230
4231 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4232 TemplateArgument Arg = Args[I];
4233
4234 // If the parameter is a pack expansion, the argument must be a pack
4235 // whose only element is a pack expansion.
4236 if (Params->getParam(Idx: I)->isParameterPack()) {
4237 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4238 !Arg.pack_begin()->isPackExpansion())
4239 return false;
4240 Arg = Arg.pack_begin()->getPackExpansionPattern();
4241 }
4242
4243 if (!isTemplateArgumentTemplateParameter(Arg, Depth, Index: I))
4244 return false;
4245
4246 // For NTTPs further specialization is allowed via deduced types, so
4247 // we need to make sure to only reject here if primary template and
4248 // specialization use the same type for the NTTP.
4249 if (auto *SpecNTTP =
4250 dyn_cast<NonTypeTemplateParmDecl>(Val: SpecParams->getParam(Idx: I))) {
4251 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: I));
4252 if (!NTTP || NTTP->getType().getCanonicalType() !=
4253 SpecNTTP->getType().getCanonicalType())
4254 return false;
4255 }
4256 }
4257
4258 return true;
4259}
4260
4261template<typename PartialSpecDecl>
4262static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4263 if (Partial->getDeclContext()->isDependentContext())
4264 return;
4265
4266 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4267 // for non-substitution-failure issues?
4268 TemplateDeductionInfo Info(Partial->getLocation());
4269 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4270 return;
4271
4272 auto *Template = Partial->getSpecializedTemplate();
4273 S.Diag(Partial->getLocation(),
4274 diag::ext_partial_spec_not_more_specialized_than_primary)
4275 << isa<VarTemplateDecl>(Template);
4276
4277 if (Info.hasSFINAEDiagnostic()) {
4278 PartialDiagnosticAt Diag = {SourceLocation(),
4279 PartialDiagnostic::NullDiagnostic()};
4280 Info.takeSFINAEDiagnostic(PD&: Diag);
4281 SmallString<128> SFINAEArgString;
4282 Diag.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
4283 S.Diag(Loc: Diag.first,
4284 DiagID: diag::note_partial_spec_not_more_specialized_than_primary)
4285 << SFINAEArgString;
4286 }
4287
4288 S.NoteTemplateLocation(Decl: *Template);
4289 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4290 Template->getAssociatedConstraints(TemplateAC);
4291 Partial->getAssociatedConstraints(PartialAC);
4292 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Partial, AC1: PartialAC, D2: Template,
4293 AC2: TemplateAC);
4294}
4295
4296static void
4297noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4298 const llvm::SmallBitVector &DeducibleParams) {
4299 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4300 if (!DeducibleParams[I]) {
4301 NamedDecl *Param = TemplateParams->getParam(Idx: I);
4302 if (Param->getDeclName())
4303 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4304 << Param->getDeclName();
4305 else
4306 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4307 << "(anonymous)";
4308 }
4309 }
4310}
4311
4312
4313template<typename PartialSpecDecl>
4314static void checkTemplatePartialSpecialization(Sema &S,
4315 PartialSpecDecl *Partial) {
4316 // C++1z [temp.class.spec]p8: (DR1495)
4317 // - The specialization shall be more specialized than the primary
4318 // template (14.5.5.2).
4319 checkMoreSpecializedThanPrimary(S, Partial);
4320
4321 // C++ [temp.class.spec]p8: (DR1315)
4322 // - Each template-parameter shall appear at least once in the
4323 // template-id outside a non-deduced context.
4324 // C++1z [temp.class.spec.match]p3 (P0127R2)
4325 // If the template arguments of a partial specialization cannot be
4326 // deduced because of the structure of its template-parameter-list
4327 // and the template-id, the program is ill-formed.
4328 auto *TemplateParams = Partial->getTemplateParameters();
4329 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4330 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4331 TemplateParams->getDepth(), DeducibleParams);
4332
4333 if (!DeducibleParams.all()) {
4334 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4335 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4336 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4337 << (NumNonDeducible > 1)
4338 << SourceRange(Partial->getLocation(),
4339 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4340 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4341 }
4342}
4343
4344void Sema::CheckTemplatePartialSpecialization(
4345 ClassTemplatePartialSpecializationDecl *Partial) {
4346 checkTemplatePartialSpecialization(S&: *this, Partial);
4347}
4348
4349void Sema::CheckTemplatePartialSpecialization(
4350 VarTemplatePartialSpecializationDecl *Partial) {
4351 checkTemplatePartialSpecialization(S&: *this, Partial);
4352}
4353
4354void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4355 // C++1z [temp.param]p11:
4356 // A template parameter of a deduction guide template that does not have a
4357 // default-argument shall be deducible from the parameter-type-list of the
4358 // deduction guide template.
4359 auto *TemplateParams = TD->getTemplateParameters();
4360 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4361 MarkDeducedTemplateParameters(FunctionTemplate: TD, Deduced&: DeducibleParams);
4362 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4363 // A parameter pack is deducible (to an empty pack).
4364 auto *Param = TemplateParams->getParam(Idx: I);
4365 if (Param->isParameterPack() || hasVisibleDefaultArgument(D: Param))
4366 DeducibleParams[I] = true;
4367 }
4368
4369 if (!DeducibleParams.all()) {
4370 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4371 Diag(Loc: TD->getLocation(), DiagID: diag::err_deduction_guide_template_not_deducible)
4372 << (NumNonDeducible > 1);
4373 noteNonDeducibleParameters(S&: *this, TemplateParams, DeducibleParams);
4374 }
4375}
4376
4377DeclResult Sema::ActOnVarTemplateSpecialization(
4378 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
4379 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4380 StorageClass SC, bool IsPartialSpecialization) {
4381 // D must be variable template id.
4382 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4383 "Variable template specialization is declared with a template id.");
4384
4385 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4386 TemplateArgumentListInfo TemplateArgs =
4387 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TemplateId);
4388 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4389 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4390 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4391
4392 TemplateName Name = TemplateId->Template.get();
4393
4394 // The template-id must name a variable template.
4395 VarTemplateDecl *VarTemplate =
4396 dyn_cast_or_null<VarTemplateDecl>(Val: Name.getAsTemplateDecl());
4397 if (!VarTemplate) {
4398 NamedDecl *FnTemplate;
4399 if (auto *OTS = Name.getAsOverloadedTemplate())
4400 FnTemplate = *OTS->begin();
4401 else
4402 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Val: Name.getAsTemplateDecl());
4403 if (FnTemplate)
4404 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template_but_method)
4405 << FnTemplate->getDeclName();
4406 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template)
4407 << IsPartialSpecialization;
4408 }
4409
4410 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4411 auto Message = DSA->getMessage();
4412 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
4413 << VarTemplate << !Message.empty() << Message;
4414 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
4415 }
4416
4417 // Check for unexpanded parameter packs in any of the template arguments.
4418 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4419 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
4420 UPPC: IsPartialSpecialization
4421 ? UPPC_PartialSpecialization
4422 : UPPC_ExplicitSpecialization))
4423 return true;
4424
4425 // Check that the template argument list is well-formed for this
4426 // template.
4427 CheckTemplateArgumentInfo CTAI;
4428 if (CheckTemplateArgumentList(Template: VarTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
4429 /*DefaultArgs=*/{},
4430 /*PartialTemplateArgs=*/false, CTAI,
4431 /*UpdateArgsWithConversions=*/true))
4432 return true;
4433
4434 // Find the variable template (partial) specialization declaration that
4435 // corresponds to these arguments.
4436 if (IsPartialSpecialization) {
4437 if (CheckTemplatePartialSpecializationArgs(Loc: TemplateNameLoc, PrimaryTemplate: VarTemplate,
4438 NumExplicitArgs: TemplateArgs.size(),
4439 Args: CTAI.CanonicalConverted))
4440 return true;
4441
4442 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4443 // we also do them during instantiation.
4444 if (!Name.isDependent() &&
4445 !TemplateSpecializationType::anyDependentTemplateArguments(
4446 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4447 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
4448 << VarTemplate->getDeclName();
4449 IsPartialSpecialization = false;
4450 }
4451
4452 if (isSameAsPrimaryTemplate(Params: VarTemplate->getTemplateParameters(),
4453 SpecParams: TemplateParams, Args: CTAI.CanonicalConverted) &&
4454 (!Context.getLangOpts().CPlusPlus20 ||
4455 !TemplateParams->hasAssociatedConstraints())) {
4456 // C++ [temp.class.spec]p9b3:
4457 //
4458 // -- The argument list of the specialization shall not be identical
4459 // to the implicit argument list of the primary template.
4460 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
4461 << /*variable template*/ 1
4462 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4463 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
4464 // FIXME: Recover from this by treating the declaration as a
4465 // redeclaration of the primary template.
4466 return true;
4467 }
4468 }
4469
4470 void *InsertPos = nullptr;
4471 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4472
4473 if (IsPartialSpecialization)
4474 PrevDecl = VarTemplate->findPartialSpecialization(
4475 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
4476 else
4477 PrevDecl =
4478 VarTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
4479
4480 VarTemplateSpecializationDecl *Specialization = nullptr;
4481
4482 // Check whether we can declare a variable template specialization in
4483 // the current scope.
4484 if (CheckTemplateSpecializationScope(S&: *this, Specialized: VarTemplate, PrevDecl,
4485 Loc: TemplateNameLoc,
4486 IsPartialSpecialization))
4487 return true;
4488
4489 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4490 // Since the only prior variable template specialization with these
4491 // arguments was referenced but not declared, reuse that
4492 // declaration node as our own, updating its source location and
4493 // the list of outer template parameters to reflect our new declaration.
4494 Specialization = PrevDecl;
4495 Specialization->setLocation(TemplateNameLoc);
4496 PrevDecl = nullptr;
4497 } else if (IsPartialSpecialization) {
4498 // Create a new class template partial specialization declaration node.
4499 VarTemplatePartialSpecializationDecl *PrevPartial =
4500 cast_or_null<VarTemplatePartialSpecializationDecl>(Val: PrevDecl);
4501 VarTemplatePartialSpecializationDecl *Partial =
4502 VarTemplatePartialSpecializationDecl::Create(
4503 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc,
4504 IdLoc: TemplateNameLoc, Params: TemplateParams, SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI,
4505 S: SC, Args: CTAI.CanonicalConverted);
4506 Partial->setTemplateArgsAsWritten(TemplateArgs);
4507
4508 if (!PrevPartial)
4509 VarTemplate->AddPartialSpecialization(D: Partial, InsertPos);
4510 Specialization = Partial;
4511
4512 CheckTemplatePartialSpecialization(Partial);
4513 } else {
4514 // Create a new class template specialization declaration node for
4515 // this explicit specialization or friend declaration.
4516 Specialization = VarTemplateSpecializationDecl::Create(
4517 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc, IdLoc: TemplateNameLoc,
4518 SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI, S: SC, Args: CTAI.CanonicalConverted);
4519 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4520
4521 if (!PrevDecl)
4522 VarTemplate->AddSpecialization(D: Specialization, InsertPos);
4523 }
4524
4525 // C++ [temp.expl.spec]p6:
4526 // If a template, a member template or the member of a class template is
4527 // explicitly specialized then that specialization shall be declared
4528 // before the first use of that specialization that would cause an implicit
4529 // instantiation to take place, in every translation unit in which such a
4530 // use occurs; no diagnostic is required.
4531 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4532 bool Okay = false;
4533 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4534 // Is there any previous explicit specialization declaration?
4535 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
4536 Okay = true;
4537 break;
4538 }
4539 }
4540
4541 if (!Okay) {
4542 SourceRange Range(TemplateNameLoc, RAngleLoc);
4543 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
4544 << Name << Range;
4545
4546 Diag(Loc: PrevDecl->getPointOfInstantiation(),
4547 DiagID: diag::note_instantiation_required_here)
4548 << (PrevDecl->getTemplateSpecializationKind() !=
4549 TSK_ImplicitInstantiation);
4550 return true;
4551 }
4552 }
4553
4554 Specialization->setLexicalDeclContext(CurContext);
4555
4556 // Add the specialization into its lexical context, so that it can
4557 // be seen when iterating through the list of declarations in that
4558 // context. However, specializations are not found by name lookup.
4559 CurContext->addDecl(D: Specialization);
4560
4561 // Note that this is an explicit specialization.
4562 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4563
4564 Previous.clear();
4565 if (PrevDecl)
4566 Previous.addDecl(D: PrevDecl);
4567 else if (Specialization->isStaticDataMember() &&
4568 Specialization->isOutOfLine())
4569 Specialization->setAccess(VarTemplate->getAccess());
4570
4571 return Specialization;
4572}
4573
4574namespace {
4575/// A partial specialization whose template arguments have matched
4576/// a given template-id.
4577struct PartialSpecMatchResult {
4578 VarTemplatePartialSpecializationDecl *Partial;
4579 TemplateArgumentList *Args;
4580};
4581
4582// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4583// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4584static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4585 if (Var->getName() != "format_kind" ||
4586 !Var->getDeclContext()->isStdNamespace())
4587 return false;
4588
4589 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4590 // release in which users can access std::format_kind.
4591 // We can use 20250520 as the final date, see the following commits.
4592 // GCC releases/gcc-15 branch:
4593 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4594 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4595 // GCC master branch:
4596 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4597 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4598 return PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2025'05'20);
4599}
4600} // end anonymous namespace
4601
4602DeclResult
4603Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4604 SourceLocation TemplateNameLoc,
4605 const TemplateArgumentListInfo &TemplateArgs,
4606 bool SetWrittenArgs) {
4607 assert(Template && "A variable template id without template?");
4608
4609 // Check that the template argument list is well-formed for this template.
4610 CheckTemplateArgumentInfo CTAI;
4611 if (CheckTemplateArgumentList(
4612 Template, TemplateLoc: TemplateNameLoc,
4613 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4614 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4615 /*UpdateArgsWithConversions=*/true))
4616 return true;
4617
4618 // Produce a placeholder value if the specialization is dependent.
4619 if (Template->getDeclContext()->isDependentContext() ||
4620 TemplateSpecializationType::anyDependentTemplateArguments(
4621 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4622 if (ParsingInitForAutoVars.empty())
4623 return DeclResult();
4624
4625 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4626 const TemplateArgument &Arg2) {
4627 return Context.isSameTemplateArgument(Arg1, Arg2);
4628 };
4629
4630 if (VarDecl *Var = Template->getTemplatedDecl();
4631 ParsingInitForAutoVars.count(Ptr: Var) &&
4632 // See comments on this function definition
4633 !IsLibstdcxxStdFormatKind(PP, Var) &&
4634 llvm::equal(
4635 LRange&: CTAI.CanonicalConverted,
4636 RRange: Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4637 P: IsSameTemplateArg)) {
4638 Diag(Loc: TemplateNameLoc,
4639 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4640 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4641 return true;
4642 }
4643
4644 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4645 Template->getPartialSpecializations(PS&: PartialSpecs);
4646 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4647 if (ParsingInitForAutoVars.count(Ptr: Partial) &&
4648 llvm::equal(LRange&: CTAI.CanonicalConverted,
4649 RRange: Partial->getTemplateArgs().asArray(),
4650 P: IsSameTemplateArg)) {
4651 Diag(Loc: TemplateNameLoc,
4652 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4653 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4654 << Partial->getType();
4655 return true;
4656 }
4657
4658 return DeclResult();
4659 }
4660
4661 // Find the variable template specialization declaration that
4662 // corresponds to these arguments.
4663 void *InsertPos = nullptr;
4664 if (VarTemplateSpecializationDecl *Spec =
4665 Template->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos)) {
4666 checkSpecializationReachability(Loc: TemplateNameLoc, Spec);
4667 if (Spec->getType()->isUndeducedType()) {
4668 if (ParsingInitForAutoVars.count(Ptr: Spec))
4669 Diag(Loc: TemplateNameLoc,
4670 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4671 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4672 << Spec->getType();
4673 else
4674 // We are substituting the initializer of this variable template
4675 // specialization.
4676 Diag(Loc: TemplateNameLoc, DiagID: diag::err_var_template_spec_type_depends_on_self)
4677 << Spec << Spec->getType();
4678
4679 return true;
4680 }
4681 // If we already have a variable template specialization, return it.
4682 return Spec;
4683 }
4684
4685 // This is the first time we have referenced this variable template
4686 // specialization. Create the canonical declaration and add it to
4687 // the set of specializations, based on the closest partial specialization
4688 // that it represents. That is,
4689 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4690 const TemplateArgumentList *PartialSpecArgs = nullptr;
4691 bool AmbiguousPartialSpec = false;
4692 typedef PartialSpecMatchResult MatchResult;
4693 SmallVector<MatchResult, 4> Matched;
4694 SourceLocation PointOfInstantiation = TemplateNameLoc;
4695 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4696 /*ForTakingAddress=*/false);
4697
4698 // 1. Attempt to find the closest partial specialization that this
4699 // specializes, if any.
4700 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4701 // Perhaps better after unification of DeduceTemplateArguments() and
4702 // getMoreSpecializedPartialSpecialization().
4703 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4704 Template->getPartialSpecializations(PS&: PartialSpecs);
4705
4706 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4707 // C++ [temp.spec.partial.member]p2:
4708 // If the primary member template is explicitly specialized for a given
4709 // (implicit) specialization of the enclosing class template, the partial
4710 // specializations of the member template are ignored for this
4711 // specialization of the enclosing class template. If a partial
4712 // specialization of the member template is explicitly specialized for a
4713 // given (implicit) specialization of the enclosing class template, the
4714 // primary member template and its other partial specializations are still
4715 // considered for this specialization of the enclosing class template.
4716 if (Template->isMemberSpecialization() &&
4717 !Partial->isMemberSpecialization())
4718 continue;
4719
4720 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4721
4722 if (TemplateDeductionResult Result =
4723 DeduceTemplateArguments(Partial, TemplateArgs: CTAI.SugaredConverted, Info);
4724 Result != TemplateDeductionResult::Success) {
4725 // Store the failed-deduction information for use in diagnostics, later.
4726 // TODO: Actually use the failed-deduction info?
4727 FailedCandidates.addCandidate().set(
4728 Found: DeclAccessPair::make(D: Template, AS: AS_public), Spec: Partial,
4729 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
4730 (void)Result;
4731 } else {
4732 Matched.push_back(Elt: PartialSpecMatchResult());
4733 Matched.back().Partial = Partial;
4734 Matched.back().Args = Info.takeSugared();
4735 }
4736 }
4737
4738 if (Matched.size() >= 1) {
4739 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4740 if (Matched.size() == 1) {
4741 // -- If exactly one matching specialization is found, the
4742 // instantiation is generated from that specialization.
4743 // We don't need to do anything for this.
4744 } else {
4745 // -- If more than one matching specialization is found, the
4746 // partial order rules (14.5.4.2) are used to determine
4747 // whether one of the specializations is more specialized
4748 // than the others. If none of the specializations is more
4749 // specialized than all of the other matching
4750 // specializations, then the use of the variable template is
4751 // ambiguous and the program is ill-formed.
4752 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4753 PEnd = Matched.end();
4754 P != PEnd; ++P) {
4755 if (getMoreSpecializedPartialSpecialization(PS1: P->Partial, PS2: Best->Partial,
4756 Loc: PointOfInstantiation) ==
4757 P->Partial)
4758 Best = P;
4759 }
4760
4761 // Determine if the best partial specialization is more specialized than
4762 // the others.
4763 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4764 PEnd = Matched.end();
4765 P != PEnd; ++P) {
4766 if (P != Best && getMoreSpecializedPartialSpecialization(
4767 PS1: P->Partial, PS2: Best->Partial,
4768 Loc: PointOfInstantiation) != Best->Partial) {
4769 AmbiguousPartialSpec = true;
4770 break;
4771 }
4772 }
4773 }
4774
4775 // Instantiate using the best variable template partial specialization.
4776 InstantiationPattern = Best->Partial;
4777 PartialSpecArgs = Best->Args;
4778 } else {
4779 // -- If no match is found, the instantiation is generated
4780 // from the primary template.
4781 // InstantiationPattern = Template->getTemplatedDecl();
4782 }
4783
4784 // 2. Create the canonical declaration.
4785 // Note that we do not instantiate a definition until we see an odr-use
4786 // in DoMarkVarDeclReferenced().
4787 // FIXME: LateAttrs et al.?
4788 if (AmbiguousPartialSpec) {
4789 // Partial ordering did not produce a clear winner. Complain.
4790 Diag(Loc: PointOfInstantiation, DiagID: diag::err_partial_spec_ordering_ambiguous)
4791 << Template;
4792 // Print the matching partial specializations.
4793 for (MatchResult P : Matched)
4794 Diag(Loc: P.Partial->getLocation(), DiagID: diag::note_partial_spec_match)
4795 << getTemplateArgumentBindingsText(Params: P.Partial->getTemplateParameters(),
4796 Args: *P.Args);
4797 return true;
4798 }
4799
4800 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4801 VarTemplate: Template, FromVar: InstantiationPattern, PartialSpecArgs, Converted&: CTAI.CanonicalConverted,
4802 PointOfInstantiation: TemplateNameLoc /*, LateAttrs, StartingScope*/);
4803 if (!Decl)
4804 return true;
4805 if (SetWrittenArgs)
4806 Decl->setTemplateArgsAsWritten(TemplateArgs);
4807
4808 if (VarTemplatePartialSpecializationDecl *D =
4809 dyn_cast<VarTemplatePartialSpecializationDecl>(Val: InstantiationPattern))
4810 Decl->setInstantiationOf(PartialSpec: D, TemplateArgs: PartialSpecArgs);
4811
4812 checkSpecializationReachability(Loc: TemplateNameLoc, Spec: Decl);
4813
4814 assert(Decl && "No variable template specialization?");
4815 return Decl;
4816}
4817
4818ExprResult Sema::CheckVarTemplateId(
4819 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4820 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4821 const TemplateArgumentListInfo *TemplateArgs) {
4822
4823 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, TemplateNameLoc: NameInfo.getLoc(),
4824 TemplateArgs: *TemplateArgs, /*SetWrittenArgs=*/false);
4825 if (Decl.isInvalid())
4826 return ExprError();
4827
4828 if (!Decl.get())
4829 return ExprResult();
4830
4831 VarDecl *Var = cast<VarDecl>(Val: Decl.get());
4832 if (!Var->getTemplateSpecializationKind())
4833 Var->setTemplateSpecializationKind(TSK: TSK_ImplicitInstantiation,
4834 PointOfInstantiation: NameInfo.getLoc());
4835
4836 // Build an ordinary singleton decl ref.
4837 return BuildDeclarationNameExpr(SS, NameInfo, D: Var, FoundD, TemplateArgs);
4838}
4839
4840ExprResult Sema::CheckVarOrConceptTemplateTemplateId(
4841 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4842 TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc,
4843 const TemplateArgumentListInfo *TemplateArgs) {
4844 assert(Template && "A variable template id without template?");
4845
4846 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4847 Template->templateParameterKind() !=
4848 TemplateNameKind::TNK_Concept_template)
4849 return ExprResult();
4850
4851 // Check that the template argument list is well-formed for this template.
4852 CheckTemplateArgumentInfo CTAI;
4853 if (CheckTemplateArgumentList(
4854 Template, TemplateLoc,
4855 // FIXME: TemplateArgs will not be modified because
4856 // UpdateArgsWithConversions is false, however, we should
4857 // CheckTemplateArgumentList to be const-correct.
4858 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4859 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4860 /*UpdateArgsWithConversions=*/false))
4861 return true;
4862
4863 UnresolvedSet<1> R;
4864 R.addDecl(D: Template);
4865
4866 // FIXME: We model references to variable template and concept parameters
4867 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4868 // data, can generally be used in the same places and work the same way.
4869 // However, it might be cleaner to use a dedicated AST node in the long run.
4870 return UnresolvedLookupExpr::Create(
4871 Context: getASTContext(), NamingClass: nullptr, QualifierLoc: SS.getWithLocInContext(Context&: getASTContext()),
4872 TemplateKWLoc: SourceLocation(), NameInfo, RequiresADL: false, Args: TemplateArgs, Begin: R.begin(), End: R.end(),
4873 /*KnownDependent=*/false,
4874 /*KnownInstantiationDependent=*/false);
4875}
4876
4877void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4878 SourceLocation Loc) {
4879 Diag(Loc, DiagID: diag::err_template_missing_args)
4880 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4881 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4882 NoteTemplateLocation(Decl: *TD, ParamRange: TD->getTemplateParameters()->getSourceRange());
4883 }
4884}
4885
4886void Sema::diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
4887 bool TemplateKeyword,
4888 TemplateDecl *TD,
4889 SourceLocation Loc) {
4890 TemplateName Name = Context.getQualifiedTemplateName(
4891 Qualifier: SS.getScopeRep(), TemplateKeyword, Template: TemplateName(TD));
4892 diagnoseMissingTemplateArguments(Name, Loc);
4893}
4894
4895ExprResult Sema::CheckConceptTemplateId(
4896 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4897 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4898 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4899 bool DoCheckConstraintSatisfaction) {
4900 assert(NamedConcept && "A concept template id without a template?");
4901
4902 if (NamedConcept->isInvalidDecl())
4903 return ExprError();
4904
4905 CheckTemplateArgumentInfo CTAI;
4906 if (CheckTemplateArgumentList(
4907 Template: NamedConcept, TemplateLoc: ConceptNameInfo.getLoc(),
4908 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4909 /*DefaultArgs=*/{},
4910 /*PartialTemplateArgs=*/false, CTAI,
4911 /*UpdateArgsWithConversions=*/false))
4912 return ExprError();
4913
4914 DiagnoseUseOfDecl(D: NamedConcept, Locs: ConceptNameInfo.getLoc());
4915
4916 // There's a bug with CTAI.CanonicalConverted.
4917 // If the template argument contains a DependentDecltypeType that includes a
4918 // TypeAliasType, and the same written type had occurred previously in the
4919 // source, then the DependentDecltypeType would be canonicalized to that
4920 // previous type which would mess up the substitution.
4921 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4922 auto *CSD = ImplicitConceptSpecializationDecl::Create(
4923 C: Context, DC: NamedConcept->getDeclContext(), SL: NamedConcept->getLocation(),
4924 ConvertedArgs: CTAI.SugaredConverted);
4925 ConstraintSatisfaction Satisfaction;
4926 bool AreArgsDependent =
4927 TemplateSpecializationType::anyDependentTemplateArguments(
4928 *TemplateArgs, Converted: CTAI.SugaredConverted);
4929 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4930 /*Final=*/false);
4931 auto *CL = ConceptReference::Create(
4932 C: Context,
4933 NNS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4934 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4935 ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: *TemplateArgs));
4936
4937 bool Error = false;
4938 if (const auto *Concept = dyn_cast<ConceptDecl>(Val: NamedConcept);
4939 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4940 DoCheckConstraintSatisfaction) {
4941
4942 LocalInstantiationScope Scope(*this);
4943
4944 EnterExpressionEvaluationContext EECtx{
4945 *this, ExpressionEvaluationContext::Unevaluated};
4946
4947 Error = CheckConstraintSatisfaction(
4948 Entity: NamedConcept, AssociatedConstraints: AssociatedConstraint(Concept->getConstraintExpr()), TemplateArgLists: MLTAL,
4949 TemplateIDRange: SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4950 TemplateArgs->getRAngleLoc()),
4951 Satisfaction, TopLevelConceptId: CL);
4952 Satisfaction.ContainsErrors = Error;
4953 }
4954
4955 if (Error)
4956 return ExprError();
4957
4958 return ConceptSpecializationExpr::Create(
4959 C: Context, ConceptRef: CL, SpecDecl: CSD, Satisfaction: AreArgsDependent ? nullptr : &Satisfaction);
4960}
4961
4962ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4963 SourceLocation TemplateKWLoc,
4964 LookupResult &R,
4965 bool RequiresADL,
4966 const TemplateArgumentListInfo *TemplateArgs) {
4967 // FIXME: Can we do any checking at this point? I guess we could check the
4968 // template arguments that we have against the template name, if the template
4969 // name refers to a single template. That's not a terribly common case,
4970 // though.
4971 // foo<int> could identify a single function unambiguously
4972 // This approach does NOT work, since f<int>(1);
4973 // gets resolved prior to resorting to overload resolution
4974 // i.e., template<class T> void f(double);
4975 // vs template<class T, class U> void f(U);
4976
4977 // These should be filtered out by our callers.
4978 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4979
4980 // Non-function templates require a template argument list.
4981 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4982 if (!TemplateArgs && !isa<FunctionTemplateDecl>(Val: TD)) {
4983 diagnoseMissingTemplateArguments(
4984 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, Loc: R.getNameLoc());
4985 return ExprError();
4986 }
4987 }
4988 bool KnownDependent = false;
4989 // In C++1y, check variable template ids.
4990 if (R.getAsSingle<VarTemplateDecl>()) {
4991 ExprResult Res = CheckVarTemplateId(
4992 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<VarTemplateDecl>(),
4993 FoundD: R.getRepresentativeDecl(), TemplateLoc: TemplateKWLoc, TemplateArgs);
4994 if (Res.isInvalid() || Res.isUsable())
4995 return Res;
4996 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4997 KnownDependent = true;
4998 }
4999
5000 // We don't want lookup warnings at this point.
5001 R.suppressDiagnostics();
5002
5003 if (R.getAsSingle<ConceptDecl>()) {
5004 return CheckConceptTemplateId(SS, TemplateKWLoc, ConceptNameInfo: R.getLookupNameInfo(),
5005 FoundDecl: R.getRepresentativeDecl(),
5006 NamedConcept: R.getAsSingle<ConceptDecl>(), TemplateArgs);
5007 }
5008
5009 // Check variable template ids (C++17) and concept template parameters
5010 // (C++26).
5011 UnresolvedLookupExpr *ULE;
5012 if (R.getAsSingle<TemplateTemplateParmDecl>())
5013 return CheckVarOrConceptTemplateTemplateId(
5014 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<TemplateTemplateParmDecl>(),
5015 TemplateLoc: TemplateKWLoc, TemplateArgs);
5016
5017 // Function templates
5018 ULE = UnresolvedLookupExpr::Create(
5019 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
5020 TemplateKWLoc, NameInfo: R.getLookupNameInfo(), RequiresADL, Args: TemplateArgs,
5021 Begin: R.begin(), End: R.end(), KnownDependent,
5022 /*KnownInstantiationDependent=*/false);
5023 // Model the templates with UnresolvedTemplateTy. The expression should then
5024 // either be transformed in an instantiation or be diagnosed in
5025 // CheckPlaceholderExpr.
5026 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5027 !R.getFoundDecl()->getAsFunction())
5028 ULE->setType(Context.UnresolvedTemplateTy);
5029
5030 return ULE;
5031}
5032
5033ExprResult Sema::BuildQualifiedTemplateIdExpr(
5034 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5035 const DeclarationNameInfo &NameInfo,
5036 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5037 assert(TemplateArgs || TemplateKWLoc.isValid());
5038
5039 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5040 if (LookupTemplateName(Found&: R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5041 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc))
5042 return ExprError();
5043
5044 if (R.isAmbiguous())
5045 return ExprError();
5046
5047 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5048 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5049
5050 if (R.empty()) {
5051 DeclContext *DC = computeDeclContext(SS);
5052 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
5053 << NameInfo.getName() << DC << SS.getRange();
5054 return ExprError();
5055 }
5056
5057 // If necessary, build an implicit class member access.
5058 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5059 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5060 /*S=*/nullptr);
5061
5062 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/RequiresADL: false, TemplateArgs);
5063}
5064
5065TemplateNameKind Sema::ActOnTemplateName(Scope *S,
5066 CXXScopeSpec &SS,
5067 SourceLocation TemplateKWLoc,
5068 const UnqualifiedId &Name,
5069 ParsedType ObjectType,
5070 bool EnteringContext,
5071 TemplateTy &Result,
5072 bool AllowInjectedClassName) {
5073 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5074 Diag(Loc: TemplateKWLoc,
5075 DiagID: getLangOpts().CPlusPlus11 ?
5076 diag::warn_cxx98_compat_template_outside_of_template :
5077 diag::ext_template_outside_of_template)
5078 << FixItHint::CreateRemoval(RemoveRange: TemplateKWLoc);
5079
5080 if (SS.isInvalid())
5081 return TNK_Non_template;
5082
5083 // Figure out where isTemplateName is going to look.
5084 DeclContext *LookupCtx = nullptr;
5085 if (SS.isNotEmpty())
5086 LookupCtx = computeDeclContext(SS, EnteringContext);
5087 else if (ObjectType)
5088 LookupCtx = computeDeclContext(T: GetTypeFromParser(Ty: ObjectType));
5089
5090 // C++0x [temp.names]p5:
5091 // If a name prefixed by the keyword template is not the name of
5092 // a template, the program is ill-formed. [Note: the keyword
5093 // template may not be applied to non-template members of class
5094 // templates. -end note ] [ Note: as is the case with the
5095 // typename prefix, the template prefix is allowed in cases
5096 // where it is not strictly necessary; i.e., when the
5097 // nested-name-specifier or the expression on the left of the ->
5098 // or . is not dependent on a template-parameter, or the use
5099 // does not appear in the scope of a template. -end note]
5100 //
5101 // Note: C++03 was more strict here, because it banned the use of
5102 // the "template" keyword prior to a template-name that was not a
5103 // dependent name. C++ DR468 relaxed this requirement (the
5104 // "template" keyword is now permitted). We follow the C++0x
5105 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5106 bool MemberOfUnknownSpecialization;
5107 TemplateNameKind TNK = isTemplateName(S, SS, hasTemplateKeyword: TemplateKWLoc.isValid(), Name,
5108 ObjectTypePtr: ObjectType, EnteringContext, TemplateResult&: Result,
5109 MemberOfUnknownSpecialization);
5110 if (TNK != TNK_Non_template) {
5111 // We resolved this to a (non-dependent) template name. Return it.
5112 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
5113 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5114 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5115 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5116 // C++14 [class.qual]p2:
5117 // In a lookup in which function names are not ignored and the
5118 // nested-name-specifier nominates a class C, if the name specified
5119 // [...] is the injected-class-name of C, [...] the name is instead
5120 // considered to name the constructor
5121 //
5122 // We don't get here if naming the constructor would be valid, so we
5123 // just reject immediately and recover by treating the
5124 // injected-class-name as naming the template.
5125 Diag(Loc: Name.getBeginLoc(),
5126 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
5127 << Name.Identifier
5128 << 0 /*injected-class-name used as template name*/
5129 << TemplateKWLoc.isValid();
5130 }
5131 return TNK;
5132 }
5133
5134 if (!MemberOfUnknownSpecialization) {
5135 // Didn't find a template name, and the lookup wasn't dependent.
5136 // Do the lookup again to determine if this is a "nothing found" case or
5137 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5138 // need to do this.
5139 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
5140 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5141 LookupOrdinaryName);
5142 // Tell LookupTemplateName that we require a template so that it diagnoses
5143 // cases where it finds a non-template.
5144 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5145 ? RequiredTemplateKind(TemplateKWLoc)
5146 : TemplateNameIsRequired;
5147 if (!LookupTemplateName(Found&: R, S, SS, ObjectType: ObjectType.get(), EnteringContext, RequiredTemplate: RTK,
5148 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5149 !R.isAmbiguous()) {
5150 if (LookupCtx)
5151 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_no_member)
5152 << DNI.getName() << LookupCtx << SS.getRange();
5153 else
5154 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_undeclared_use)
5155 << DNI.getName() << SS.getRange();
5156 }
5157 return TNK_Non_template;
5158 }
5159
5160 NestedNameSpecifier Qualifier = SS.getScopeRep();
5161
5162 switch (Name.getKind()) {
5163 case UnqualifiedIdKind::IK_Identifier:
5164 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5165 Name: {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5166 return TNK_Dependent_template_name;
5167
5168 case UnqualifiedIdKind::IK_OperatorFunctionId:
5169 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5170 Name: {Qualifier, Name.OperatorFunctionId.Operator,
5171 TemplateKWLoc.isValid()}));
5172 return TNK_Function_template;
5173
5174 case UnqualifiedIdKind::IK_LiteralOperatorId:
5175 // This is a kind of template name, but can never occur in a dependent
5176 // scope (literal operators can only be declared at namespace scope).
5177 break;
5178
5179 default:
5180 break;
5181 }
5182
5183 // This name cannot possibly name a dependent template. Diagnose this now
5184 // rather than building a dependent template name that can never be valid.
5185 Diag(Loc: Name.getBeginLoc(),
5186 DiagID: diag::err_template_kw_refers_to_dependent_non_template)
5187 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5188 << TemplateKWLoc.isValid() << TemplateKWLoc;
5189 return TNK_Non_template;
5190}
5191
5192bool Sema::CheckTemplateTypeArgument(
5193 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
5194 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5195 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5196 const TemplateArgument &Arg = AL.getArgument();
5197 QualType ArgType;
5198 TypeSourceInfo *TSI = nullptr;
5199
5200 // Check template type parameter.
5201 switch(Arg.getKind()) {
5202 case TemplateArgument::Type:
5203 // C++ [temp.arg.type]p1:
5204 // A template-argument for a template-parameter which is a
5205 // type shall be a type-id.
5206 ArgType = Arg.getAsType();
5207 TSI = AL.getTypeSourceInfo();
5208 break;
5209 case TemplateArgument::Template:
5210 case TemplateArgument::TemplateExpansion: {
5211 // We have a template type parameter but the template argument
5212 // is a template without any arguments.
5213 SourceRange SR = AL.getSourceRange();
5214 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5215 diagnoseMissingTemplateArguments(Name, Loc: SR.getEnd());
5216 return true;
5217 }
5218 case TemplateArgument::Expression: {
5219 // We have a template type parameter but the template argument is an
5220 // expression; see if maybe it is missing the "typename" keyword.
5221 CXXScopeSpec SS;
5222 DeclarationNameInfo NameInfo;
5223
5224 if (DependentScopeDeclRefExpr *ArgExpr =
5225 dyn_cast<DependentScopeDeclRefExpr>(Val: Arg.getAsExpr())) {
5226 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5227 NameInfo = ArgExpr->getNameInfo();
5228 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5229 dyn_cast<CXXDependentScopeMemberExpr>(Val: Arg.getAsExpr())) {
5230 if (ArgExpr->isImplicitAccess()) {
5231 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5232 NameInfo = ArgExpr->getMemberNameInfo();
5233 }
5234 }
5235
5236 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5237 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5238 LookupParsedName(R&: Result, S: CurScope, SS: &SS, /*ObjectType=*/QualType());
5239
5240 if (Result.getAsSingle<TypeDecl>() ||
5241 Result.wasNotFoundInCurrentInstantiation()) {
5242 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5243 // Suggest that the user add 'typename' before the NNS.
5244 SourceLocation Loc = AL.getSourceRange().getBegin();
5245 Diag(Loc, DiagID: getLangOpts().MSVCCompat
5246 ? diag::ext_ms_template_type_arg_missing_typename
5247 : diag::err_template_arg_must_be_type_suggest)
5248 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
5249 NoteTemplateParameterLocation(Decl: *Param);
5250
5251 // Recover by synthesizing a type using the location information that we
5252 // already have.
5253 ArgType = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
5254 NNS: SS.getScopeRep(), Name: II);
5255 TypeLocBuilder TLB;
5256 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: ArgType);
5257 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5258 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5259 TL.setNameLoc(NameInfo.getLoc());
5260 TSI = TLB.getTypeSourceInfo(Context, T: ArgType);
5261
5262 // Overwrite our input TemplateArgumentLoc so that we can recover
5263 // properly.
5264 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5265 TemplateArgumentLocInfo(TSI));
5266
5267 break;
5268 }
5269 }
5270 // fallthrough
5271 [[fallthrough]];
5272 }
5273 default: {
5274 // We allow instantiating a template with template argument packs when
5275 // building deduction guides or mapping constraint template parameters.
5276 if (Arg.getKind() == TemplateArgument::Pack &&
5277 (CodeSynthesisContexts.back().Kind ==
5278 Sema::CodeSynthesisContext::BuildingDeductionGuides ||
5279 inParameterMappingSubstitution())) {
5280 SugaredConverted.push_back(Elt: Arg);
5281 CanonicalConverted.push_back(Elt: Arg);
5282 return false;
5283 }
5284 // We have a template type parameter but the template argument
5285 // is not a type.
5286 SourceRange SR = AL.getSourceRange();
5287 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_type) << SR;
5288 NoteTemplateParameterLocation(Decl: *Param);
5289
5290 return true;
5291 }
5292 }
5293
5294 if (CheckTemplateArgument(Arg: TSI))
5295 return true;
5296
5297 // Objective-C ARC:
5298 // If an explicitly-specified template argument type is a lifetime type
5299 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5300 if (getLangOpts().ObjCAutoRefCount &&
5301 ArgType->isObjCLifetimeType() &&
5302 !ArgType.getObjCLifetime()) {
5303 Qualifiers Qs;
5304 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5305 ArgType = Context.getQualifiedType(T: ArgType, Qs);
5306 }
5307
5308 SugaredConverted.push_back(Elt: TemplateArgument(ArgType));
5309 CanonicalConverted.push_back(
5310 Elt: TemplateArgument(Context.getCanonicalType(T: ArgType)));
5311 return false;
5312}
5313
5314/// Substitute template arguments into the default template argument for
5315/// the given template type parameter.
5316///
5317/// \param SemaRef the semantic analysis object for which we are performing
5318/// the substitution.
5319///
5320/// \param Template the template that we are synthesizing template arguments
5321/// for.
5322///
5323/// \param TemplateLoc the location of the template name that started the
5324/// template-id we are checking.
5325///
5326/// \param RAngleLoc the location of the right angle bracket ('>') that
5327/// terminates the template-id.
5328///
5329/// \param Param the template template parameter whose default we are
5330/// substituting into.
5331///
5332/// \param Converted the list of template arguments provided for template
5333/// parameters that precede \p Param in the template parameter list.
5334///
5335/// \param Output the resulting substituted template argument.
5336///
5337/// \returns true if an error occurred.
5338static bool SubstDefaultTemplateArgument(
5339 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5340 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5341 ArrayRef<TemplateArgument> SugaredConverted,
5342 ArrayRef<TemplateArgument> CanonicalConverted,
5343 TemplateArgumentLoc &Output) {
5344 Output = Param->getDefaultArgument();
5345
5346 // If the argument type is dependent, instantiate it now based
5347 // on the previously-computed template arguments.
5348 if (Output.getArgument().isInstantiationDependent()) {
5349 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5350 SugaredConverted,
5351 SourceRange(TemplateLoc, RAngleLoc));
5352 if (Inst.isInvalid())
5353 return true;
5354
5355 // Only substitute for the innermost template argument list.
5356 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5357 /*Final=*/true);
5358 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5359 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5360
5361 bool ForLambdaCallOperator = false;
5362 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Val: Template->getDeclContext()))
5363 ForLambdaCallOperator = Rec->isLambda();
5364 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5365 !ForLambdaCallOperator);
5366
5367 if (SemaRef.SubstTemplateArgument(Input: Output, TemplateArgs: TemplateArgLists, Output,
5368 Loc: Param->getDefaultArgumentLoc(),
5369 Entity: Param->getDeclName()))
5370 return true;
5371 }
5372
5373 return false;
5374}
5375
5376/// Substitute template arguments into the default template argument for
5377/// the given non-type template parameter.
5378///
5379/// \param SemaRef the semantic analysis object for which we are performing
5380/// the substitution.
5381///
5382/// \param Template the template that we are synthesizing template arguments
5383/// for.
5384///
5385/// \param TemplateLoc the location of the template name that started the
5386/// template-id we are checking.
5387///
5388/// \param RAngleLoc the location of the right angle bracket ('>') that
5389/// terminates the template-id.
5390///
5391/// \param Param the non-type template parameter whose default we are
5392/// substituting into.
5393///
5394/// \param Converted the list of template arguments provided for template
5395/// parameters that precede \p Param in the template parameter list.
5396///
5397/// \returns the substituted template argument, or NULL if an error occurred.
5398static bool SubstDefaultTemplateArgument(
5399 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5400 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5401 ArrayRef<TemplateArgument> SugaredConverted,
5402 ArrayRef<TemplateArgument> CanonicalConverted,
5403 TemplateArgumentLoc &Output) {
5404 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5405 SugaredConverted,
5406 SourceRange(TemplateLoc, RAngleLoc));
5407 if (Inst.isInvalid())
5408 return true;
5409
5410 // Only substitute for the innermost template argument list.
5411 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5412 /*Final=*/true);
5413 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5414 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5415
5416 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5417 EnterExpressionEvaluationContext ConstantEvaluated(
5418 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5419 return SemaRef.SubstTemplateArgument(Input: Param->getDefaultArgument(),
5420 TemplateArgs: TemplateArgLists, Output);
5421}
5422
5423/// Substitute template arguments into the default template argument for
5424/// the given template template parameter.
5425///
5426/// \param SemaRef the semantic analysis object for which we are performing
5427/// the substitution.
5428///
5429/// \param Template the template that we are synthesizing template arguments
5430/// for.
5431///
5432/// \param TemplateLoc the location of the template name that started the
5433/// template-id we are checking.
5434///
5435/// \param RAngleLoc the location of the right angle bracket ('>') that
5436/// terminates the template-id.
5437///
5438/// \param Param the template template parameter whose default we are
5439/// substituting into.
5440///
5441/// \param Converted the list of template arguments provided for template
5442/// parameters that precede \p Param in the template parameter list.
5443///
5444/// \param QualifierLoc Will be set to the nested-name-specifier (with
5445/// source-location information) that precedes the template name.
5446///
5447/// \returns the substituted template argument, or NULL if an error occurred.
5448static TemplateName SubstDefaultTemplateArgument(
5449 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5450 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5451 TemplateTemplateParmDecl *Param,
5452 ArrayRef<TemplateArgument> SugaredConverted,
5453 ArrayRef<TemplateArgument> CanonicalConverted,
5454 NestedNameSpecifierLoc &QualifierLoc) {
5455 Sema::InstantiatingTemplate Inst(
5456 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5457 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5458 if (Inst.isInvalid())
5459 return TemplateName();
5460
5461 // Only substitute for the innermost template argument list.
5462 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5463 /*Final=*/true);
5464 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5465 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5466
5467 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5468
5469 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5470 QualifierLoc = A.getTemplateQualifierLoc();
5471 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5472 Name: A.getArgument().getAsTemplate(),
5473 NameLoc: A.getTemplateNameLoc(), TemplateArgs: TemplateArgLists);
5474}
5475
5476TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5477 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5478 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5479 ArrayRef<TemplateArgument> SugaredConverted,
5480 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5481 HasDefaultArg = false;
5482
5483 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
5484 if (!hasReachableDefaultArgument(D: TypeParm))
5485 return TemplateArgumentLoc();
5486
5487 HasDefaultArg = true;
5488 TemplateArgumentLoc Output;
5489 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5490 RAngleLoc, Param: TypeParm, SugaredConverted,
5491 CanonicalConverted, Output))
5492 return TemplateArgumentLoc();
5493 return Output;
5494 }
5495
5496 if (NonTypeTemplateParmDecl *NonTypeParm
5497 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5498 if (!hasReachableDefaultArgument(D: NonTypeParm))
5499 return TemplateArgumentLoc();
5500
5501 HasDefaultArg = true;
5502 TemplateArgumentLoc Output;
5503 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5504 RAngleLoc, Param: NonTypeParm, SugaredConverted,
5505 CanonicalConverted, Output))
5506 return TemplateArgumentLoc();
5507 return Output;
5508 }
5509
5510 TemplateTemplateParmDecl *TempTempParm
5511 = cast<TemplateTemplateParmDecl>(Val: Param);
5512 if (!hasReachableDefaultArgument(D: TempTempParm))
5513 return TemplateArgumentLoc();
5514
5515 HasDefaultArg = true;
5516 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5517 NestedNameSpecifierLoc QualifierLoc;
5518 TemplateName TName = SubstDefaultTemplateArgument(
5519 SemaRef&: *this, Template, TemplateKWLoc, TemplateLoc: TemplateNameLoc, RAngleLoc, Param: TempTempParm,
5520 SugaredConverted, CanonicalConverted, QualifierLoc);
5521 if (TName.isNull())
5522 return TemplateArgumentLoc();
5523
5524 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5525 QualifierLoc, A.getTemplateNameLoc());
5526}
5527
5528/// Convert a template-argument that we parsed as a type into a template, if
5529/// possible. C++ permits injected-class-names to perform dual service as
5530/// template template arguments and as template type arguments.
5531static TemplateArgumentLoc
5532convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5533 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5534 if (!TagLoc)
5535 return TemplateArgumentLoc();
5536
5537 // If this type was written as an injected-class-name, it can be used as a
5538 // template template argument.
5539 // If this type was written as an injected-class-name, it may have been
5540 // converted to a RecordType during instantiation. If the RecordType is
5541 // *not* wrapped in a TemplateSpecializationType and denotes a class
5542 // template specialization, it must have come from an injected-class-name.
5543
5544 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Ctx: Context);
5545 if (Name.isNull())
5546 return TemplateArgumentLoc();
5547
5548 return TemplateArgumentLoc(Context, Name,
5549 /*TemplateKWLoc=*/SourceLocation(),
5550 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5551}
5552
5553bool Sema::CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &ArgLoc,
5554 NamedDecl *Template,
5555 SourceLocation TemplateLoc,
5556 SourceLocation RAngleLoc,
5557 unsigned ArgumentPackIndex,
5558 CheckTemplateArgumentInfo &CTAI,
5559 CheckTemplateArgumentKind CTAK) {
5560 // Check template type parameters.
5561 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param))
5562 return CheckTemplateTypeArgument(Param: TTP, AL&: ArgLoc, SugaredConverted&: CTAI.SugaredConverted,
5563 CanonicalConverted&: CTAI.CanonicalConverted);
5564
5565 const TemplateArgument &Arg = ArgLoc.getArgument();
5566 // Check non-type template parameters.
5567 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5568 // Do substitution on the type of the non-type template parameter
5569 // with the template arguments we've seen thus far. But if the
5570 // template has a dependent context then we cannot substitute yet.
5571 QualType NTTPType = NTTP->getType();
5572 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5573 NTTPType = NTTP->getExpansionType(I: ArgumentPackIndex);
5574
5575 if (NTTPType->isInstantiationDependentType()) {
5576 // Do substitution on the type of the non-type template parameter.
5577 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5578 CTAI.SugaredConverted,
5579 SourceRange(TemplateLoc, RAngleLoc));
5580 if (Inst.isInvalid())
5581 return true;
5582
5583 MultiLevelTemplateArgumentList MLTAL(Template, CTAI.SugaredConverted,
5584 /*Final=*/true);
5585 MLTAL.addOuterRetainedLevels(Num: NTTP->getDepth());
5586 // If the parameter is a pack expansion, expand this slice of the pack.
5587 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5588 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5589 NTTPType = SubstType(T: PET->getPattern(), TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5590 Entity: NTTP->getDeclName());
5591 } else {
5592 NTTPType = SubstType(T: NTTPType, TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5593 Entity: NTTP->getDeclName());
5594 }
5595
5596 // If that worked, check the non-type template parameter type
5597 // for validity.
5598 if (!NTTPType.isNull())
5599 NTTPType = CheckNonTypeTemplateParameterType(T: NTTPType,
5600 Loc: NTTP->getLocation());
5601 if (NTTPType.isNull())
5602 return true;
5603 }
5604
5605 auto checkExpr = [&](Expr *E) -> Expr * {
5606 TemplateArgument SugaredResult, CanonicalResult;
5607 ExprResult Res = CheckTemplateArgument(
5608 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E, SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5609 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5610 // If the current template argument causes an error, give up now.
5611 if (Res.isInvalid())
5612 return nullptr;
5613 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5614 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5615 return Res.get();
5616 };
5617
5618 switch (Arg.getKind()) {
5619 case TemplateArgument::Null:
5620 llvm_unreachable("Should never see a NULL template argument here");
5621
5622 case TemplateArgument::Expression: {
5623 Expr *E = Arg.getAsExpr();
5624 Expr *R = checkExpr(E);
5625 if (!R)
5626 return true;
5627 // If the resulting expression is new, then use it in place of the
5628 // old expression in the template argument.
5629 if (R != E) {
5630 TemplateArgument TA(R, /*IsCanonical=*/false);
5631 ArgLoc = TemplateArgumentLoc(TA, R);
5632 }
5633 break;
5634 }
5635
5636 // As for the converted NTTP kinds, they still might need another
5637 // conversion, as the new corresponding parameter might be different.
5638 // Ideally, we would always perform substitution starting with sugared types
5639 // and never need these, as we would still have expressions. Since these are
5640 // needed so rarely, it's probably a better tradeoff to just convert them
5641 // back to expressions.
5642 case TemplateArgument::Integral:
5643 case TemplateArgument::Declaration:
5644 case TemplateArgument::NullPtr:
5645 case TemplateArgument::StructuralValue: {
5646 // FIXME: StructuralValue is untested here.
5647 ExprResult R =
5648 BuildExpressionFromNonTypeTemplateArgument(Arg, Loc: SourceLocation());
5649 assert(R.isUsable());
5650 if (!checkExpr(R.get()))
5651 return true;
5652 break;
5653 }
5654
5655 case TemplateArgument::Template:
5656 case TemplateArgument::TemplateExpansion:
5657 // We were given a template template argument. It may not be ill-formed;
5658 // see below.
5659 if (DependentTemplateName *DTN = Arg.getAsTemplateOrTemplatePattern()
5660 .getAsDependentTemplateName()) {
5661 // We have a template argument such as \c T::template X, which we
5662 // parsed as a template template argument. However, since we now
5663 // know that we need a non-type template argument, convert this
5664 // template name into an expression.
5665
5666 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5667 ArgLoc.getTemplateNameLoc());
5668
5669 CXXScopeSpec SS;
5670 SS.Adopt(Other: ArgLoc.getTemplateQualifierLoc());
5671 // FIXME: the template-template arg was a DependentTemplateName,
5672 // so it was provided with a template keyword. However, its source
5673 // location is not stored in the template argument structure.
5674 SourceLocation TemplateKWLoc;
5675 ExprResult E = DependentScopeDeclRefExpr::Create(
5676 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5677 TemplateArgs: nullptr);
5678
5679 // If we parsed the template argument as a pack expansion, create a
5680 // pack expansion expression.
5681 if (Arg.getKind() == TemplateArgument::TemplateExpansion) {
5682 E = ActOnPackExpansion(Pattern: E.get(), EllipsisLoc: ArgLoc.getTemplateEllipsisLoc());
5683 if (E.isInvalid())
5684 return true;
5685 }
5686
5687 TemplateArgument SugaredResult, CanonicalResult;
5688 E = CheckTemplateArgument(
5689 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E.get(), SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5690 /*StrictCheck=*/CTAI.PartialOrdering, CTAK: CTAK_Specified);
5691 if (E.isInvalid())
5692 return true;
5693
5694 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5695 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5696 break;
5697 }
5698
5699 // We have a template argument that actually does refer to a class
5700 // template, alias template, or template template parameter, and
5701 // therefore cannot be a non-type template argument.
5702 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_expr)
5703 << ArgLoc.getSourceRange();
5704 NoteTemplateParameterLocation(Decl: *Param);
5705
5706 return true;
5707
5708 case TemplateArgument::Type: {
5709 // We have a non-type template parameter but the template
5710 // argument is a type.
5711
5712 // C++ [temp.arg]p2:
5713 // In a template-argument, an ambiguity between a type-id and
5714 // an expression is resolved to a type-id, regardless of the
5715 // form of the corresponding template-parameter.
5716 //
5717 // We warn specifically about this case, since it can be rather
5718 // confusing for users.
5719 QualType T = Arg.getAsType();
5720 SourceRange SR = ArgLoc.getSourceRange();
5721 if (T->isFunctionType())
5722 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_nontype_ambig) << SR << T;
5723 else
5724 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_expr) << SR;
5725 NoteTemplateParameterLocation(Decl: *Param);
5726 return true;
5727 }
5728
5729 case TemplateArgument::Pack:
5730 llvm_unreachable("Caller must expand template argument packs");
5731 }
5732
5733 return false;
5734 }
5735
5736
5737 // Check template template parameters.
5738 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Val: Param);
5739
5740 TemplateParameterList *Params = TempParm->getTemplateParameters();
5741 if (TempParm->isExpandedParameterPack())
5742 Params = TempParm->getExpansionTemplateParameters(I: ArgumentPackIndex);
5743
5744 // Substitute into the template parameter list of the template
5745 // template parameter, since previously-supplied template arguments
5746 // may appear within the template template parameter.
5747 //
5748 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5749 {
5750 // Set up a template instantiation context.
5751 LocalInstantiationScope Scope(*this);
5752 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5753 CTAI.SugaredConverted,
5754 SourceRange(TemplateLoc, RAngleLoc));
5755 if (Inst.isInvalid())
5756 return true;
5757
5758 Params = SubstTemplateParams(
5759 Params, Owner: CurContext,
5760 TemplateArgs: MultiLevelTemplateArgumentList(Template, CTAI.SugaredConverted,
5761 /*Final=*/true),
5762 /*EvaluateConstraints=*/false);
5763 if (!Params)
5764 return true;
5765 }
5766
5767 // C++1z [temp.local]p1: (DR1004)
5768 // When [the injected-class-name] is used [...] as a template-argument for
5769 // a template template-parameter [...] it refers to the class template
5770 // itself.
5771 if (Arg.getKind() == TemplateArgument::Type) {
5772 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5773 Context, TLoc: ArgLoc.getTypeSourceInfo()->getTypeLoc());
5774 if (!ConvertedArg.getArgument().isNull())
5775 ArgLoc = ConvertedArg;
5776 }
5777
5778 switch (Arg.getKind()) {
5779 case TemplateArgument::Null:
5780 llvm_unreachable("Should never see a NULL template argument here");
5781
5782 case TemplateArgument::Template:
5783 case TemplateArgument::TemplateExpansion:
5784 if (CheckTemplateTemplateArgument(Param: TempParm, Params, Arg&: ArgLoc,
5785 PartialOrdering: CTAI.PartialOrdering,
5786 StrictPackMatch: &CTAI.StrictPackMatch))
5787 return true;
5788
5789 CTAI.SugaredConverted.push_back(Elt: Arg);
5790 CTAI.CanonicalConverted.push_back(
5791 Elt: Context.getCanonicalTemplateArgument(Arg));
5792 break;
5793
5794 case TemplateArgument::Expression:
5795 case TemplateArgument::Type: {
5796 auto Kind = 0;
5797 switch (TempParm->templateParameterKind()) {
5798 case TemplateNameKind::TNK_Var_template:
5799 Kind = 1;
5800 break;
5801 case TemplateNameKind::TNK_Concept_template:
5802 Kind = 2;
5803 break;
5804 default:
5805 break;
5806 }
5807
5808 // We have a template template parameter but the template
5809 // argument does not refer to a template.
5810 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_template)
5811 << Kind << getLangOpts().CPlusPlus11;
5812 return true;
5813 }
5814
5815 case TemplateArgument::Declaration:
5816 case TemplateArgument::Integral:
5817 case TemplateArgument::StructuralValue:
5818 case TemplateArgument::NullPtr:
5819 llvm_unreachable("non-type argument with template template parameter");
5820
5821 case TemplateArgument::Pack:
5822 llvm_unreachable("Caller must expand template argument packs");
5823 }
5824
5825 return false;
5826}
5827
5828/// Diagnose a missing template argument.
5829template<typename TemplateParmDecl>
5830static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5831 TemplateDecl *TD,
5832 const TemplateParmDecl *D,
5833 TemplateArgumentListInfo &Args) {
5834 // Dig out the most recent declaration of the template parameter; there may be
5835 // declarations of the template that are more recent than TD.
5836 D = cast<TemplateParmDecl>(cast<TemplateDecl>(Val: TD->getMostRecentDecl())
5837 ->getTemplateParameters()
5838 ->getParam(D->getIndex()));
5839
5840 // If there's a default argument that's not reachable, diagnose that we're
5841 // missing a module import.
5842 llvm::SmallVector<Module*, 8> Modules;
5843 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, Modules: &Modules)) {
5844 S.diagnoseMissingImport(Loc, cast<NamedDecl>(Val: TD),
5845 D->getDefaultArgumentLoc(), Modules,
5846 Sema::MissingImportKind::DefaultArgument,
5847 /*Recover*/true);
5848 return true;
5849 }
5850
5851 // FIXME: If there's a more recent default argument that *is* visible,
5852 // diagnose that it was declared too late.
5853
5854 TemplateParameterList *Params = TD->getTemplateParameters();
5855
5856 S.Diag(Loc, DiagID: diag::err_template_arg_list_different_arity)
5857 << /*not enough args*/0
5858 << (int)S.getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
5859 << TD;
5860 S.NoteTemplateLocation(Decl: *TD, ParamRange: Params->getSourceRange());
5861 return true;
5862}
5863
5864/// Check that the given template argument list is well-formed
5865/// for specializing the given template.
5866bool Sema::CheckTemplateArgumentList(
5867 TemplateDecl *Template, SourceLocation TemplateLoc,
5868 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5869 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5870 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5871 return CheckTemplateArgumentList(
5872 Template, Params: GetTemplateParameterList(TD: Template), TemplateLoc, TemplateArgs,
5873 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5874 ConstraintsNotSatisfied);
5875}
5876
5877/// Check that the given template argument list is well-formed
5878/// for specializing the given template.
5879bool Sema::CheckTemplateArgumentList(
5880 TemplateDecl *Template, TemplateParameterList *Params,
5881 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5882 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5883 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5884 bool *ConstraintsNotSatisfied) {
5885
5886 if (ConstraintsNotSatisfied)
5887 *ConstraintsNotSatisfied = false;
5888
5889 // Make a copy of the template arguments for processing. Only make the
5890 // changes at the end when successful in matching the arguments to the
5891 // template.
5892 TemplateArgumentListInfo NewArgs = TemplateArgs;
5893
5894 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5895
5896 // C++23 [temp.arg.general]p1:
5897 // [...] The type and form of each template-argument specified in
5898 // a template-id shall match the type and form specified for the
5899 // corresponding parameter declared by the template in its
5900 // template-parameter-list.
5901 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Val: Template);
5902 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5903 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5904 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5905 LocalInstantiationScope InstScope(*this, true);
5906 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5907 ParamEnd = Params->end(),
5908 Param = ParamBegin;
5909 Param != ParamEnd;
5910 /* increment in loop */) {
5911 if (size_t ParamIdx = Param - ParamBegin;
5912 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5913 // All written arguments should have been consumed by this point.
5914 assert(ArgIdx == NumArgs && "bad default argument deduction");
5915 if (ParamIdx == DefaultArgs.StartPos) {
5916 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5917 // Default arguments from a DeducedTemplateName are already converted.
5918 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5919 CTAI.SugaredConverted.push_back(Elt: DefArg);
5920 CTAI.CanonicalConverted.push_back(
5921 Elt: Context.getCanonicalTemplateArgument(Arg: DefArg));
5922 ++Param;
5923 }
5924 continue;
5925 }
5926 }
5927
5928 // If we have an expanded parameter pack, make sure we don't have too
5929 // many arguments.
5930 if (UnsignedOrNone Expansions = getExpandedPackSize(Param: *Param)) {
5931 if (*Expansions == SugaredArgumentPack.size()) {
5932 // We're done with this parameter pack. Pack up its arguments and add
5933 // them to the list.
5934 CTAI.SugaredConverted.push_back(
5935 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
5936 SugaredArgumentPack.clear();
5937
5938 CTAI.CanonicalConverted.push_back(
5939 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
5940 CanonicalArgumentPack.clear();
5941
5942 // This argument is assigned to the next parameter.
5943 ++Param;
5944 continue;
5945 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5946 // Not enough arguments for this parameter pack.
5947 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
5948 << /*not enough args*/0
5949 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
5950 << Template;
5951 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
5952 return true;
5953 }
5954 }
5955
5956 // Check for builtins producing template packs in this context, we do not
5957 // support them yet.
5958 if (const NonTypeTemplateParmDecl *NTTP =
5959 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param);
5960 NTTP && NTTP->isPackExpansion()) {
5961 auto TL = NTTP->getTypeSourceInfo()
5962 ->getTypeLoc()
5963 .castAs<PackExpansionTypeLoc>();
5964 llvm::SmallVector<UnexpandedParameterPack> Unexpanded;
5965 collectUnexpandedParameterPacks(TL: TL.getPatternLoc(), Unexpanded);
5966 for (const auto &UPP : Unexpanded) {
5967 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5968 if (!TST)
5969 continue;
5970 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5971 // Expanding a built-in pack in this context is not yet supported.
5972 Diag(Loc: TL.getEllipsisLoc(),
5973 DiagID: diag::err_unsupported_builtin_template_pack_expansion)
5974 << TST->getTemplateName();
5975 return true;
5976 }
5977 }
5978
5979 if (ArgIdx < NumArgs) {
5980 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5981 bool NonPackParameter =
5982 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(Param: *Param);
5983 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5984
5985 if (ArgIsExpansion && CTAI.MatchingTTP) {
5986 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5987 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5988 ++Param) {
5989 TemplateArgument &Arg = Args[Param - First];
5990 Arg = ArgLoc.getArgument();
5991 if (!(*Param)->isTemplateParameterPack() ||
5992 getExpandedPackSize(Param: *Param))
5993 Arg = Arg.getPackExpansionPattern();
5994 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5995 SaveAndRestore _1(CTAI.PartialOrdering, false);
5996 SaveAndRestore _2(CTAI.MatchingTTP, true);
5997 if (CheckTemplateArgument(Param: *Param, ArgLoc&: NewArgLoc, Template, TemplateLoc,
5998 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
5999 CTAK: CTAK_Specified))
6000 return true;
6001 Arg = NewArgLoc.getArgument();
6002 CTAI.CanonicalConverted.back().setIsDefaulted(
6003 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg, Param: *Param,
6004 Args: CTAI.CanonicalConverted,
6005 Depth: Params->getDepth()));
6006 }
6007 ArgLoc = TemplateArgumentLoc(
6008 TemplateArgument::CreatePackCopy(Context, Args),
6009 TemplateArgumentLocInfo(Context, ArgLoc.getLocation()));
6010 } else {
6011 SaveAndRestore _1(CTAI.PartialOrdering, false);
6012 if (CheckTemplateArgument(Param: *Param, ArgLoc, Template, TemplateLoc,
6013 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
6014 CTAK: CTAK_Specified))
6015 return true;
6016 CTAI.CanonicalConverted.back().setIsDefaulted(
6017 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg: ArgLoc.getArgument(),
6018 Param: *Param, Args: CTAI.CanonicalConverted,
6019 Depth: Params->getDepth()));
6020 if (ArgIsExpansion && NonPackParameter) {
6021 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6022 // alias template, builtin template, or concept, and it's not part of
6023 // a parameter pack. This can't be canonicalized, so reject it now.
6024 if (isa<TypeAliasTemplateDecl, ConceptDecl, BuiltinTemplateDecl>(
6025 Val: Template)) {
6026 unsigned DiagSelect = isa<ConceptDecl>(Val: Template) ? 1
6027 : isa<BuiltinTemplateDecl>(Val: Template) ? 2
6028 : 0;
6029 Diag(Loc: ArgLoc.getLocation(),
6030 DiagID: diag::err_template_expansion_into_fixed_list)
6031 << DiagSelect << ArgLoc.getSourceRange();
6032 NoteTemplateParameterLocation(Decl: **Param);
6033 return true;
6034 }
6035 }
6036 }
6037
6038 // We're now done with this argument.
6039 ++ArgIdx;
6040
6041 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6042 // Directly convert the remaining arguments, because we don't know what
6043 // parameters they'll match up with.
6044
6045 if (!SugaredArgumentPack.empty()) {
6046 // If we were part way through filling in an expanded parameter pack,
6047 // fall back to just producing individual arguments.
6048 CTAI.SugaredConverted.insert(I: CTAI.SugaredConverted.end(),
6049 From: SugaredArgumentPack.begin(),
6050 To: SugaredArgumentPack.end());
6051 SugaredArgumentPack.clear();
6052
6053 CTAI.CanonicalConverted.insert(I: CTAI.CanonicalConverted.end(),
6054 From: CanonicalArgumentPack.begin(),
6055 To: CanonicalArgumentPack.end());
6056 CanonicalArgumentPack.clear();
6057 }
6058
6059 while (ArgIdx < NumArgs) {
6060 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6061 CTAI.SugaredConverted.push_back(Elt: Arg);
6062 CTAI.CanonicalConverted.push_back(
6063 Elt: Context.getCanonicalTemplateArgument(Arg));
6064 ++ArgIdx;
6065 }
6066
6067 return false;
6068 }
6069
6070 if ((*Param)->isTemplateParameterPack()) {
6071 // The template parameter was a template parameter pack, so take the
6072 // deduced argument and place it on the argument pack. Note that we
6073 // stay on the same template parameter so that we can deduce more
6074 // arguments.
6075 SugaredArgumentPack.push_back(Elt: CTAI.SugaredConverted.pop_back_val());
6076 CanonicalArgumentPack.push_back(Elt: CTAI.CanonicalConverted.pop_back_val());
6077 } else {
6078 // Move to the next template parameter.
6079 ++Param;
6080 }
6081 continue;
6082 }
6083
6084 // If we're checking a partial template argument list, we're done.
6085 if (PartialTemplateArgs) {
6086 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6087 CTAI.SugaredConverted.push_back(
6088 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6089 CTAI.CanonicalConverted.push_back(
6090 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6091 }
6092 return false;
6093 }
6094
6095 // If we have a template parameter pack with no more corresponding
6096 // arguments, just break out now and we'll fill in the argument pack below.
6097 if ((*Param)->isTemplateParameterPack()) {
6098 assert(!getExpandedPackSize(*Param) &&
6099 "Should have dealt with this already");
6100
6101 // A non-expanded parameter pack before the end of the parameter list
6102 // only occurs for an ill-formed template parameter list, unless we've
6103 // got a partial argument list for a function template, so just bail out.
6104 if (Param + 1 != ParamEnd) {
6105 assert(
6106 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6107 "Concept templates must have parameter packs at the end.");
6108 return true;
6109 }
6110
6111 CTAI.SugaredConverted.push_back(
6112 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6113 SugaredArgumentPack.clear();
6114
6115 CTAI.CanonicalConverted.push_back(
6116 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6117 CanonicalArgumentPack.clear();
6118
6119 ++Param;
6120 continue;
6121 }
6122
6123 // Check whether we have a default argument.
6124 bool HasDefaultArg;
6125
6126 // Retrieve the default template argument from the template
6127 // parameter. For each kind of template parameter, we substitute the
6128 // template arguments provided thus far and any "outer" template arguments
6129 // (when the template parameter was part of a nested template) into
6130 // the default argument.
6131 TemplateArgumentLoc Arg = SubstDefaultTemplateArgumentIfAvailable(
6132 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateNameLoc: TemplateLoc, RAngleLoc,
6133 Param: *Param, SugaredConverted: CTAI.SugaredConverted, CanonicalConverted: CTAI.CanonicalConverted, HasDefaultArg);
6134
6135 if (Arg.getArgument().isNull()) {
6136 if (!HasDefaultArg) {
6137 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *Param))
6138 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: TTP,
6139 Args&: NewArgs);
6140 if (NonTypeTemplateParmDecl *NTTP =
6141 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param))
6142 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: NTTP,
6143 Args&: NewArgs);
6144 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template,
6145 D: cast<TemplateTemplateParmDecl>(Val: *Param),
6146 Args&: NewArgs);
6147 }
6148 return true;
6149 }
6150
6151 // Introduce an instantiation record that describes where we are using
6152 // the default template argument. We're not actually instantiating a
6153 // template here, we just create this object to put a note into the
6154 // context stack.
6155 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6156 CTAI.SugaredConverted,
6157 SourceRange(TemplateLoc, RAngleLoc));
6158 if (Inst.isInvalid())
6159 return true;
6160
6161 SaveAndRestore _1(CTAI.PartialOrdering, false);
6162 SaveAndRestore _2(CTAI.MatchingTTP, false);
6163 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6164 // Check the default template argument.
6165 if (CheckTemplateArgument(Param: *Param, ArgLoc&: Arg, Template, TemplateLoc, RAngleLoc, ArgumentPackIndex: 0,
6166 CTAI, CTAK: CTAK_Specified))
6167 return true;
6168
6169 CTAI.SugaredConverted.back().setIsDefaulted(true);
6170 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6171
6172 // Core issue 150 (assumed resolution): if this is a template template
6173 // parameter, keep track of the default template arguments from the
6174 // template definition.
6175 if (isTemplateTemplateParameter)
6176 NewArgs.addArgument(Loc: Arg);
6177
6178 // Move to the next template parameter and argument.
6179 ++Param;
6180 ++ArgIdx;
6181 }
6182
6183 // If we're performing a partial argument substitution, allow any trailing
6184 // pack expansions; they might be empty. This can happen even if
6185 // PartialTemplateArgs is false (the list of arguments is complete but
6186 // still dependent).
6187 if (CTAI.MatchingTTP ||
6188 (CurrentInstantiationScope &&
6189 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6190 while (ArgIdx < NumArgs &&
6191 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6192 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6193 CTAI.SugaredConverted.push_back(Elt: Arg);
6194 CTAI.CanonicalConverted.push_back(
6195 Elt: Context.getCanonicalTemplateArgument(Arg));
6196 }
6197 }
6198
6199 // If we have any leftover arguments, then there were too many arguments.
6200 // Complain and fail.
6201 if (ArgIdx < NumArgs) {
6202 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
6203 << /*too many args*/1
6204 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
6205 << Template
6206 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6207 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
6208 return true;
6209 }
6210
6211 // No problems found with the new argument list, propagate changes back
6212 // to caller.
6213 if (UpdateArgsWithConversions)
6214 TemplateArgs = std::move(NewArgs);
6215
6216 if (!PartialTemplateArgs) {
6217 // Setup the context/ThisScope for the case where we are needing to
6218 // re-instantiate constraints outside of normal instantiation.
6219 DeclContext *NewContext = Template->getDeclContext();
6220
6221 // If this template is in a template, make sure we extract the templated
6222 // decl.
6223 if (auto *TD = dyn_cast<TemplateDecl>(Val: NewContext))
6224 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6225 auto *RD = dyn_cast<CXXRecordDecl>(Val: NewContext);
6226
6227 Qualifiers ThisQuals;
6228 if (const auto *Method =
6229 dyn_cast_or_null<CXXMethodDecl>(Val: Template->getTemplatedDecl()))
6230 ThisQuals = Method->getMethodQualifiers();
6231
6232 ContextRAII Context(*this, NewContext);
6233 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6234
6235 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6236 D: Template, DC: NewContext, /*Final=*/true, Innermost: CTAI.SugaredConverted,
6237 /*RelativeToPrimary=*/true,
6238 /*Pattern=*/nullptr,
6239 /*ForConceptInstantiation=*/ForConstraintInstantiation: true);
6240 if (!isa<ConceptDecl>(Val: Template) &&
6241 EnsureTemplateArgumentListConstraints(
6242 Template, TemplateArgs: MLTAL,
6243 TemplateIDRange: SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6244 if (ConstraintsNotSatisfied)
6245 *ConstraintsNotSatisfied = true;
6246 return true;
6247 }
6248 }
6249
6250 return false;
6251}
6252
6253namespace {
6254 class UnnamedLocalNoLinkageFinder
6255 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6256 {
6257 Sema &S;
6258 SourceRange SR;
6259
6260 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6261
6262 public:
6263 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6264
6265 bool Visit(QualType T) {
6266 return T.isNull() ? false : inherited::Visit(T: T.getTypePtr());
6267 }
6268
6269#define TYPE(Class, Parent) \
6270 bool Visit##Class##Type(const Class##Type *);
6271#define ABSTRACT_TYPE(Class, Parent) \
6272 bool Visit##Class##Type(const Class##Type *) { return false; }
6273#define NON_CANONICAL_TYPE(Class, Parent) \
6274 bool Visit##Class##Type(const Class##Type *) { return false; }
6275#include "clang/AST/TypeNodes.inc"
6276
6277 bool VisitTagDecl(const TagDecl *Tag);
6278 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6279 };
6280} // end anonymous namespace
6281
6282bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6283 return false;
6284}
6285
6286bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6287 return Visit(T: T->getElementType());
6288}
6289
6290bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6291 return Visit(T: T->getPointeeType());
6292}
6293
6294bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6295 const BlockPointerType* T) {
6296 return Visit(T: T->getPointeeType());
6297}
6298
6299bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6300 const LValueReferenceType* T) {
6301 return Visit(T: T->getPointeeType());
6302}
6303
6304bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6305 const RValueReferenceType* T) {
6306 return Visit(T: T->getPointeeType());
6307}
6308
6309bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6310 const MemberPointerType *T) {
6311 if (Visit(T: T->getPointeeType()))
6312 return true;
6313 if (auto *RD = T->getMostRecentCXXRecordDecl())
6314 return VisitTagDecl(Tag: RD);
6315 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6316}
6317
6318bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6319 const ConstantArrayType* T) {
6320 return Visit(T: T->getElementType());
6321}
6322
6323bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6324 const IncompleteArrayType* T) {
6325 return Visit(T: T->getElementType());
6326}
6327
6328bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6329 const VariableArrayType* T) {
6330 return Visit(T: T->getElementType());
6331}
6332
6333bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6334 const DependentSizedArrayType* T) {
6335 return Visit(T: T->getElementType());
6336}
6337
6338bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6339 const DependentSizedExtVectorType* T) {
6340 return Visit(T: T->getElementType());
6341}
6342
6343bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6344 const DependentSizedMatrixType *T) {
6345 return Visit(T: T->getElementType());
6346}
6347
6348bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6349 const DependentAddressSpaceType *T) {
6350 return Visit(T: T->getPointeeType());
6351}
6352
6353bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6354 return Visit(T: T->getElementType());
6355}
6356
6357bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6358 const DependentVectorType *T) {
6359 return Visit(T: T->getElementType());
6360}
6361
6362bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6363 return Visit(T: T->getElementType());
6364}
6365
6366bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6367 const ConstantMatrixType *T) {
6368 return Visit(T: T->getElementType());
6369}
6370
6371bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6372 const FunctionProtoType* T) {
6373 for (const auto &A : T->param_types()) {
6374 if (Visit(T: A))
6375 return true;
6376 }
6377
6378 return Visit(T: T->getReturnType());
6379}
6380
6381bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6382 const FunctionNoProtoType* T) {
6383 return Visit(T: T->getReturnType());
6384}
6385
6386bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6387 const UnresolvedUsingType*) {
6388 return false;
6389}
6390
6391bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6392 return false;
6393}
6394
6395bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6396 return Visit(T: T->getUnmodifiedType());
6397}
6398
6399bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6400 return false;
6401}
6402
6403bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6404 const PackIndexingType *) {
6405 return false;
6406}
6407
6408bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6409 const UnaryTransformType*) {
6410 return false;
6411}
6412
6413bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6414 return Visit(T: T->getDeducedType());
6415}
6416
6417bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6418 const DeducedTemplateSpecializationType *T) {
6419 return Visit(T: T->getDeducedType());
6420}
6421
6422bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6423 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6424}
6425
6426bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6427 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6428}
6429
6430bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6431 const TemplateTypeParmType*) {
6432 return false;
6433}
6434
6435bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6436 const SubstTemplateTypeParmPackType *) {
6437 return false;
6438}
6439
6440bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6441 const SubstBuiltinTemplatePackType *) {
6442 return false;
6443}
6444
6445bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6446 const TemplateSpecializationType*) {
6447 return false;
6448}
6449
6450bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6451 const InjectedClassNameType* T) {
6452 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6453}
6454
6455bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6456 const DependentNameType* T) {
6457 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6458}
6459
6460bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6461 const PackExpansionType* T) {
6462 return Visit(T: T->getPattern());
6463}
6464
6465bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6466 return false;
6467}
6468
6469bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6470 const ObjCInterfaceType *) {
6471 return false;
6472}
6473
6474bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6475 const ObjCObjectPointerType *) {
6476 return false;
6477}
6478
6479bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6480 return Visit(T: T->getValueType());
6481}
6482
6483bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6484 const OverflowBehaviorType *T) {
6485 return Visit(T: T->getUnderlyingType());
6486}
6487
6488bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6489 return false;
6490}
6491
6492bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6493 return false;
6494}
6495
6496bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6497 const ArrayParameterType *T) {
6498 return VisitConstantArrayType(T);
6499}
6500
6501bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6502 const DependentBitIntType *T) {
6503 return false;
6504}
6505
6506bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6507 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6508 S.Diag(Loc: SR.getBegin(), DiagID: S.getLangOpts().CPlusPlus11
6509 ? diag::warn_cxx98_compat_template_arg_local_type
6510 : diag::ext_template_arg_local_type)
6511 << S.Context.getCanonicalTagType(TD: Tag) << SR;
6512 return true;
6513 }
6514
6515 if (!Tag->hasNameForLinkage()) {
6516 S.Diag(Loc: SR.getBegin(),
6517 DiagID: S.getLangOpts().CPlusPlus11 ?
6518 diag::warn_cxx98_compat_template_arg_unnamed_type :
6519 diag::ext_template_arg_unnamed_type) << SR;
6520 S.Diag(Loc: Tag->getLocation(), DiagID: diag::note_template_unnamed_type_here);
6521 return true;
6522 }
6523
6524 return false;
6525}
6526
6527bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6528 NestedNameSpecifier NNS) {
6529 switch (NNS.getKind()) {
6530 case NestedNameSpecifier::Kind::Null:
6531 case NestedNameSpecifier::Kind::Namespace:
6532 case NestedNameSpecifier::Kind::Global:
6533 case NestedNameSpecifier::Kind::MicrosoftSuper:
6534 return false;
6535 case NestedNameSpecifier::Kind::Type:
6536 return Visit(T: QualType(NNS.getAsType(), 0));
6537 }
6538 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6539}
6540
6541bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6542 const HLSLAttributedResourceType *T) {
6543 if (T->hasContainedType() && Visit(T: T->getContainedType()))
6544 return true;
6545 return Visit(T: T->getWrappedType());
6546}
6547
6548bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6549 const HLSLInlineSpirvType *T) {
6550 for (auto &Operand : T->getOperands())
6551 if (Operand.isConstant() && Operand.isLiteral())
6552 if (Visit(T: Operand.getResultType()))
6553 return true;
6554 return false;
6555}
6556
6557bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6558 assert(ArgInfo && "invalid TypeSourceInfo");
6559 QualType Arg = ArgInfo->getType();
6560 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6561 QualType CanonArg = Context.getCanonicalType(T: Arg);
6562
6563 if (CanonArg->isVariablyModifiedType()) {
6564 return Diag(Loc: SR.getBegin(), DiagID: diag::err_variably_modified_template_arg) << Arg;
6565 } else if (Context.hasSameUnqualifiedType(T1: Arg, T2: Context.OverloadTy)) {
6566 return Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_overload_type) << SR;
6567 }
6568
6569 // C++03 [temp.arg.type]p2:
6570 // A local type, a type with no linkage, an unnamed type or a type
6571 // compounded from any of these types shall not be used as a
6572 // template-argument for a template type-parameter.
6573 //
6574 // C++11 allows these, and even in C++03 we allow them as an extension with
6575 // a warning.
6576 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6577 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6578 (void)Finder.Visit(T: CanonArg);
6579 }
6580
6581 return false;
6582}
6583
6584enum NullPointerValueKind {
6585 NPV_NotNullPointer,
6586 NPV_NullPointer,
6587 NPV_Error
6588};
6589
6590/// Determine whether the given template argument is a null pointer
6591/// value of the appropriate type.
6592static NullPointerValueKind
6593isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param,
6594 QualType ParamType, Expr *Arg,
6595 Decl *Entity = nullptr) {
6596 if (Arg->isValueDependent() || Arg->isTypeDependent())
6597 return NPV_NotNullPointer;
6598
6599 // dllimport'd entities aren't constant but are available inside of template
6600 // arguments.
6601 if (Entity && Entity->hasAttr<DLLImportAttr>())
6602 return NPV_NotNullPointer;
6603
6604 if (!S.isCompleteType(Loc: Arg->getExprLoc(), T: ParamType))
6605 llvm_unreachable(
6606 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6607
6608 if (!S.getLangOpts().CPlusPlus11)
6609 return NPV_NotNullPointer;
6610
6611 // Determine whether we have a constant expression.
6612 ExprResult ArgRV = S.DefaultFunctionArrayConversion(E: Arg);
6613 if (ArgRV.isInvalid())
6614 return NPV_Error;
6615 Arg = ArgRV.get();
6616
6617 Expr::EvalResult EvalResult;
6618 SmallVector<PartialDiagnosticAt, 8> Notes;
6619 EvalResult.Diag = &Notes;
6620 if (!Arg->EvaluateAsRValue(Result&: EvalResult, Ctx: S.Context) ||
6621 EvalResult.HasSideEffects) {
6622 SourceLocation DiagLoc = Arg->getExprLoc();
6623
6624 // If our only note is the usual "invalid subexpression" note, just point
6625 // the caret at its location rather than producing an essentially
6626 // redundant note.
6627 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6628 diag::note_invalid_subexpr_in_const_expr) {
6629 DiagLoc = Notes[0].first;
6630 Notes.clear();
6631 }
6632
6633 S.Diag(Loc: DiagLoc, DiagID: diag::err_template_arg_not_address_constant)
6634 << Arg->getType() << Arg->getSourceRange();
6635 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6636 S.Diag(Loc: Notes[I].first, PD: Notes[I].second);
6637
6638 S.NoteTemplateParameterLocation(Decl: *Param);
6639 return NPV_Error;
6640 }
6641
6642 // C++11 [temp.arg.nontype]p1:
6643 // - an address constant expression of type std::nullptr_t
6644 if (Arg->getType()->isNullPtrType())
6645 return NPV_NullPointer;
6646
6647 // - a constant expression that evaluates to a null pointer value (4.10); or
6648 // - a constant expression that evaluates to a null member pointer value
6649 // (4.11); or
6650 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6651 (EvalResult.Val.isMemberPointer() &&
6652 !EvalResult.Val.getMemberPointerDecl())) {
6653 // If our expression has an appropriate type, we've succeeded.
6654 bool ObjCLifetimeConversion;
6655 if (S.Context.hasSameUnqualifiedType(T1: Arg->getType(), T2: ParamType) ||
6656 S.IsQualificationConversion(FromType: Arg->getType(), ToType: ParamType, CStyle: false,
6657 ObjCLifetimeConversion))
6658 return NPV_NullPointer;
6659
6660 // The types didn't match, but we know we got a null pointer; complain,
6661 // then recover as if the types were correct.
6662 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_wrongtype_null_constant)
6663 << Arg->getType() << ParamType << Arg->getSourceRange();
6664 S.NoteTemplateParameterLocation(Decl: *Param);
6665 return NPV_NullPointer;
6666 }
6667
6668 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6669 // We found a pointer that isn't null, but doesn't refer to an object.
6670 // We could just return NPV_NotNullPointer, but we can print a better
6671 // message with the information we have here.
6672 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_invalid)
6673 << EvalResult.Val.getAsString(Ctx: S.Context, Ty: ParamType);
6674 S.NoteTemplateParameterLocation(Decl: *Param);
6675 return NPV_Error;
6676 }
6677
6678 // If we don't have a null pointer value, but we do have a NULL pointer
6679 // constant, suggest a cast to the appropriate type.
6680 if (Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_NeverValueDependent)) {
6681 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6682 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_untyped_null_constant)
6683 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code)
6684 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: Arg->getEndLoc()),
6685 Code: ")");
6686 S.NoteTemplateParameterLocation(Decl: *Param);
6687 return NPV_NullPointer;
6688 }
6689
6690 // FIXME: If we ever want to support general, address-constant expressions
6691 // as non-type template arguments, we should return the ExprResult here to
6692 // be interpreted by the caller.
6693 return NPV_NotNullPointer;
6694}
6695
6696/// Checks whether the given template argument is compatible with its
6697/// template parameter.
6698static bool
6699CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param,
6700 QualType ParamType, Expr *ArgIn,
6701 Expr *Arg, QualType ArgType) {
6702 bool ObjCLifetimeConversion;
6703 if (ParamType->isPointerType() &&
6704 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6705 S.IsQualificationConversion(FromType: ArgType, ToType: ParamType, CStyle: false,
6706 ObjCLifetimeConversion)) {
6707 // For pointer-to-object types, qualification conversions are
6708 // permitted.
6709 } else {
6710 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6711 if (!ParamRef->getPointeeType()->isFunctionType()) {
6712 // C++ [temp.arg.nontype]p5b3:
6713 // For a non-type template-parameter of type reference to
6714 // object, no conversions apply. The type referred to by the
6715 // reference may be more cv-qualified than the (otherwise
6716 // identical) type of the template- argument. The
6717 // template-parameter is bound directly to the
6718 // template-argument, which shall be an lvalue.
6719
6720 // FIXME: Other qualifiers?
6721 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6722 unsigned ArgQuals = ArgType.getCVRQualifiers();
6723
6724 if ((ParamQuals | ArgQuals) != ParamQuals) {
6725 S.Diag(Loc: Arg->getBeginLoc(),
6726 DiagID: diag::err_template_arg_ref_bind_ignores_quals)
6727 << ParamType << Arg->getType() << Arg->getSourceRange();
6728 S.NoteTemplateParameterLocation(Decl: *Param);
6729 return true;
6730 }
6731 }
6732 }
6733
6734 // At this point, the template argument refers to an object or
6735 // function with external linkage. We now need to check whether the
6736 // argument and parameter types are compatible.
6737 if (!S.Context.hasSameUnqualifiedType(T1: ArgType,
6738 T2: ParamType.getNonReferenceType())) {
6739 // We can't perform this conversion or binding.
6740 if (ParamType->isReferenceType())
6741 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_no_ref_bind)
6742 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6743 else
6744 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
6745 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6746 S.NoteTemplateParameterLocation(Decl: *Param);
6747 return true;
6748 }
6749 }
6750
6751 return false;
6752}
6753
6754/// Checks whether the given template argument is the address
6755/// of an object or function according to C++ [temp.arg.nontype]p1.
6756static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6757 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6758 bool IsSpecified, TemplateArgument &SugaredConverted,
6759 TemplateArgument &CanonicalConverted) {
6760 Expr *Arg = ArgIn;
6761 QualType ArgType = Arg->getType();
6762
6763 bool AddressTaken = false;
6764 SourceLocation AddrOpLoc;
6765 if (S.getLangOpts().MicrosoftExt) {
6766 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6767 // dereference and address-of operators.
6768 Arg = Arg->IgnoreParenCasts();
6769
6770 bool ExtWarnMSTemplateArg = false;
6771 UnaryOperatorKind FirstOpKind;
6772 SourceLocation FirstOpLoc;
6773 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6774 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6775 if (UnOpKind == UO_Deref)
6776 ExtWarnMSTemplateArg = true;
6777 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6778 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6779 if (!AddrOpLoc.isValid()) {
6780 FirstOpKind = UnOpKind;
6781 FirstOpLoc = UnOp->getOperatorLoc();
6782 }
6783 } else
6784 break;
6785 }
6786 if (FirstOpLoc.isValid()) {
6787 if (ExtWarnMSTemplateArg)
6788 S.Diag(Loc: ArgIn->getBeginLoc(), DiagID: diag::ext_ms_deref_template_argument)
6789 << ArgIn->getSourceRange();
6790
6791 if (FirstOpKind == UO_AddrOf)
6792 AddressTaken = true;
6793 else if (Arg->getType()->isPointerType()) {
6794 // We cannot let pointers get dereferenced here, that is obviously not a
6795 // constant expression.
6796 assert(FirstOpKind == UO_Deref);
6797 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6798 << Arg->getSourceRange();
6799 }
6800 }
6801 } else {
6802 // See through any implicit casts we added to fix the type.
6803 // Also ignore parentheses for deduced template arguments.
6804 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6805
6806 // C++ [temp.arg.nontype]p1:
6807 //
6808 // A template-argument for a non-type, non-template
6809 // template-parameter shall be one of: [...]
6810 //
6811 // -- the address of an object or function with external
6812 // linkage, including function templates and function
6813 // template-ids but excluding non-static class members,
6814 // expressed as & id-expression where the & is optional if
6815 // the name refers to a function or array, or if the
6816 // corresponding template-parameter is a reference; or
6817
6818 // In C++98/03 mode, give an extension warning on any extra parentheses.
6819 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6820 if (IsSpecified) {
6821 bool ExtraParens = false;
6822 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6823 if (!ExtraParens) {
6824 S.DiagCompat(Loc: Arg->getBeginLoc(),
6825 CompatDiagId: diag_compat::template_arg_extra_parens)
6826 << Arg->getSourceRange();
6827 ExtraParens = true;
6828 }
6829
6830 Arg = Parens->getSubExpr();
6831 }
6832 }
6833
6834 while (SubstNonTypeTemplateParmExpr *subst =
6835 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6836 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6837
6838 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6839 if (UnOp->getOpcode() == UO_AddrOf) {
6840 Arg = UnOp->getSubExpr();
6841 AddressTaken = true;
6842 AddrOpLoc = UnOp->getOperatorLoc();
6843 }
6844 }
6845
6846 while (SubstNonTypeTemplateParmExpr *subst =
6847 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6848 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6849 }
6850
6851 ValueDecl *Entity = nullptr;
6852 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg))
6853 Entity = DRE->getDecl();
6854 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Val: Arg))
6855 Entity = CUE->getGuidDecl();
6856
6857 // If our parameter has pointer type, check for a null template value.
6858 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6859 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ArgIn,
6860 Entity)) {
6861 case NPV_NullPointer:
6862 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
6863 SugaredConverted = TemplateArgument(ParamType,
6864 /*isNullPtr=*/true);
6865 CanonicalConverted =
6866 TemplateArgument(S.Context.getCanonicalType(T: ParamType),
6867 /*isNullPtr=*/true);
6868 return false;
6869
6870 case NPV_Error:
6871 return true;
6872
6873 case NPV_NotNullPointer:
6874 break;
6875 }
6876 }
6877
6878 // Stop checking the precise nature of the argument if it is value dependent,
6879 // it should be checked when instantiated.
6880 if (Arg->isValueDependent()) {
6881 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6882 CanonicalConverted =
6883 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6884 return false;
6885 }
6886
6887 if (!Entity) {
6888 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6889 << Arg->getSourceRange();
6890 S.NoteTemplateParameterLocation(Decl: *Param);
6891 return true;
6892 }
6893
6894 // Cannot refer to non-static data members
6895 if (isa<FieldDecl>(Val: Entity) || isa<IndirectFieldDecl>(Val: Entity)) {
6896 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_field)
6897 << Entity << Arg->getSourceRange();
6898 S.NoteTemplateParameterLocation(Decl: *Param);
6899 return true;
6900 }
6901
6902 // Cannot refer to non-static member functions
6903 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Entity)) {
6904 if (!Method->isStatic()) {
6905 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_method)
6906 << Method << Arg->getSourceRange();
6907 S.NoteTemplateParameterLocation(Decl: *Param);
6908 return true;
6909 }
6910 }
6911
6912 FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Entity);
6913 VarDecl *Var = dyn_cast<VarDecl>(Val: Entity);
6914 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Val: Entity);
6915
6916 // A non-type template argument must refer to an object or function.
6917 if (!Func && !Var && !Guid) {
6918 // We found something, but we don't know specifically what it is.
6919 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_object_or_func)
6920 << Arg->getSourceRange();
6921 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_refers_here);
6922 return true;
6923 }
6924
6925 // Address / reference template args must have external linkage in C++98.
6926 if (Entity->getFormalLinkage() == Linkage::Internal) {
6927 S.Diag(Loc: Arg->getBeginLoc(),
6928 DiagID: S.getLangOpts().CPlusPlus11
6929 ? diag::warn_cxx98_compat_template_arg_object_internal
6930 : diag::ext_template_arg_object_internal)
6931 << !Func << Entity << Arg->getSourceRange();
6932 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6933 << !Func;
6934 } else if (!Entity->hasLinkage()) {
6935 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_object_no_linkage)
6936 << !Func << Entity << Arg->getSourceRange();
6937 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6938 << !Func;
6939 return true;
6940 }
6941
6942 if (Var) {
6943 // A value of reference type is not an object.
6944 if (Var->getType()->isReferenceType()) {
6945 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_reference_var)
6946 << Var->getType() << Arg->getSourceRange();
6947 S.NoteTemplateParameterLocation(Decl: *Param);
6948 return true;
6949 }
6950
6951 // A template argument must have static storage duration.
6952 if (Var->getTLSKind()) {
6953 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_thread_local)
6954 << Arg->getSourceRange();
6955 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_template_arg_refers_here);
6956 return true;
6957 }
6958 }
6959
6960 if (AddressTaken && ParamType->isReferenceType()) {
6961 // If we originally had an address-of operator, but the
6962 // parameter has reference type, complain and (if things look
6963 // like they will work) drop the address-of operator.
6964 if (!S.Context.hasSameUnqualifiedType(T1: Entity->getType(),
6965 T2: ParamType.getNonReferenceType())) {
6966 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6967 << ParamType;
6968 S.NoteTemplateParameterLocation(Decl: *Param);
6969 return true;
6970 }
6971
6972 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6973 << ParamType
6974 << FixItHint::CreateRemoval(RemoveRange: AddrOpLoc);
6975 S.NoteTemplateParameterLocation(Decl: *Param);
6976
6977 ArgType = Entity->getType();
6978 }
6979
6980 // If the template parameter has pointer type, either we must have taken the
6981 // address or the argument must decay to a pointer.
6982 if (!AddressTaken && ParamType->isPointerType()) {
6983 if (Func) {
6984 // Function-to-pointer decay.
6985 ArgType = S.Context.getPointerType(T: Func->getType());
6986 } else if (Entity->getType()->isArrayType()) {
6987 // Array-to-pointer decay.
6988 ArgType = S.Context.getArrayDecayedType(T: Entity->getType());
6989 } else {
6990 // If the template parameter has pointer type but the address of
6991 // this object was not taken, complain and (possibly) recover by
6992 // taking the address of the entity.
6993 ArgType = S.Context.getPointerType(T: Entity->getType());
6994 if (!S.Context.hasSameUnqualifiedType(T1: ArgType, T2: ParamType)) {
6995 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6996 << ParamType;
6997 S.NoteTemplateParameterLocation(Decl: *Param);
6998 return true;
6999 }
7000
7001 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
7002 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code: "&");
7003
7004 S.NoteTemplateParameterLocation(Decl: *Param);
7005 }
7006 }
7007
7008 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7009 Arg, ArgType))
7010 return true;
7011
7012 // Create the template argument.
7013 SugaredConverted = TemplateArgument(Entity, ParamType);
7014 CanonicalConverted =
7015 TemplateArgument(cast<ValueDecl>(Val: Entity->getCanonicalDecl()),
7016 S.Context.getCanonicalType(T: ParamType));
7017 S.MarkAnyDeclReferenced(Loc: Arg->getBeginLoc(), D: Entity, MightBeOdrUse: false);
7018 return false;
7019}
7020
7021/// Checks whether the given template argument is a pointer to
7022/// member constant according to C++ [temp.arg.nontype]p1.
7023static bool CheckTemplateArgumentPointerToMember(
7024 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7025 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7026 bool Invalid = false;
7027
7028 Expr *Arg = ResultArg;
7029 bool ObjCLifetimeConversion;
7030
7031 // C++ [temp.arg.nontype]p1:
7032 //
7033 // A template-argument for a non-type, non-template
7034 // template-parameter shall be one of: [...]
7035 //
7036 // -- a pointer to member expressed as described in 5.3.1.
7037 DeclRefExpr *DRE = nullptr;
7038
7039 // In C++98/03 mode, give an extension warning on any extra parentheses.
7040 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7041 bool ExtraParens = false;
7042 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
7043 if (!Invalid && !ExtraParens) {
7044 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
7045 << Arg->getSourceRange();
7046 ExtraParens = true;
7047 }
7048
7049 Arg = Parens->getSubExpr();
7050 }
7051
7052 while (SubstNonTypeTemplateParmExpr *subst =
7053 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
7054 Arg = subst->getReplacement()->IgnoreImpCasts();
7055
7056 // A pointer-to-member constant written &Class::member.
7057 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
7058 if (UnOp->getOpcode() == UO_AddrOf) {
7059 DRE = dyn_cast<DeclRefExpr>(Val: UnOp->getSubExpr());
7060 if (DRE && !DRE->getQualifier())
7061 DRE = nullptr;
7062 }
7063 }
7064 // A constant of pointer-to-member type.
7065 else if ((DRE = dyn_cast<DeclRefExpr>(Val: Arg))) {
7066 ValueDecl *VD = DRE->getDecl();
7067 if (VD->getType()->isMemberPointerType()) {
7068 if (isa<NonTypeTemplateParmDecl>(Val: VD)) {
7069 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7070 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7071 CanonicalConverted =
7072 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7073 } else {
7074 SugaredConverted = TemplateArgument(VD, ParamType);
7075 CanonicalConverted =
7076 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7077 S.Context.getCanonicalType(T: ParamType));
7078 }
7079 return Invalid;
7080 }
7081 }
7082
7083 DRE = nullptr;
7084 }
7085
7086 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7087
7088 // Check for a null pointer value.
7089 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ResultArg,
7090 Entity)) {
7091 case NPV_Error:
7092 return true;
7093 case NPV_NullPointer:
7094 S.Diag(Loc: ResultArg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7095 SugaredConverted = TemplateArgument(ParamType,
7096 /*isNullPtr*/ true);
7097 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(T: ParamType),
7098 /*isNullPtr*/ true);
7099 return false;
7100 case NPV_NotNullPointer:
7101 break;
7102 }
7103
7104 if (S.IsQualificationConversion(FromType: ResultArg->getType(),
7105 ToType: ParamType.getNonReferenceType(), CStyle: false,
7106 ObjCLifetimeConversion)) {
7107 ResultArg = S.ImpCastExprToType(E: ResultArg, Type: ParamType, CK: CK_NoOp,
7108 VK: ResultArg->getValueKind())
7109 .get();
7110 } else if (!S.Context.hasSameUnqualifiedType(
7111 T1: ResultArg->getType(), T2: ParamType.getNonReferenceType())) {
7112 // We can't perform this conversion.
7113 S.Diag(Loc: ResultArg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
7114 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7115 S.NoteTemplateParameterLocation(Decl: *Param);
7116 return true;
7117 }
7118
7119 if (!DRE)
7120 return S.Diag(Loc: Arg->getBeginLoc(),
7121 DiagID: diag::err_template_arg_not_pointer_to_member_form)
7122 << Arg->getSourceRange();
7123
7124 if (isa<FieldDecl>(Val: DRE->getDecl()) ||
7125 isa<IndirectFieldDecl>(Val: DRE->getDecl()) ||
7126 isa<CXXMethodDecl>(Val: DRE->getDecl())) {
7127 assert((isa<FieldDecl>(DRE->getDecl()) ||
7128 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7129 cast<CXXMethodDecl>(DRE->getDecl())
7130 ->isImplicitObjectMemberFunction()) &&
7131 "Only non-static member pointers can make it here");
7132
7133 // Okay: this is the address of a non-static member, and therefore
7134 // a member pointer constant.
7135 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7136 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7137 CanonicalConverted =
7138 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7139 } else {
7140 ValueDecl *D = DRE->getDecl();
7141 SugaredConverted = TemplateArgument(D, ParamType);
7142 CanonicalConverted =
7143 TemplateArgument(cast<ValueDecl>(Val: D->getCanonicalDecl()),
7144 S.Context.getCanonicalType(T: ParamType));
7145 }
7146 return Invalid;
7147 }
7148
7149 // We found something else, but we don't know specifically what it is.
7150 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_pointer_to_member_form)
7151 << Arg->getSourceRange();
7152 S.Diag(Loc: DRE->getDecl()->getLocation(), DiagID: diag::note_template_arg_refers_here);
7153 return true;
7154}
7155
7156/// Check a template argument against its corresponding
7157/// non-type template parameter.
7158///
7159/// This routine implements the semantics of C++ [temp.arg.nontype].
7160/// If an error occurred, it returns ExprError(); otherwise, it
7161/// returns the converted template argument. \p ParamType is the
7162/// type of the non-type template parameter after it has been instantiated.
7163ExprResult Sema::CheckTemplateArgument(NamedDecl *Param, QualType ParamType,
7164 Expr *Arg,
7165 TemplateArgument &SugaredConverted,
7166 TemplateArgument &CanonicalConverted,
7167 bool StrictCheck,
7168 CheckTemplateArgumentKind CTAK) {
7169 SourceLocation StartLoc = Arg->getBeginLoc();
7170 auto *ArgPE = dyn_cast<PackExpansionExpr>(Val: Arg);
7171 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7172 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7173 DeductionArg = NewDeductionArg;
7174 if (ArgPE) {
7175 // Recreate a pack expansion if we unwrapped one.
7176 Arg = new (Context) PackExpansionExpr(
7177 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7178 } else {
7179 Arg = DeductionArg;
7180 }
7181 };
7182
7183 // If the parameter type somehow involves auto, deduce the type now.
7184 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7185 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7186 if (IsDeduced) {
7187 // When checking a deduced template argument, deduce from its type even if
7188 // the type is dependent, in order to check the types of non-type template
7189 // arguments line up properly in partial ordering.
7190 TypeSourceInfo *TSI =
7191 Context.getTrivialTypeSourceInfo(T: ParamType, Loc: Param->getLocation());
7192 if (isa<DeducedTemplateSpecializationType>(Val: DeducedT)) {
7193 InitializedEntity Entity =
7194 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7195 InitializationKind Kind = InitializationKind::CreateForInit(
7196 Loc: DeductionArg->getBeginLoc(), /*DirectInit*/false, Init: DeductionArg);
7197 Expr *Inits[1] = {DeductionArg};
7198 ParamType =
7199 DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind, Init: Inits);
7200 if (ParamType.isNull())
7201 return ExprError();
7202 } else {
7203 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7204 Param->getTemplateDepth() + 1);
7205 ParamType = QualType();
7206 TemplateDeductionResult Result =
7207 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeductionArg, Result&: ParamType, Info,
7208 /*DependentDeduction=*/true,
7209 // We do not check constraints right now because the
7210 // immediately-declared constraint of the auto type is
7211 // also an associated constraint, and will be checked
7212 // along with the other associated constraints after
7213 // checking the template argument list.
7214 /*IgnoreConstraints=*/true);
7215 if (Result != TemplateDeductionResult::Success) {
7216 ParamType = TSI->getType();
7217 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7218 if (Result == TemplateDeductionResult::AlreadyDiagnosed)
7219 return ExprError();
7220 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param))
7221 Diag(Loc: Arg->getExprLoc(),
7222 DiagID: diag::err_non_type_template_parm_type_deduction_failure)
7223 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7224 << Arg->getSourceRange();
7225 NoteTemplateParameterLocation(Decl: *Param);
7226 return ExprError();
7227 }
7228 ParamType = SubstAutoTypeDependent(TypeWithAuto: ParamType);
7229 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7230 }
7231 }
7232 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7233 // an error. The error message normally references the parameter
7234 // declaration, but here we'll pass the argument location because that's
7235 // where the parameter type is deduced.
7236 ParamType = CheckNonTypeTemplateParameterType(T: ParamType, Loc: Arg->getExprLoc());
7237 if (ParamType.isNull()) {
7238 NoteTemplateParameterLocation(Decl: *Param);
7239 return ExprError();
7240 }
7241 }
7242
7243 // We should have already dropped all cv-qualifiers by now.
7244 assert(!ParamType.hasQualifiers() &&
7245 "non-type template parameter type cannot be qualified");
7246
7247 // If either the parameter has a dependent type or the argument is
7248 // type-dependent, there's nothing we can check now.
7249 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7250 // Force the argument to the type of the parameter to maintain invariants.
7251 if (!IsDeduced) {
7252 ExprResult E = ImpCastExprToType(
7253 E: DeductionArg, Type: ParamType.getNonLValueExprType(Context), CK: CK_Dependent,
7254 VK: ParamType->isLValueReferenceType() ? VK_LValue
7255 : ParamType->isRValueReferenceType() ? VK_XValue
7256 : VK_PRValue);
7257 if (E.isInvalid())
7258 return ExprError();
7259 setDeductionArg(E.get());
7260 }
7261 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7262 CanonicalConverted = TemplateArgument(
7263 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7264 return Arg;
7265 }
7266
7267 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7268 if (CTAK == CTAK_Deduced && !StrictCheck &&
7269 (ParamType->isReferenceType()
7270 ? !Context.hasSameType(T1: ParamType.getNonReferenceType(),
7271 T2: DeductionArg->getType())
7272 : !Context.hasSameUnqualifiedType(T1: ParamType,
7273 T2: DeductionArg->getType()))) {
7274 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7275 // we should actually be checking the type of the template argument in P,
7276 // not the type of the template argument deduced from A, against the
7277 // template parameter type.
7278 Diag(Loc: StartLoc, DiagID: diag::err_deduced_non_type_template_arg_type_mismatch)
7279 << Arg->getType() << ParamType.getUnqualifiedType();
7280 NoteTemplateParameterLocation(Decl: *Param);
7281 return ExprError();
7282 }
7283
7284 // If the argument is a pack expansion, we don't know how many times it would
7285 // expand. If we continue checking the argument, this will make the template
7286 // definition ill-formed if it would be ill-formed for any number of
7287 // expansions during instantiation time. When partial ordering or matching
7288 // template template parameters, this is exactly what we want. Otherwise, the
7289 // normal template rules apply: we accept the template if it would be valid
7290 // for any number of expansions (i.e. none).
7291 if (ArgPE && !StrictCheck) {
7292 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7293 CanonicalConverted = TemplateArgument(
7294 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7295 return Arg;
7296 }
7297
7298 // Avoid making a copy when initializing a template parameter of class type
7299 // from a template parameter object of the same type. This is going beyond
7300 // the standard, but is required for soundness: in
7301 // template<A a> struct X { X *p; X<a> *q; };
7302 // ... we need p and q to have the same type.
7303 //
7304 // Similarly, don't inject a call to a copy constructor when initializing
7305 // from a template parameter of the same type.
7306 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7307 if (ParamType->isRecordType() && isa<DeclRefExpr>(Val: InnerArg) &&
7308 Context.hasSameUnqualifiedType(T1: ParamType, T2: InnerArg->getType())) {
7309 NamedDecl *ND = cast<DeclRefExpr>(Val: InnerArg)->getDecl();
7310 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: ND)) {
7311
7312 SugaredConverted = TemplateArgument(TPO, ParamType);
7313 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7314 ParamType.getCanonicalType());
7315 return Arg;
7316 }
7317 if (isa<NonTypeTemplateParmDecl>(Val: ND)) {
7318 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7319 CanonicalConverted =
7320 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7321 return Arg;
7322 }
7323 }
7324
7325 // The initialization of the parameter from the argument is
7326 // a constant-evaluated context.
7327 EnterExpressionEvaluationContext ConstantEvaluated(
7328 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7329
7330 bool IsConvertedConstantExpression = true;
7331 if (isa<InitListExpr>(Val: DeductionArg) || ParamType->isRecordType()) {
7332 InitializationKind Kind = InitializationKind::CreateForInit(
7333 Loc: StartLoc, /*DirectInit=*/false, Init: DeductionArg);
7334 Expr *Inits[1] = {DeductionArg};
7335 InitializedEntity Entity =
7336 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7337 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7338 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Inits);
7339 if (Result.isInvalid() || !Result.get())
7340 return ExprError();
7341 Result = ActOnConstantExpression(Res: Result.get());
7342 if (Result.isInvalid() || !Result.get())
7343 return ExprError();
7344 setDeductionArg(ActOnFinishFullExpr(Expr: Result.get(), CC: Arg->getBeginLoc(),
7345 /*DiscardedValue=*/false,
7346 /*IsConstexpr=*/true,
7347 /*IsTemplateArgument=*/true)
7348 .get());
7349 IsConvertedConstantExpression = false;
7350 }
7351
7352 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7353 // C++17 [temp.arg.nontype]p1:
7354 // A template-argument for a non-type template parameter shall be
7355 // a converted constant expression of the type of the template-parameter.
7356 APValue Value;
7357 ExprResult ArgResult;
7358 if (IsConvertedConstantExpression) {
7359 ArgResult = BuildConvertedConstantExpression(
7360 From: DeductionArg, T: ParamType,
7361 CCE: StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Dest: Param);
7362 assert(!ArgResult.isUnset());
7363 if (ArgResult.isInvalid()) {
7364 NoteTemplateParameterLocation(Decl: *Param);
7365 return ExprError();
7366 }
7367 } else {
7368 ArgResult = DeductionArg;
7369 }
7370
7371 // For a value-dependent argument, CheckConvertedConstantExpression is
7372 // permitted (and expected) to be unable to determine a value.
7373 if (ArgResult.get()->isValueDependent()) {
7374 setDeductionArg(ArgResult.get());
7375 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7376 CanonicalConverted =
7377 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7378 return Arg;
7379 }
7380
7381 APValue PreNarrowingValue;
7382 ArgResult = EvaluateConvertedConstantExpression(
7383 E: ArgResult.get(), T: ParamType, Value, CCE: CCEKind::TemplateArg, /*RequireInt=*/
7384 false, PreNarrowingValue);
7385 if (ArgResult.isInvalid())
7386 return ExprError();
7387 setDeductionArg(ArgResult.get());
7388
7389 if (Value.isLValue()) {
7390 APValue::LValueBase Base = Value.getLValueBase();
7391 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7392 // For a non-type template-parameter of pointer or reference type,
7393 // the value of the constant expression shall not refer to
7394 assert(ParamType->isPointerOrReferenceType() ||
7395 ParamType->isNullPtrType());
7396 // -- a temporary object
7397 // -- a string literal
7398 // -- the result of a typeid expression, or
7399 // -- a predefined __func__ variable
7400 if (Base &&
7401 (!VD ||
7402 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(Val: VD))) {
7403 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
7404 << Arg->getSourceRange();
7405 return ExprError();
7406 }
7407
7408 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7409 VD->getType()->isArrayType() &&
7410 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7411 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7412 if (ArgPE) {
7413 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7414 CanonicalConverted =
7415 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7416 } else {
7417 SugaredConverted = TemplateArgument(VD, ParamType);
7418 CanonicalConverted =
7419 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7420 ParamType.getCanonicalType());
7421 }
7422 return Arg;
7423 }
7424
7425 // -- a subobject [until C++20]
7426 if (!getLangOpts().CPlusPlus20) {
7427 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7428 Value.isLValueOnePastTheEnd()) {
7429 Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_subobject)
7430 << Value.getAsString(Ctx: Context, Ty: ParamType);
7431 return ExprError();
7432 }
7433 assert((VD || !ParamType->isReferenceType()) &&
7434 "null reference should not be a constant expression");
7435 assert((!VD || !ParamType->isNullPtrType()) &&
7436 "non-null value of type nullptr_t?");
7437 }
7438 }
7439
7440 if (Value.isAddrLabelDiff())
7441 return Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_addr_label_diff);
7442
7443 if (ArgPE) {
7444 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7445 CanonicalConverted =
7446 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7447 } else {
7448 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7449 CanonicalConverted =
7450 TemplateArgument(Context, ParamType.getCanonicalType(), Value);
7451 }
7452 return Arg;
7453 }
7454
7455 // These should have all been handled above using the C++17 rules.
7456 assert(!ArgPE && !StrictCheck);
7457
7458 // C++ [temp.arg.nontype]p5:
7459 // The following conversions are performed on each expression used
7460 // as a non-type template-argument. If a non-type
7461 // template-argument cannot be converted to the type of the
7462 // corresponding template-parameter then the program is
7463 // ill-formed.
7464 if (ParamType->isIntegralOrEnumerationType()) {
7465 // C++11:
7466 // -- for a non-type template-parameter of integral or
7467 // enumeration type, conversions permitted in a converted
7468 // constant expression are applied.
7469 //
7470 // C++98:
7471 // -- for a non-type template-parameter of integral or
7472 // enumeration type, integral promotions (4.5) and integral
7473 // conversions (4.7) are applied.
7474
7475 if (getLangOpts().CPlusPlus11) {
7476 // C++ [temp.arg.nontype]p1:
7477 // A template-argument for a non-type, non-template template-parameter
7478 // shall be one of:
7479 //
7480 // -- for a non-type template-parameter of integral or enumeration
7481 // type, a converted constant expression of the type of the
7482 // template-parameter; or
7483 llvm::APSInt Value;
7484 ExprResult ArgResult = CheckConvertedConstantExpression(
7485 From: Arg, T: ParamType, Value, CCE: CCEKind::TemplateArg);
7486 if (ArgResult.isInvalid())
7487 return ExprError();
7488 Arg = ArgResult.get();
7489
7490 // We can't check arbitrary value-dependent arguments.
7491 if (Arg->isValueDependent()) {
7492 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7493 CanonicalConverted =
7494 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7495 return Arg;
7496 }
7497
7498 // Widen the argument value to sizeof(parameter type). This is almost
7499 // always a no-op, except when the parameter type is bool. In
7500 // that case, this may extend the argument from 1 bit to 8 bits.
7501 QualType IntegerType = ParamType;
7502 if (const auto *ED = IntegerType->getAsEnumDecl())
7503 IntegerType = ED->getIntegerType();
7504 Value = Value.extOrTrunc(width: IntegerType->isBitIntType()
7505 ? Context.getIntWidth(T: IntegerType)
7506 : Context.getTypeSize(T: IntegerType));
7507
7508 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7509 CanonicalConverted =
7510 TemplateArgument(Context, Value, Context.getCanonicalType(T: ParamType));
7511 return Arg;
7512 }
7513
7514 ExprResult ArgResult = DefaultLvalueConversion(E: Arg);
7515 if (ArgResult.isInvalid())
7516 return ExprError();
7517 Arg = ArgResult.get();
7518
7519 QualType ArgType = Arg->getType();
7520
7521 // C++ [temp.arg.nontype]p1:
7522 // A template-argument for a non-type, non-template
7523 // template-parameter shall be one of:
7524 //
7525 // -- an integral constant-expression of integral or enumeration
7526 // type; or
7527 // -- the name of a non-type template-parameter; or
7528 llvm::APSInt Value;
7529 if (!ArgType->isIntegralOrEnumerationType()) {
7530 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_integral_or_enumeral)
7531 << ArgType << Arg->getSourceRange();
7532 NoteTemplateParameterLocation(Decl: *Param);
7533 return ExprError();
7534 }
7535 if (!Arg->isValueDependent()) {
7536 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7537 QualType T;
7538
7539 public:
7540 TmplArgICEDiagnoser(QualType T) : T(T) { }
7541
7542 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7543 SourceLocation Loc) override {
7544 return S.Diag(Loc, DiagID: diag::err_template_arg_not_ice) << T;
7545 }
7546 } Diagnoser(ArgType);
7547
7548 Arg = VerifyIntegerConstantExpression(E: Arg, Result: &Value, Diagnoser).get();
7549 if (!Arg)
7550 return ExprError();
7551 }
7552
7553 // From here on out, all we care about is the unqualified form
7554 // of the argument type.
7555 ArgType = ArgType.getUnqualifiedType();
7556
7557 // Try to convert the argument to the parameter's type.
7558 if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
7559 // Okay: no conversion necessary
7560 } else if (ParamType->isBooleanType()) {
7561 // This is an integral-to-boolean conversion.
7562 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralToBoolean).get();
7563 } else if (IsIntegralPromotion(From: Arg, FromType: ArgType, ToType: ParamType) ||
7564 !ParamType->isEnumeralType()) {
7565 // This is an integral promotion or conversion.
7566 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralCast).get();
7567 } else {
7568 // We can't perform this conversion.
7569 Diag(Loc: StartLoc, DiagID: diag::err_template_arg_not_convertible)
7570 << Arg->getType() << ParamType << Arg->getSourceRange();
7571 NoteTemplateParameterLocation(Decl: *Param);
7572 return ExprError();
7573 }
7574
7575 // Add the value of this argument to the list of converted
7576 // arguments. We use the bitwidth and signedness of the template
7577 // parameter.
7578 if (Arg->isValueDependent()) {
7579 // The argument is value-dependent. Create a new
7580 // TemplateArgument with the converted expression.
7581 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7582 CanonicalConverted =
7583 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7584 return Arg;
7585 }
7586
7587 QualType IntegerType = ParamType;
7588 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7589 IntegerType = ED->getIntegerType();
7590 }
7591
7592 if (ParamType->isBooleanType()) {
7593 // Value must be zero or one.
7594 Value = Value != 0;
7595 unsigned AllowedBits = Context.getTypeSize(T: IntegerType);
7596 if (Value.getBitWidth() != AllowedBits)
7597 Value = Value.extOrTrunc(width: AllowedBits);
7598 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7599 } else {
7600 llvm::APSInt OldValue = Value;
7601
7602 // Coerce the template argument's value to the value it will have
7603 // based on the template parameter's type.
7604 unsigned AllowedBits = IntegerType->isBitIntType()
7605 ? Context.getIntWidth(T: IntegerType)
7606 : Context.getTypeSize(T: IntegerType);
7607 if (Value.getBitWidth() != AllowedBits)
7608 Value = Value.extOrTrunc(width: AllowedBits);
7609 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7610
7611 // Complain if an unsigned parameter received a negative value.
7612 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7613 (OldValue.isSigned() && OldValue.isNegative())) {
7614 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_negative)
7615 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7616 << Arg->getSourceRange();
7617 NoteTemplateParameterLocation(Decl: *Param);
7618 }
7619
7620 // Complain if we overflowed the template parameter's type.
7621 unsigned RequiredBits;
7622 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7623 RequiredBits = OldValue.getActiveBits();
7624 else if (OldValue.isUnsigned())
7625 RequiredBits = OldValue.getActiveBits() + 1;
7626 else
7627 RequiredBits = OldValue.getSignificantBits();
7628 if (RequiredBits > AllowedBits) {
7629 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_too_large)
7630 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7631 << Arg->getSourceRange();
7632 NoteTemplateParameterLocation(Decl: *Param);
7633 }
7634 }
7635
7636 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7637 SugaredConverted = TemplateArgument(Context, Value, T);
7638 CanonicalConverted =
7639 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7640 return Arg;
7641 }
7642
7643 QualType ArgType = Arg->getType();
7644 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7645 bool IsSpecified = CTAK == CTAK_Specified;
7646
7647 // Handle pointer-to-function, reference-to-function, and
7648 // pointer-to-member-function all in (roughly) the same way.
7649 if (// -- For a non-type template-parameter of type pointer to
7650 // function, only the function-to-pointer conversion (4.3) is
7651 // applied. If the template-argument represents a set of
7652 // overloaded functions (or a pointer to such), the matching
7653 // function is selected from the set (13.4).
7654 (ParamType->isPointerType() &&
7655 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7656 // -- For a non-type template-parameter of type reference to
7657 // function, no conversions apply. If the template-argument
7658 // represents a set of overloaded functions, the matching
7659 // function is selected from the set (13.4).
7660 (ParamType->isReferenceType() &&
7661 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7662 // -- For a non-type template-parameter of type pointer to
7663 // member function, no conversions apply. If the
7664 // template-argument represents a set of overloaded member
7665 // functions, the matching member function is selected from
7666 // the set (13.4).
7667 (ParamType->isMemberPointerType() &&
7668 ParamType->castAs<MemberPointerType>()->getPointeeType()
7669 ->isFunctionType())) {
7670
7671 if (Arg->getType() == Context.OverloadTy) {
7672 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg, TargetType: ParamType,
7673 Complain: true,
7674 Found&: FoundResult)) {
7675 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7676 return ExprError();
7677
7678 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7679 if (Res.isInvalid())
7680 return ExprError();
7681 Arg = Res.get();
7682 ArgType = Arg->getType();
7683 } else
7684 return ExprError();
7685 }
7686
7687 if (!ParamType->isMemberPointerType()) {
7688 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7689 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7690 CanonicalConverted))
7691 return ExprError();
7692 return Arg;
7693 }
7694
7695 if (CheckTemplateArgumentPointerToMember(
7696 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7697 return ExprError();
7698 return Arg;
7699 }
7700
7701 if (ParamType->isPointerType()) {
7702 // -- for a non-type template-parameter of type pointer to
7703 // object, qualification conversions (4.4) and the
7704 // array-to-pointer conversion (4.2) are applied.
7705 // C++0x also allows a value of std::nullptr_t.
7706 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7707 "Only object pointers allowed here");
7708
7709 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7710 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7711 CanonicalConverted))
7712 return ExprError();
7713 return Arg;
7714 }
7715
7716 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7717 // -- For a non-type template-parameter of type reference to
7718 // object, no conversions apply. The type referred to by the
7719 // reference may be more cv-qualified than the (otherwise
7720 // identical) type of the template-argument. The
7721 // template-parameter is bound directly to the
7722 // template-argument, which must be an lvalue.
7723 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7724 "Only object references allowed here");
7725
7726 if (Arg->getType() == Context.OverloadTy) {
7727 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg,
7728 TargetType: ParamRefType->getPointeeType(),
7729 Complain: true,
7730 Found&: FoundResult)) {
7731 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7732 return ExprError();
7733 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7734 if (Res.isInvalid())
7735 return ExprError();
7736 Arg = Res.get();
7737 ArgType = Arg->getType();
7738 } else
7739 return ExprError();
7740 }
7741
7742 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7743 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7744 CanonicalConverted))
7745 return ExprError();
7746 return Arg;
7747 }
7748
7749 // Deal with parameters of type std::nullptr_t.
7750 if (ParamType->isNullPtrType()) {
7751 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7752 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7753 CanonicalConverted =
7754 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7755 return Arg;
7756 }
7757
7758 switch (isNullPointerValueTemplateArgument(S&: *this, Param, ParamType, Arg)) {
7759 case NPV_NotNullPointer:
7760 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_not_convertible)
7761 << Arg->getType() << ParamType;
7762 NoteTemplateParameterLocation(Decl: *Param);
7763 return ExprError();
7764
7765 case NPV_Error:
7766 return ExprError();
7767
7768 case NPV_NullPointer:
7769 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7770 SugaredConverted = TemplateArgument(ParamType,
7771 /*isNullPtr=*/true);
7772 CanonicalConverted = TemplateArgument(Context.getCanonicalType(T: ParamType),
7773 /*isNullPtr=*/true);
7774 return Arg;
7775 }
7776 }
7777
7778 // -- For a non-type template-parameter of type pointer to data
7779 // member, qualification conversions (4.4) are applied.
7780 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7781
7782 if (CheckTemplateArgumentPointerToMember(
7783 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7784 return ExprError();
7785 return Arg;
7786}
7787
7788static void DiagnoseTemplateParameterListArityMismatch(
7789 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7790 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7791
7792bool Sema::CheckDeclCompatibleWithTemplateTemplate(
7793 TemplateDecl *Template, TemplateTemplateParmDecl *Param,
7794 const TemplateArgumentLoc &Arg) {
7795 // C++0x [temp.arg.template]p1:
7796 // A template-argument for a template template-parameter shall be
7797 // the name of a class template or an alias template, expressed as an
7798 // id-expression. When the template-argument names a class template, only
7799 // primary class templates are considered when matching the
7800 // template template argument with the corresponding parameter;
7801 // partial specializations are not considered even if their
7802 // parameter lists match that of the template template parameter.
7803 //
7804
7805 TemplateNameKind Kind = TNK_Non_template;
7806 unsigned DiagFoundKind = 0;
7807
7808 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Val: Template)) {
7809 switch (TTP->templateParameterKind()) {
7810 case TemplateNameKind::TNK_Concept_template:
7811 DiagFoundKind = 3;
7812 break;
7813 case TemplateNameKind::TNK_Var_template:
7814 DiagFoundKind = 2;
7815 break;
7816 default:
7817 DiagFoundKind = 1;
7818 break;
7819 }
7820 Kind = TTP->templateParameterKind();
7821 } else if (isa<ConceptDecl>(Val: Template)) {
7822 Kind = TemplateNameKind::TNK_Concept_template;
7823 DiagFoundKind = 3;
7824 } else if (isa<FunctionTemplateDecl>(Val: Template)) {
7825 Kind = TemplateNameKind::TNK_Function_template;
7826 DiagFoundKind = 0;
7827 } else if (isa<VarTemplateDecl>(Val: Template)) {
7828 Kind = TemplateNameKind::TNK_Var_template;
7829 DiagFoundKind = 2;
7830 } else if (isa<ClassTemplateDecl>(Val: Template) ||
7831 isa<TypeAliasTemplateDecl>(Val: Template) ||
7832 isa<BuiltinTemplateDecl>(Val: Template)) {
7833 Kind = TemplateNameKind::TNK_Type_template;
7834 DiagFoundKind = 1;
7835 } else {
7836 assert(false && "Unexpected Decl");
7837 }
7838
7839 if (Kind == Param->templateParameterKind()) {
7840 return true;
7841 }
7842
7843 unsigned DiagKind = 0;
7844 switch (Param->templateParameterKind()) {
7845 case TemplateNameKind::TNK_Concept_template:
7846 DiagKind = 2;
7847 break;
7848 case TemplateNameKind::TNK_Var_template:
7849 DiagKind = 1;
7850 break;
7851 default:
7852 DiagKind = 0;
7853 break;
7854 }
7855 Diag(Loc: Arg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
7856 << DiagKind;
7857 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_arg_refers_to_template_here)
7858 << DiagFoundKind << Template;
7859 return false;
7860}
7861
7862/// Check a template argument against its corresponding
7863/// template template parameter.
7864///
7865/// This routine implements the semantics of C++ [temp.arg.template].
7866/// It returns true if an error occurred, and false otherwise.
7867bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7868 TemplateParameterList *Params,
7869 TemplateArgumentLoc &Arg,
7870 bool PartialOrdering,
7871 bool *StrictPackMatch) {
7872 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7873 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7874 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7875 if (!Template) {
7876 // FIXME: Handle AssumedTemplateNames
7877 // Any dependent template name is fine.
7878 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7879 return false;
7880 }
7881
7882 if (Template->isInvalidDecl())
7883 return true;
7884
7885 if (!CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg)) {
7886 return true;
7887 }
7888
7889 // C++1z [temp.arg.template]p3: (DR 150)
7890 // A template-argument matches a template template-parameter P when P
7891 // is at least as specialized as the template-argument A.
7892 if (!isTemplateTemplateParameterAtLeastAsSpecializedAs(
7893 PParam: Params, PArg: Param, AArg: Template, DefaultArgs, ArgLoc: Arg.getLocation(),
7894 PartialOrdering, StrictPackMatch))
7895 return true;
7896 // P2113
7897 // C++20[temp.func.order]p2
7898 // [...] If both deductions succeed, the partial ordering selects the
7899 // more constrained template (if one exists) as determined below.
7900 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7901 Params->getAssociatedConstraints(AC&: ParamsAC);
7902 // C++20[temp.arg.template]p3
7903 // [...] In this comparison, if P is unconstrained, the constraints on A
7904 // are not considered.
7905 if (ParamsAC.empty())
7906 return false;
7907
7908 Template->getAssociatedConstraints(AC&: TemplateAC);
7909
7910 bool IsParamAtLeastAsConstrained;
7911 if (IsAtLeastAsConstrained(D1: Param, AC1: ParamsAC, D2: Template, AC2: TemplateAC,
7912 Result&: IsParamAtLeastAsConstrained))
7913 return true;
7914 if (!IsParamAtLeastAsConstrained) {
7915 Diag(Loc: Arg.getLocation(),
7916 DiagID: diag::err_template_template_parameter_not_at_least_as_constrained)
7917 << Template << Param << Arg.getSourceRange();
7918 Diag(Loc: Param->getLocation(), DiagID: diag::note_entity_declared_at) << Param;
7919 Diag(Loc: Template->getLocation(), DiagID: diag::note_entity_declared_at) << Template;
7920 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Param, AC1: ParamsAC, D2: Template,
7921 AC2: TemplateAC);
7922 return true;
7923 }
7924 return false;
7925}
7926
7927static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7928 unsigned HereDiagID,
7929 unsigned ExternalDiagID) {
7930 if (Decl.getLocation().isValid())
7931 return S.Diag(Loc: Decl.getLocation(), DiagID: HereDiagID);
7932
7933 SmallString<128> Str;
7934 llvm::raw_svector_ostream Out(Str);
7935 PrintingPolicy PP = S.getPrintingPolicy();
7936 PP.TerseOutput = 1;
7937 Decl.print(Out, Policy: PP);
7938 return S.Diag(Loc: Decl.getLocation(), DiagID: ExternalDiagID) << Out.str();
7939}
7940
7941void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7942 std::optional<SourceRange> ParamRange) {
7943 SemaDiagnosticBuilder DB =
7944 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_decl_here,
7945 ExternalDiagID: diag::note_template_decl_external);
7946 if (ParamRange && ParamRange->isValid()) {
7947 assert(Decl.getLocation().isValid() &&
7948 "Parameter range has location when Decl does not");
7949 DB << *ParamRange;
7950 }
7951}
7952
7953void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7954 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_param_here,
7955 ExternalDiagID: diag::note_template_param_external);
7956}
7957
7958/// Given a non-type template argument that refers to a
7959/// declaration and the type of its corresponding non-type template
7960/// parameter, produce an expression that properly refers to that
7961/// declaration.
7962ExprResult Sema::BuildExpressionFromDeclTemplateArgument(
7963 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
7964 // C++ [temp.param]p8:
7965 //
7966 // A non-type template-parameter of type "array of T" or
7967 // "function returning T" is adjusted to be of type "pointer to
7968 // T" or "pointer to function returning T", respectively.
7969 if (ParamType->isArrayType())
7970 ParamType = Context.getArrayDecayedType(T: ParamType);
7971 else if (ParamType->isFunctionType())
7972 ParamType = Context.getPointerType(T: ParamType);
7973
7974 // For a NULL non-type template argument, return nullptr casted to the
7975 // parameter's type.
7976 if (Arg.getKind() == TemplateArgument::NullPtr) {
7977 return ImpCastExprToType(
7978 E: new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7979 Type: ParamType,
7980 CK: ParamType->getAs<MemberPointerType>()
7981 ? CK_NullToMemberPointer
7982 : CK_NullToPointer);
7983 }
7984 assert(Arg.getKind() == TemplateArgument::Declaration &&
7985 "Only declaration template arguments permitted here");
7986
7987 ValueDecl *VD = Arg.getAsDecl();
7988
7989 CXXScopeSpec SS;
7990 if (ParamType->isMemberPointerType()) {
7991 // If this is a pointer to member, we need to use a qualified name to
7992 // form a suitable pointer-to-member constant.
7993 assert(VD->getDeclContext()->isRecord() &&
7994 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7995 isa<IndirectFieldDecl>(VD)));
7996 CanQualType ClassType =
7997 Context.getCanonicalTagType(TD: cast<RecordDecl>(Val: VD->getDeclContext()));
7998 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7999 SS.MakeTrivial(Context, Qualifier, R: Loc);
8000 }
8001
8002 ExprResult RefExpr = BuildDeclarationNameExpr(
8003 SS, NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
8004 if (RefExpr.isInvalid())
8005 return ExprError();
8006
8007 // For a pointer, the argument declaration is the pointee. Take its address.
8008 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8009 if (ParamType->isPointerType() && !ElemT.isNull() &&
8010 Context.hasSimilarType(T1: ElemT, T2: ParamType->getPointeeType())) {
8011 // Decay an array argument if we want a pointer to its first element.
8012 RefExpr = DefaultFunctionArrayConversion(E: RefExpr.get());
8013 if (RefExpr.isInvalid())
8014 return ExprError();
8015 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8016 // For any other pointer, take the address (or form a pointer-to-member).
8017 RefExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_AddrOf, InputExpr: RefExpr.get());
8018 if (RefExpr.isInvalid())
8019 return ExprError();
8020 } else if (ParamType->isRecordType()) {
8021 assert(isa<TemplateParamObjectDecl>(VD) &&
8022 "arg for class template param not a template parameter object");
8023 // No conversions apply in this case.
8024 return RefExpr;
8025 } else {
8026 assert(ParamType->isReferenceType() &&
8027 "unexpected type for decl template argument");
8028 // If the parameter has reference type, wrap it in paretheses so that this
8029 // expression will have the correct type under `decltype`.
8030 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8031 }
8032
8033 // At this point we should have the right value category.
8034 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8035 "value kind mismatch for non-type template argument");
8036
8037 // The type of the template parameter can differ from the type of the
8038 // argument in various ways; convert it now if necessary.
8039 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8040 QualType SrcExprType = RefExpr.get()->getType();
8041 if (!Context.hasSameType(T1: SrcExprType, T2: DestExprType)) {
8042 CastKind CK;
8043 if (Context.hasSimilarType(T1: SrcExprType, T2: DestExprType) ||
8044 IsFunctionConversion(FromType: SrcExprType, ToType: DestExprType)) {
8045 CK = CK_NoOp;
8046 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8047 CK = CK_BitCast;
8048 } else {
8049 // FIXME: Pointers to members can need conversion derived-to-base or
8050 // base-to-derived conversions. We currently don't retain enough
8051 // information to convert properly (we need to track a cast path or
8052 // subobject number in the template argument).
8053 llvm_unreachable(
8054 "unexpected conversion required for non-type template argument");
8055 }
8056 RefExpr = ImpCastExprToType(E: RefExpr.get(), Type: DestExprType, CK,
8057 VK: RefExpr.get()->getValueKind());
8058 }
8059
8060 return RefExpr;
8061}
8062
8063/// Construct a new expression that refers to the given
8064/// integral template argument with the given source-location
8065/// information.
8066///
8067/// This routine takes care of the mapping from an integral template
8068/// argument (which may have any integral type) to the appropriate
8069/// literal value.
8070static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
8071 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8072 assert(OrigT->isIntegralOrEnumerationType());
8073
8074 // If this is an enum type that we're instantiating, we need to use an integer
8075 // type the same size as the enumerator. We don't want to build an
8076 // IntegerLiteral with enum type. The integer type of an enum type can be of
8077 // any integral type with C++11 enum classes, make sure we create the right
8078 // type of literal for it.
8079 QualType T = OrigT;
8080 if (const auto *ED = OrigT->getAsEnumDecl())
8081 T = ED->getIntegerType();
8082
8083 Expr *E;
8084 if (T->isAnyCharacterType()) {
8085 CharacterLiteralKind Kind;
8086 if (T->isWideCharType())
8087 Kind = CharacterLiteralKind::Wide;
8088 else if (T->isChar8Type() && S.getLangOpts().Char8)
8089 Kind = CharacterLiteralKind::UTF8;
8090 else if (T->isChar16Type())
8091 Kind = CharacterLiteralKind::UTF16;
8092 else if (T->isChar32Type())
8093 Kind = CharacterLiteralKind::UTF32;
8094 else
8095 Kind = CharacterLiteralKind::Ascii;
8096
8097 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8098 } else if (T->isBooleanType()) {
8099 E = CXXBoolLiteralExpr::Create(C: S.Context, Val: Int.getBoolValue(), Ty: T, Loc);
8100 } else {
8101 E = IntegerLiteral::Create(C: S.Context, V: Int, type: T, l: Loc);
8102 }
8103
8104 if (OrigT->isEnumeralType()) {
8105 // FIXME: This is a hack. We need a better way to handle substituted
8106 // non-type template parameters.
8107 E = CStyleCastExpr::Create(Context: S.Context, T: OrigT, VK: VK_PRValue, K: CK_IntegralCast, Op: E,
8108 BasePath: nullptr, FPO: S.CurFPFeatureOverrides(),
8109 WrittenTy: S.Context.getTrivialTypeSourceInfo(T: OrigT, Loc),
8110 L: Loc, R: Loc);
8111 }
8112
8113 return E;
8114}
8115
8116static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
8117 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8118 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8119 auto *ILE = new (S.Context)
8120 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8121 ILE->setType(T);
8122 return ILE;
8123 };
8124
8125 switch (Val.getKind()) {
8126 case APValue::AddrLabelDiff:
8127 // This cannot occur in a template argument at all.
8128 case APValue::Array:
8129 case APValue::Struct:
8130 case APValue::Union:
8131 // These can only occur within a template parameter object, which is
8132 // represented as a TemplateArgument::Declaration.
8133 llvm_unreachable("unexpected template argument value");
8134
8135 case APValue::Int:
8136 return BuildExpressionFromIntegralTemplateArgumentValue(S, OrigT: T, Int: Val.getInt(),
8137 Loc);
8138
8139 case APValue::Float:
8140 return FloatingLiteral::Create(C: S.Context, V: Val.getFloat(), /*IsExact=*/isexact: true,
8141 Type: T, L: Loc);
8142
8143 case APValue::FixedPoint:
8144 return FixedPointLiteral::CreateFromRawInt(
8145 C: S.Context, V: Val.getFixedPoint().getValue(), type: T, l: Loc,
8146 Scale: Val.getFixedPoint().getScale());
8147
8148 case APValue::ComplexInt: {
8149 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8150 return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
8151 S, OrigT: ElemT, Int: Val.getComplexIntReal(), Loc),
8152 BuildExpressionFromIntegralTemplateArgumentValue(
8153 S, OrigT: ElemT, Int: Val.getComplexIntImag(), Loc)});
8154 }
8155
8156 case APValue::ComplexFloat: {
8157 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8158 return MakeInitList(
8159 {FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatReal(), isexact: true,
8160 Type: ElemT, L: Loc),
8161 FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatImag(), isexact: true,
8162 Type: ElemT, L: Loc)});
8163 }
8164
8165 case APValue::Vector: {
8166 QualType ElemT = T->castAs<VectorType>()->getElementType();
8167 llvm::SmallVector<Expr *, 8> Elts;
8168 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8169 Elts.push_back(Elt: BuildExpressionFromNonTypeTemplateArgumentValue(
8170 S, T: ElemT, Val: Val.getVectorElt(I), Loc));
8171 return MakeInitList(Elts);
8172 }
8173
8174 case APValue::Matrix:
8175 llvm_unreachable("Matrix template argument expression not yet supported");
8176
8177 case APValue::None:
8178 case APValue::Indeterminate:
8179 llvm_unreachable("Unexpected APValue kind.");
8180 case APValue::LValue:
8181 case APValue::MemberPointer:
8182 // There isn't necessarily a valid equivalent source-level syntax for
8183 // these; in particular, a naive lowering might violate access control.
8184 // So for now we lower to a ConstantExpr holding the value, wrapped around
8185 // an OpaqueValueExpr.
8186 // FIXME: We should have a better representation for this.
8187 ExprValueKind VK = VK_PRValue;
8188 if (T->isReferenceType()) {
8189 T = T->getPointeeType();
8190 VK = VK_LValue;
8191 }
8192 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8193 return ConstantExpr::Create(Context: S.Context, E: OVE, Result: Val);
8194 }
8195 llvm_unreachable("Unhandled APValue::ValueKind enum");
8196}
8197
8198ExprResult
8199Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
8200 SourceLocation Loc) {
8201 switch (Arg.getKind()) {
8202 case TemplateArgument::Null:
8203 case TemplateArgument::Type:
8204 case TemplateArgument::Template:
8205 case TemplateArgument::TemplateExpansion:
8206 case TemplateArgument::Pack:
8207 llvm_unreachable("not a non-type template argument");
8208
8209 case TemplateArgument::Expression:
8210 return Arg.getAsExpr();
8211
8212 case TemplateArgument::NullPtr:
8213 case TemplateArgument::Declaration:
8214 return BuildExpressionFromDeclTemplateArgument(
8215 Arg, ParamType: Arg.getNonTypeTemplateArgumentType(), Loc);
8216
8217 case TemplateArgument::Integral:
8218 return BuildExpressionFromIntegralTemplateArgumentValue(
8219 S&: *this, OrigT: Arg.getIntegralType(), Int: Arg.getAsIntegral(), Loc);
8220
8221 case TemplateArgument::StructuralValue:
8222 return BuildExpressionFromNonTypeTemplateArgumentValue(
8223 S&: *this, T: Arg.getStructuralValueType(), Val: Arg.getAsStructuralValue(), Loc);
8224 }
8225 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8226}
8227
8228/// Match two template parameters within template parameter lists.
8229static bool MatchTemplateParameterKind(
8230 Sema &S, NamedDecl *New,
8231 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8232 const NamedDecl *OldInstFrom, bool Complain,
8233 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8234 // Check the actual kind (type, non-type, template).
8235 if (Old->getKind() != New->getKind()) {
8236 if (Complain) {
8237 unsigned NextDiag = diag::err_template_param_different_kind;
8238 if (TemplateArgLoc.isValid()) {
8239 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8240 NextDiag = diag::note_template_param_different_kind;
8241 }
8242 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8243 << (Kind != Sema::TPL_TemplateMatch);
8244 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_prev_declaration)
8245 << (Kind != Sema::TPL_TemplateMatch);
8246 }
8247
8248 return false;
8249 }
8250
8251 // Check that both are parameter packs or neither are parameter packs.
8252 // However, if we are matching a template template argument to a
8253 // template template parameter, the template template parameter can have
8254 // a parameter pack where the template template argument does not.
8255 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8256 if (Complain) {
8257 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8258 if (TemplateArgLoc.isValid()) {
8259 S.Diag(Loc: TemplateArgLoc,
8260 DiagID: diag::err_template_arg_template_params_mismatch);
8261 NextDiag = diag::note_template_parameter_pack_non_pack;
8262 }
8263
8264 unsigned ParamKind = isa<TemplateTypeParmDecl>(Val: New)? 0
8265 : isa<NonTypeTemplateParmDecl>(Val: New)? 1
8266 : 2;
8267 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8268 << ParamKind << New->isParameterPack();
8269 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_parameter_pack_here)
8270 << ParamKind << Old->isParameterPack();
8271 }
8272
8273 return false;
8274 }
8275 // For non-type template parameters, check the type of the parameter.
8276 if (NonTypeTemplateParmDecl *OldNTTP =
8277 dyn_cast<NonTypeTemplateParmDecl>(Val: Old)) {
8278 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(Val: New);
8279
8280 // If we are matching a template template argument to a template
8281 // template parameter and one of the non-type template parameter types
8282 // is dependent, then we must wait until template instantiation time
8283 // to actually compare the arguments.
8284 if (Kind != Sema::TPL_TemplateTemplateParmMatch ||
8285 (!OldNTTP->getType()->isDependentType() &&
8286 !NewNTTP->getType()->isDependentType())) {
8287 // C++20 [temp.over.link]p6:
8288 // Two [non-type] template-parameters are equivalent [if] they have
8289 // equivalent types ignoring the use of type-constraints for
8290 // placeholder types
8291 QualType OldType = S.Context.getUnconstrainedType(T: OldNTTP->getType());
8292 QualType NewType = S.Context.getUnconstrainedType(T: NewNTTP->getType());
8293 if (!S.Context.hasSameType(T1: OldType, T2: NewType)) {
8294 if (Complain) {
8295 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8296 if (TemplateArgLoc.isValid()) {
8297 S.Diag(Loc: TemplateArgLoc,
8298 DiagID: diag::err_template_arg_template_params_mismatch);
8299 NextDiag = diag::note_template_nontype_parm_different_type;
8300 }
8301 S.Diag(Loc: NewNTTP->getLocation(), DiagID: NextDiag)
8302 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8303 S.Diag(Loc: OldNTTP->getLocation(),
8304 DiagID: diag::note_template_nontype_parm_prev_declaration)
8305 << OldNTTP->getType();
8306 }
8307 return false;
8308 }
8309 }
8310 }
8311 // For template template parameters, check the template parameter types.
8312 // The template parameter lists of template template
8313 // parameters must agree.
8314 else if (TemplateTemplateParmDecl *OldTTP =
8315 dyn_cast<TemplateTemplateParmDecl>(Val: Old)) {
8316 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(Val: New);
8317 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8318 return false;
8319 if (!S.TemplateParameterListsAreEqual(
8320 NewInstFrom, New: NewTTP->getTemplateParameters(), OldInstFrom,
8321 Old: OldTTP->getTemplateParameters(), Complain,
8322 Kind: (Kind == Sema::TPL_TemplateMatch
8323 ? Sema::TPL_TemplateTemplateParmMatch
8324 : Kind),
8325 TemplateArgLoc))
8326 return false;
8327 }
8328
8329 if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8330 Kind != Sema::TPL_TemplateTemplateParmMatch &&
8331 !isa<TemplateTemplateParmDecl>(Val: Old)) {
8332 const Expr *NewC = nullptr, *OldC = nullptr;
8333
8334 if (isa<TemplateTypeParmDecl>(Val: New)) {
8335 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: New)->getTypeConstraint())
8336 NewC = TC->getImmediatelyDeclaredConstraint();
8337 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: Old)->getTypeConstraint())
8338 OldC = TC->getImmediatelyDeclaredConstraint();
8339 } else if (isa<NonTypeTemplateParmDecl>(Val: New)) {
8340 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: New)
8341 ->getPlaceholderTypeConstraint())
8342 NewC = E;
8343 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: Old)
8344 ->getPlaceholderTypeConstraint())
8345 OldC = E;
8346 } else
8347 llvm_unreachable("unexpected template parameter type");
8348
8349 auto Diagnose = [&] {
8350 S.Diag(Loc: NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8351 DiagID: diag::err_template_different_type_constraint);
8352 S.Diag(Loc: OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8353 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8354 };
8355
8356 if (!NewC != !OldC) {
8357 if (Complain)
8358 Diagnose();
8359 return false;
8360 }
8361
8362 if (NewC) {
8363 if (!S.AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldC, New: NewInstFrom,
8364 NewConstr: NewC)) {
8365 if (Complain)
8366 Diagnose();
8367 return false;
8368 }
8369 }
8370 }
8371
8372 return true;
8373}
8374
8375/// Diagnose a known arity mismatch when comparing template argument
8376/// lists.
8377static
8378void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8379 TemplateParameterList *New,
8380 TemplateParameterList *Old,
8381 Sema::TemplateParameterListEqualKind Kind,
8382 SourceLocation TemplateArgLoc) {
8383 unsigned NextDiag = diag::err_template_param_list_different_arity;
8384 if (TemplateArgLoc.isValid()) {
8385 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8386 NextDiag = diag::note_template_param_list_different_arity;
8387 }
8388 S.Diag(Loc: New->getTemplateLoc(), DiagID: NextDiag)
8389 << (New->size() > Old->size())
8390 << (Kind != Sema::TPL_TemplateMatch)
8391 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8392 S.Diag(Loc: Old->getTemplateLoc(), DiagID: diag::note_template_prev_declaration)
8393 << (Kind != Sema::TPL_TemplateMatch)
8394 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8395}
8396
8397bool Sema::TemplateParameterListsAreEqual(
8398 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8399 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8400 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8401 if (Old->size() != New->size()) {
8402 if (Complain)
8403 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8404 TemplateArgLoc);
8405
8406 return false;
8407 }
8408
8409 // C++0x [temp.arg.template]p3:
8410 // A template-argument matches a template template-parameter (call it P)
8411 // when each of the template parameters in the template-parameter-list of
8412 // the template-argument's corresponding class template or alias template
8413 // (call it A) matches the corresponding template parameter in the
8414 // template-parameter-list of P. [...]
8415 TemplateParameterList::iterator NewParm = New->begin();
8416 TemplateParameterList::iterator NewParmEnd = New->end();
8417 for (TemplateParameterList::iterator OldParm = Old->begin(),
8418 OldParmEnd = Old->end();
8419 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8420 if (NewParm == NewParmEnd) {
8421 if (Complain)
8422 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8423 TemplateArgLoc);
8424 return false;
8425 }
8426 if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm,
8427 OldInstFrom, Complain, Kind,
8428 TemplateArgLoc))
8429 return false;
8430 }
8431
8432 // Make sure we exhausted all of the arguments.
8433 if (NewParm != NewParmEnd) {
8434 if (Complain)
8435 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8436 TemplateArgLoc);
8437
8438 return false;
8439 }
8440
8441 if (Kind != TPL_TemplateParamsEquivalent) {
8442 const Expr *NewRC = New->getRequiresClause();
8443 const Expr *OldRC = Old->getRequiresClause();
8444
8445 auto Diagnose = [&] {
8446 Diag(Loc: NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8447 DiagID: diag::err_template_different_requires_clause);
8448 Diag(Loc: OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8449 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8450 };
8451
8452 if (!NewRC != !OldRC) {
8453 if (Complain)
8454 Diagnose();
8455 return false;
8456 }
8457
8458 if (NewRC) {
8459 if (!AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldRC, New: NewInstFrom,
8460 NewConstr: NewRC)) {
8461 if (Complain)
8462 Diagnose();
8463 return false;
8464 }
8465 }
8466 }
8467
8468 return true;
8469}
8470
8471bool
8472Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8473 if (!S)
8474 return false;
8475
8476 // Find the nearest enclosing declaration scope.
8477 S = S->getDeclParent();
8478
8479 // C++ [temp.pre]p6: [P2096]
8480 // A template, explicit specialization, or partial specialization shall not
8481 // have C linkage.
8482 DeclContext *Ctx = S->getEntity();
8483 if (Ctx && Ctx->isExternCContext()) {
8484 SourceRange Range =
8485 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8486 ? TemplateParams->getParam(Idx: 0)->getSourceRange()
8487 : TemplateParams->getSourceRange();
8488 Diag(Loc: Range.getBegin(), DiagID: diag::err_template_linkage) << Range;
8489 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8490 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
8491 return true;
8492 }
8493 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8494
8495 // C++ [temp]p2:
8496 // A template-declaration can appear only as a namespace scope or
8497 // class scope declaration.
8498 // C++ [temp.expl.spec]p3:
8499 // An explicit specialization may be declared in any scope in which the
8500 // corresponding primary template may be defined.
8501 // C++ [temp.class.spec]p6: [P2096]
8502 // A partial specialization may be declared in any scope in which the
8503 // corresponding primary template may be defined.
8504 if (Ctx) {
8505 if (Ctx->isFileContext())
8506 return false;
8507 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Ctx)) {
8508 // C++ [temp.mem]p2:
8509 // A local class shall not have member templates.
8510 if (RD->isLocalClass())
8511 return Diag(Loc: TemplateParams->getTemplateLoc(),
8512 DiagID: diag::err_template_inside_local_class)
8513 << TemplateParams->getSourceRange();
8514 else
8515 return false;
8516 }
8517 }
8518
8519 return Diag(Loc: TemplateParams->getTemplateLoc(),
8520 DiagID: diag::err_template_outside_namespace_or_class_scope)
8521 << TemplateParams->getSourceRange();
8522}
8523
8524/// Determine what kind of template specialization the given declaration
8525/// is.
8526static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8527 if (!D)
8528 return TSK_Undeclared;
8529
8530 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D))
8531 return Record->getTemplateSpecializationKind();
8532 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D))
8533 return Function->getTemplateSpecializationKind();
8534 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D))
8535 return Var->getTemplateSpecializationKind();
8536
8537 return TSK_Undeclared;
8538}
8539
8540/// Check whether a specialization is well-formed in the current
8541/// context.
8542///
8543/// This routine determines whether a template specialization can be declared
8544/// in the current context (C++ [temp.expl.spec]p2).
8545///
8546/// \param S the semantic analysis object for which this check is being
8547/// performed.
8548///
8549/// \param Specialized the entity being specialized or instantiated, which
8550/// may be a kind of template (class template, function template, etc.) or
8551/// a member of a class template (member function, static data member,
8552/// member class).
8553///
8554/// \param PrevDecl the previous declaration of this entity, if any.
8555///
8556/// \param Loc the location of the explicit specialization or instantiation of
8557/// this entity.
8558///
8559/// \param IsPartialSpecialization whether this is a partial specialization of
8560/// a class template.
8561///
8562/// \returns true if there was an error that we cannot recover from, false
8563/// otherwise.
8564static bool CheckTemplateSpecializationScope(Sema &S,
8565 NamedDecl *Specialized,
8566 NamedDecl *PrevDecl,
8567 SourceLocation Loc,
8568 bool IsPartialSpecialization) {
8569 // Keep these "kind" numbers in sync with the %select statements in the
8570 // various diagnostics emitted by this routine.
8571 int EntityKind = 0;
8572 if (isa<ClassTemplateDecl>(Val: Specialized))
8573 EntityKind = IsPartialSpecialization? 1 : 0;
8574 else if (isa<VarTemplateDecl>(Val: Specialized))
8575 EntityKind = IsPartialSpecialization ? 3 : 2;
8576 else if (isa<FunctionTemplateDecl>(Val: Specialized))
8577 EntityKind = 4;
8578 else if (isa<CXXMethodDecl>(Val: Specialized))
8579 EntityKind = 5;
8580 else if (isa<VarDecl>(Val: Specialized))
8581 EntityKind = 6;
8582 else if (isa<RecordDecl>(Val: Specialized))
8583 EntityKind = 7;
8584 else if (isa<EnumDecl>(Val: Specialized) && S.getLangOpts().CPlusPlus11)
8585 EntityKind = 8;
8586 else {
8587 S.Diag(Loc, DiagID: diag::err_template_spec_unknown_kind)
8588 << S.getLangOpts().CPlusPlus11;
8589 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8590 return true;
8591 }
8592
8593 // C++ [temp.expl.spec]p2:
8594 // An explicit specialization may be declared in any scope in which
8595 // the corresponding primary template may be defined.
8596 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8597 S.Diag(Loc, DiagID: diag::err_template_spec_decl_function_scope)
8598 << Specialized;
8599 return true;
8600 }
8601
8602 // C++ [temp.class.spec]p6:
8603 // A class template partial specialization may be declared in any
8604 // scope in which the primary template may be defined.
8605 DeclContext *SpecializedContext =
8606 Specialized->getDeclContext()->getRedeclContext();
8607 DeclContext *DC = S.CurContext->getRedeclContext();
8608
8609 // Make sure that this redeclaration (or definition) occurs in the same
8610 // scope or an enclosing namespace.
8611 if (!(DC->isFileContext() ? DC->Encloses(DC: SpecializedContext)
8612 : DC->Equals(DC: SpecializedContext))) {
8613 if (isa<TranslationUnitDecl>(Val: SpecializedContext))
8614 S.Diag(Loc, DiagID: diag::err_template_spec_redecl_global_scope)
8615 << EntityKind << Specialized;
8616 else {
8617 auto *ND = cast<NamedDecl>(Val: SpecializedContext);
8618 int Diag = diag::err_template_spec_redecl_out_of_scope;
8619 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8620 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8621 S.Diag(Loc, DiagID: Diag) << EntityKind << Specialized
8622 << ND << isa<CXXRecordDecl>(Val: ND);
8623 }
8624
8625 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8626
8627 // Don't allow specializing in the wrong class during error recovery.
8628 // Otherwise, things can go horribly wrong.
8629 if (DC->isRecord())
8630 return true;
8631 }
8632
8633 return false;
8634}
8635
8636static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8637 if (!E->isTypeDependent())
8638 return SourceLocation();
8639 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8640 Checker.TraverseStmt(S: E);
8641 if (Checker.MatchLoc.isInvalid())
8642 return E->getSourceRange();
8643 return Checker.MatchLoc;
8644}
8645
8646static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8647 if (!TL.getType()->isDependentType())
8648 return SourceLocation();
8649 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8650 Checker.TraverseTypeLoc(TL);
8651 if (Checker.MatchLoc.isInvalid())
8652 return TL.getSourceRange();
8653 return Checker.MatchLoc;
8654}
8655
8656/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8657/// that checks non-type template partial specialization arguments.
8658static bool CheckNonTypeTemplatePartialSpecializationArgs(
8659 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8660 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8661 bool HasError = false;
8662 for (unsigned I = 0; I != NumArgs; ++I) {
8663 if (Args[I].getKind() == TemplateArgument::Pack) {
8664 if (CheckNonTypeTemplatePartialSpecializationArgs(
8665 S, TemplateNameLoc, Param, Args: Args[I].pack_begin(),
8666 NumArgs: Args[I].pack_size(), IsDefaultArgument))
8667 return true;
8668
8669 continue;
8670 }
8671
8672 if (Args[I].getKind() != TemplateArgument::Expression)
8673 continue;
8674
8675 Expr *ArgExpr = Args[I].getAsExpr();
8676 if (ArgExpr->containsErrors()) {
8677 HasError = true;
8678 continue;
8679 }
8680
8681 // We can have a pack expansion of any of the bullets below.
8682 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: ArgExpr))
8683 ArgExpr = Expansion->getPattern();
8684
8685 // Strip off any implicit casts we added as part of type checking.
8686 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
8687 ArgExpr = ICE->getSubExpr();
8688
8689 // C++ [temp.class.spec]p8:
8690 // A non-type argument is non-specialized if it is the name of a
8691 // non-type parameter. All other non-type arguments are
8692 // specialized.
8693 //
8694 // Below, we check the two conditions that only apply to
8695 // specialized non-type arguments, so skip any non-specialized
8696 // arguments.
8697 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ArgExpr))
8698 if (isa<NonTypeTemplateParmDecl>(Val: DRE->getDecl()))
8699 continue;
8700
8701 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ArgExpr);
8702 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8703 continue;
8704 }
8705
8706 // C++ [temp.class.spec]p9:
8707 // Within the argument list of a class template partial
8708 // specialization, the following restrictions apply:
8709 // -- A partially specialized non-type argument expression
8710 // shall not involve a template parameter of the partial
8711 // specialization except when the argument expression is a
8712 // simple identifier.
8713 // -- The type of a template parameter corresponding to a
8714 // specialized non-type argument shall not be dependent on a
8715 // parameter of the specialization.
8716 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8717 // We implement a compromise between the original rules and DR1315:
8718 // -- A specialized non-type template argument shall not be
8719 // type-dependent and the corresponding template parameter
8720 // shall have a non-dependent type.
8721 SourceRange ParamUseRange =
8722 findTemplateParameterInType(Depth: Param->getDepth(), E: ArgExpr);
8723 if (ParamUseRange.isValid()) {
8724 if (IsDefaultArgument) {
8725 S.Diag(Loc: TemplateNameLoc,
8726 DiagID: diag::err_dependent_non_type_arg_in_partial_spec);
8727 S.Diag(Loc: ParamUseRange.getBegin(),
8728 DiagID: diag::note_dependent_non_type_default_arg_in_partial_spec)
8729 << ParamUseRange;
8730 } else {
8731 S.Diag(Loc: ParamUseRange.getBegin(),
8732 DiagID: diag::err_dependent_non_type_arg_in_partial_spec)
8733 << ParamUseRange;
8734 }
8735 return true;
8736 }
8737
8738 ParamUseRange = findTemplateParameter(
8739 Depth: Param->getDepth(), TL: Param->getTypeSourceInfo()->getTypeLoc());
8740 if (ParamUseRange.isValid()) {
8741 S.Diag(Loc: IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8742 DiagID: diag::err_dependent_typed_non_type_arg_in_partial_spec)
8743 << Param->getType();
8744 S.NoteTemplateParameterLocation(Decl: *Param);
8745 return true;
8746 }
8747 }
8748
8749 return HasError;
8750}
8751
8752bool Sema::CheckTemplatePartialSpecializationArgs(
8753 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8754 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8755 // We have to be conservative when checking a template in a dependent
8756 // context.
8757 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8758 return false;
8759
8760 TemplateParameterList *TemplateParams =
8761 PrimaryTemplate->getTemplateParameters();
8762 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8763 NonTypeTemplateParmDecl *Param
8764 = dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: I));
8765 if (!Param)
8766 continue;
8767
8768 if (CheckNonTypeTemplatePartialSpecializationArgs(S&: *this, TemplateNameLoc,
8769 Param, Args: &TemplateArgs[I],
8770 NumArgs: 1, IsDefaultArgument: I >= NumExplicit))
8771 return true;
8772 }
8773
8774 return false;
8775}
8776
8777DeclResult Sema::ActOnClassTemplateSpecialization(
8778 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8779 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8780 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8781 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8782 assert(TUK != TagUseKind::Reference && "References are not specializations");
8783
8784 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8785 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8786 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8787
8788 // Find the class template we're specializing
8789 TemplateName Name = TemplateId.Template.get();
8790 ClassTemplateDecl *ClassTemplate
8791 = dyn_cast_or_null<ClassTemplateDecl>(Val: Name.getAsTemplateDecl());
8792
8793 if (!ClassTemplate) {
8794 Diag(Loc: TemplateNameLoc, DiagID: diag::err_not_class_template_specialization)
8795 << (Name.getAsTemplateDecl() &&
8796 isa<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl()));
8797 return true;
8798 }
8799
8800 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8801 auto Message = DSA->getMessage();
8802 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
8803 << ClassTemplate << !Message.empty() << Message;
8804 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
8805 }
8806
8807 if (S->isTemplateParamScope())
8808 EnterTemplatedContext(S, DC: ClassTemplate->getTemplatedDecl());
8809
8810 DeclContext *DC = ClassTemplate->getDeclContext();
8811
8812 bool isMemberSpecialization = false;
8813 bool isPartialSpecialization = false;
8814
8815 if (SS.isSet()) {
8816 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8817 diagnoseQualifiedDeclaration(SS, DC, Name: ClassTemplate->getDeclName(),
8818 Loc: TemplateNameLoc, TemplateId: &TemplateId,
8819 /*IsMemberSpecialization=*/false))
8820 return true;
8821 }
8822
8823 // Check the validity of the template headers that introduce this
8824 // template.
8825 // FIXME: We probably shouldn't complain about these headers for
8826 // friend declarations.
8827 bool Invalid = false;
8828 TemplateParameterList *TemplateParams =
8829 MatchTemplateParametersToScopeSpecifier(
8830 DeclStartLoc: KWLoc, DeclLoc: TemplateNameLoc, SS, TemplateId: &TemplateId, ParamLists: TemplateParameterLists,
8831 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
8832 if (Invalid)
8833 return true;
8834
8835 // Check that we can declare a template specialization here.
8836 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8837 return true;
8838
8839 if (TemplateParams && DC->isDependentContext()) {
8840 ContextRAII SavedContext(*this, DC);
8841 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
8842 return true;
8843 }
8844
8845 if (TemplateParams && TemplateParams->size() > 0) {
8846 isPartialSpecialization = true;
8847
8848 if (TUK == TagUseKind::Friend) {
8849 Diag(Loc: KWLoc, DiagID: diag::err_partial_specialization_friend)
8850 << SourceRange(LAngleLoc, RAngleLoc);
8851 return true;
8852 }
8853
8854 // C++ [temp.class.spec]p10:
8855 // The template parameter list of a specialization shall not
8856 // contain default template argument values.
8857 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8858 Decl *Param = TemplateParams->getParam(Idx: I);
8859 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
8860 if (TTP->hasDefaultArgument()) {
8861 Diag(Loc: TTP->getDefaultArgumentLoc(),
8862 DiagID: diag::err_default_arg_in_partial_spec);
8863 TTP->removeDefaultArgument();
8864 }
8865 } else if (NonTypeTemplateParmDecl *NTTP
8866 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
8867 if (NTTP->hasDefaultArgument()) {
8868 Diag(Loc: NTTP->getDefaultArgumentLoc(),
8869 DiagID: diag::err_default_arg_in_partial_spec)
8870 << NTTP->getDefaultArgument().getSourceRange();
8871 NTTP->removeDefaultArgument();
8872 }
8873 } else {
8874 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
8875 if (TTP->hasDefaultArgument()) {
8876 Diag(Loc: TTP->getDefaultArgument().getLocation(),
8877 DiagID: diag::err_default_arg_in_partial_spec)
8878 << TTP->getDefaultArgument().getSourceRange();
8879 TTP->removeDefaultArgument();
8880 }
8881 }
8882 }
8883 } else if (TemplateParams) {
8884 if (TUK == TagUseKind::Friend)
8885 Diag(Loc: KWLoc, DiagID: diag::err_template_spec_friend)
8886 << FixItHint::CreateRemoval(
8887 RemoveRange: SourceRange(TemplateParams->getTemplateLoc(),
8888 TemplateParams->getRAngleLoc()))
8889 << SourceRange(LAngleLoc, RAngleLoc);
8890 } else {
8891 assert(TUK == TagUseKind::Friend &&
8892 "should have a 'template<>' for this decl");
8893 }
8894
8895 // Check that the specialization uses the same tag kind as the
8896 // original template.
8897 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
8898 assert(Kind != TagTypeKind::Enum &&
8899 "Invalid enum tag in class template spec!");
8900 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(), NewTag: Kind,
8901 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
8902 Name: ClassTemplate->getIdentifier())) {
8903 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
8904 << ClassTemplate
8905 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
8906 Code: ClassTemplate->getTemplatedDecl()->getKindName());
8907 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
8908 DiagID: diag::note_previous_use);
8909 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8910 }
8911
8912 // Translate the parser's template argument list in our AST format.
8913 TemplateArgumentListInfo TemplateArgs =
8914 makeTemplateArgumentListInfo(S&: *this, TemplateId);
8915
8916 // Check for unexpanded parameter packs in any of the template arguments.
8917 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8918 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
8919 UPPC: isPartialSpecialization
8920 ? UPPC_PartialSpecialization
8921 : UPPC_ExplicitSpecialization))
8922 return true;
8923
8924 // Check that the template argument list is well-formed for this
8925 // template.
8926 CheckTemplateArgumentInfo CTAI;
8927 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
8928 /*DefaultArgs=*/{},
8929 /*PartialTemplateArgs=*/false, CTAI,
8930 /*UpdateArgsWithConversions=*/true))
8931 return true;
8932
8933 // Find the class template (partial) specialization declaration that
8934 // corresponds to these arguments.
8935 if (isPartialSpecialization) {
8936 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, PrimaryTemplate: ClassTemplate,
8937 NumExplicit: TemplateArgs.size(),
8938 TemplateArgs: CTAI.CanonicalConverted))
8939 return true;
8940
8941 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8942 // also do it during instantiation.
8943 if (!Name.isDependent() &&
8944 !TemplateSpecializationType::anyDependentTemplateArguments(
8945 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
8946 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
8947 << ClassTemplate->getDeclName();
8948 isPartialSpecialization = false;
8949 Invalid = true;
8950 }
8951 }
8952
8953 void *InsertPos = nullptr;
8954 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8955
8956 if (isPartialSpecialization)
8957 PrevDecl = ClassTemplate->findPartialSpecialization(
8958 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
8959 else
8960 PrevDecl =
8961 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
8962
8963 ClassTemplateSpecializationDecl *Specialization = nullptr;
8964
8965 // Check whether we can declare a class template specialization in
8966 // the current scope.
8967 if (TUK != TagUseKind::Friend &&
8968 CheckTemplateSpecializationScope(S&: *this, Specialized: ClassTemplate, PrevDecl,
8969 Loc: TemplateNameLoc,
8970 IsPartialSpecialization: isPartialSpecialization))
8971 return true;
8972
8973 if (!isPartialSpecialization) {
8974 // Create a new class template specialization declaration node for
8975 // this explicit specialization or friend declaration.
8976 Specialization = ClassTemplateSpecializationDecl::Create(
8977 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
8978 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
8979 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8980 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
8981 if (TemplateParameterLists.size() > 0) {
8982 Specialization->setTemplateParameterListsInfo(Context,
8983 TPLists: TemplateParameterLists);
8984 }
8985
8986 if (!PrevDecl)
8987 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
8988 } else {
8989 CanQualType CanonType = CanQualType::CreateUnsafe(
8990 Other: Context.getCanonicalTemplateSpecializationType(
8991 Keyword: ElaboratedTypeKeyword::None,
8992 T: TemplateName(ClassTemplate->getCanonicalDecl()),
8993 CanonicalArgs: CTAI.CanonicalConverted));
8994 if (Context.hasSameType(
8995 T1: CanonType,
8996 T2: ClassTemplate->getCanonicalInjectedSpecializationType(Ctx: Context)) &&
8997 (!Context.getLangOpts().CPlusPlus20 ||
8998 !TemplateParams->hasAssociatedConstraints())) {
8999 // C++ [temp.class.spec]p9b3:
9000 //
9001 // -- The argument list of the specialization shall not be identical
9002 // to the implicit argument list of the primary template.
9003 //
9004 // This rule has since been removed, because it's redundant given DR1495,
9005 // but we keep it because it produces better diagnostics and recovery.
9006 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
9007 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
9008 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
9009 return CheckClassTemplate(
9010 S, TagSpec, TUK, KWLoc, SS, Name: ClassTemplate->getIdentifier(),
9011 NameLoc: TemplateNameLoc, Attr, TemplateParams, AS: AS_none,
9012 /*ModulePrivateLoc=*/SourceLocation(),
9013 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
9014 OuterTemplateParamLists: TemplateParameterLists.data(), IsMemberSpecialization: isMemberSpecialization);
9015 }
9016
9017 // Create a new class template partial specialization declaration node.
9018 ClassTemplatePartialSpecializationDecl *PrevPartial =
9019 cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl);
9020 ClassTemplatePartialSpecializationDecl *Partial =
9021 ClassTemplatePartialSpecializationDecl::Create(
9022 Context, TK: Kind, DC, StartLoc: KWLoc, IdLoc: TemplateNameLoc, Params: TemplateParams,
9023 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, CanonInjectedTST: CanonType, PrevDecl: PrevPartial);
9024 Partial->setTemplateArgsAsWritten(TemplateArgs);
9025 SetNestedNameSpecifier(S&: *this, T: Partial, SS);
9026 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9027 Partial->setTemplateParameterListsInfo(
9028 Context, TPLists: TemplateParameterLists.drop_back(N: 1));
9029 }
9030
9031 if (!PrevPartial)
9032 ClassTemplate->AddPartialSpecialization(D: Partial, InsertPos);
9033 Specialization = Partial;
9034
9035 // If we are providing an explicit specialization of a member class
9036 // template specialization, make a note of that.
9037 if (isMemberSpecialization)
9038 Partial->setMemberSpecialization();
9039
9040 CheckTemplatePartialSpecialization(Partial);
9041 }
9042
9043 // C++ [temp.expl.spec]p6:
9044 // If a template, a member template or the member of a class template is
9045 // explicitly specialized then that specialization shall be declared
9046 // before the first use of that specialization that would cause an implicit
9047 // instantiation to take place, in every translation unit in which such a
9048 // use occurs; no diagnostic is required.
9049 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9050 bool Okay = false;
9051 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9052 // Is there any previous explicit specialization declaration?
9053 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9054 Okay = true;
9055 break;
9056 }
9057 }
9058
9059 if (!Okay) {
9060 SourceRange Range(TemplateNameLoc, RAngleLoc);
9061 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
9062 << Context.getCanonicalTagType(TD: Specialization) << Range;
9063
9064 Diag(Loc: PrevDecl->getPointOfInstantiation(),
9065 DiagID: diag::note_instantiation_required_here)
9066 << (PrevDecl->getTemplateSpecializationKind()
9067 != TSK_ImplicitInstantiation);
9068 return true;
9069 }
9070 }
9071
9072 // If this is not a friend, note that this is an explicit specialization.
9073 if (TUK != TagUseKind::Friend)
9074 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9075
9076 // Check that this isn't a redefinition of this specialization.
9077 if (TUK == TagUseKind::Definition) {
9078 RecordDecl *Def = Specialization->getDefinition();
9079 NamedDecl *Hidden = nullptr;
9080 bool HiddenDefVisible = false;
9081 if (Def && SkipBody &&
9082 isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible)) {
9083 SkipBody->ShouldSkip = true;
9084 SkipBody->Previous = Def;
9085 if (!HiddenDefVisible && Hidden)
9086 makeMergedDefinitionVisible(ND: Hidden);
9087 } else if (Def) {
9088 SourceRange Range(TemplateNameLoc, RAngleLoc);
9089 Diag(Loc: TemplateNameLoc, DiagID: diag::err_redefinition) << Specialization << Range;
9090 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
9091 Specialization->setInvalidDecl();
9092 return true;
9093 }
9094 }
9095
9096 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
9097 ProcessAPINotes(D: Specialization);
9098
9099 // Add alignment attributes if necessary; these attributes are checked when
9100 // the ASTContext lays out the structure.
9101 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9102 if (LangOpts.HLSL)
9103 Specialization->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
9104 AddAlignmentAttributesForRecord(RD: Specialization);
9105 AddMsStructLayoutForRecord(RD: Specialization);
9106 }
9107
9108 if (ModulePrivateLoc.isValid())
9109 Diag(Loc: Specialization->getLocation(), DiagID: diag::err_module_private_specialization)
9110 << (isPartialSpecialization? 1 : 0)
9111 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
9112
9113 // C++ [temp.expl.spec]p9:
9114 // A template explicit specialization is in the scope of the
9115 // namespace in which the template was defined.
9116 //
9117 // We actually implement this paragraph where we set the semantic
9118 // context (in the creation of the ClassTemplateSpecializationDecl),
9119 // but we also maintain the lexical context where the actual
9120 // definition occurs.
9121 Specialization->setLexicalDeclContext(CurContext);
9122
9123 // We may be starting the definition of this specialization.
9124 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9125 Specialization->startDefinition();
9126
9127 if (TUK == TagUseKind::Friend) {
9128 CanQualType CanonType = Context.getCanonicalTagType(TD: Specialization);
9129 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9130 Keyword: ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9131 QualifierLoc: SS.getWithLocInContext(Context),
9132 /*TemplateKeywordLoc=*/SourceLocation(), T: Name, TLoc: TemplateNameLoc,
9133 SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted, Canon: CanonType);
9134
9135 // Build the fully-sugared type for this class template
9136 // specialization as the user wrote in the specialization
9137 // itself. This means that we'll pretty-print the type retrieved
9138 // from the specialization's declaration the way that the user
9139 // actually wrote the specialization, rather than formatting the
9140 // name based on the "canonical" representation used to store the
9141 // template arguments in the specialization.
9142 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext,
9143 L: TemplateNameLoc,
9144 Friend_: WrittenTy,
9145 /*FIXME:*/FriendL: KWLoc);
9146 Friend->setAccess(AS_public);
9147 CurContext->addDecl(D: Friend);
9148 } else {
9149 // Add the specialization into its lexical context, so that it can
9150 // be seen when iterating through the list of declarations in that
9151 // context. However, specializations are not found by name lookup.
9152 CurContext->addDecl(D: Specialization);
9153 }
9154
9155 if (SkipBody && SkipBody->ShouldSkip)
9156 return SkipBody->Previous;
9157
9158 Specialization->setInvalidDecl(Invalid);
9159 inferGslOwnerPointerAttribute(Record: Specialization);
9160 return Specialization;
9161}
9162
9163Decl *Sema::ActOnTemplateDeclarator(Scope *S,
9164 MultiTemplateParamsArg TemplateParameterLists,
9165 Declarator &D) {
9166 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9167 ActOnDocumentableDecl(D: NewDecl);
9168 return NewDecl;
9169}
9170
9171ConceptDecl *Sema::ActOnStartConceptDefinition(
9172 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9173 const IdentifierInfo *Name, SourceLocation NameLoc) {
9174 DeclContext *DC = CurContext;
9175
9176 if (!DC->getRedeclContext()->isFileContext()) {
9177 Diag(Loc: NameLoc,
9178 DiagID: diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9179 return nullptr;
9180 }
9181
9182 if (TemplateParameterLists.size() > 1) {
9183 Diag(Loc: NameLoc, DiagID: diag::err_concept_extra_headers);
9184 return nullptr;
9185 }
9186
9187 TemplateParameterList *Params = TemplateParameterLists.front();
9188
9189 if (Params->size() == 0) {
9190 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_parameters);
9191 return nullptr;
9192 }
9193
9194 // Ensure that the parameter pack, if present, is the last parameter in the
9195 // template.
9196 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9197 ParamEnd = Params->end();
9198 ParamIt != ParamEnd; ++ParamIt) {
9199 Decl const *Param = *ParamIt;
9200 if (Param->isParameterPack()) {
9201 if (++ParamIt == ParamEnd)
9202 break;
9203 Diag(Loc: Param->getLocation(),
9204 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
9205 return nullptr;
9206 }
9207 }
9208
9209 ConceptDecl *NewDecl =
9210 ConceptDecl::Create(C&: Context, DC, L: NameLoc, Name, Params);
9211
9212 if (NewDecl->hasAssociatedConstraints()) {
9213 // C++2a [temp.concept]p4:
9214 // A concept shall not have associated constraints.
9215 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_associated_constraints);
9216 NewDecl->setInvalidDecl();
9217 }
9218
9219 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9220 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9221 forRedeclarationInCurContext());
9222 LookupName(R&: Previous, S);
9223 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9224 /*AllowInlineNamespace*/ false);
9225
9226 // We cannot properly handle redeclarations until we parse the constraint
9227 // expression, so only inject the name if we are sure we are not redeclaring a
9228 // symbol
9229 if (Previous.empty())
9230 PushOnScopeChains(D: NewDecl, S, AddToContext: true);
9231
9232 return NewDecl;
9233}
9234
9235static bool RemoveLookupResult(LookupResult &R, NamedDecl *C) {
9236 bool Found = false;
9237 LookupResult::Filter F = R.makeFilter();
9238 while (F.hasNext()) {
9239 NamedDecl *D = F.next();
9240 if (D == C) {
9241 F.erase();
9242 Found = true;
9243 break;
9244 }
9245 }
9246 F.done();
9247 return Found;
9248}
9249
9250ConceptDecl *
9251Sema::ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
9252 Expr *ConstraintExpr,
9253 const ParsedAttributesView &Attrs) {
9254 assert(!C->hasDefinition() && "Concept already defined");
9255 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr)) {
9256 C->setInvalidDecl();
9257 return nullptr;
9258 }
9259 C->setDefinition(ConstraintExpr);
9260 ProcessDeclAttributeList(S, D: C, AttrList: Attrs);
9261
9262 // Check for conflicting previous declaration.
9263 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9264 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9265 forRedeclarationInCurContext());
9266 LookupName(R&: Previous, S);
9267 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9268 /*AllowInlineNamespace*/ false);
9269 bool WasAlreadyAdded = RemoveLookupResult(R&: Previous, C);
9270 bool AddToScope = true;
9271 CheckConceptRedefinition(NewDecl: C, Previous, AddToScope);
9272
9273 ActOnDocumentableDecl(D: C);
9274 if (!WasAlreadyAdded && AddToScope)
9275 PushOnScopeChains(D: C, S);
9276
9277 return C;
9278}
9279
9280void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
9281 LookupResult &Previous, bool &AddToScope) {
9282 AddToScope = true;
9283
9284 if (Previous.empty())
9285 return;
9286
9287 auto *OldConcept = dyn_cast<ConceptDecl>(Val: Previous.getRepresentativeDecl()->getUnderlyingDecl());
9288 if (!OldConcept) {
9289 auto *Old = Previous.getRepresentativeDecl();
9290 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_kind)
9291 << NewDecl->getDeclName();
9292 notePreviousDefinition(Old, New: NewDecl->getLocation());
9293 AddToScope = false;
9294 return;
9295 }
9296 // Check if we can merge with a concept declaration.
9297 bool IsSame = Context.isSameEntity(X: NewDecl, Y: OldConcept);
9298 if (!IsSame) {
9299 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_concept)
9300 << NewDecl->getDeclName();
9301 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9302 AddToScope = false;
9303 return;
9304 }
9305 if (hasReachableDefinition(D: OldConcept) &&
9306 IsRedefinitionInModule(New: NewDecl, Old: OldConcept)) {
9307 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition)
9308 << NewDecl->getDeclName();
9309 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9310 AddToScope = false;
9311 return;
9312 }
9313 if (!Previous.isSingleResult()) {
9314 // FIXME: we should produce an error in case of ambig and failed lookups.
9315 // Other decls (e.g. namespaces) also have this shortcoming.
9316 return;
9317 }
9318 // We unwrap canonical decl late to check for module visibility.
9319 Context.setPrimaryMergedDecl(D: NewDecl, Primary: OldConcept->getCanonicalDecl());
9320}
9321
9322bool Sema::CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc) {
9323 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Val: Concept);
9324 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9325 Diag(Loc, DiagID: diag::err_recursive_concept) << CE;
9326 Diag(Loc: CE->getLocation(), DiagID: diag::note_declared_at);
9327 CE->setInvalidDecl();
9328 return true;
9329 }
9330 // Concept template parameters don't have a definition and can't
9331 // be defined recursively.
9332 return false;
9333}
9334
9335/// \brief Strips various properties off an implicit instantiation
9336/// that has just been explicitly specialized.
9337static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9338 if (MinGW || (isa<FunctionDecl>(Val: D) &&
9339 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization()))
9340 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9341
9342 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D))
9343 FD->setInlineSpecified(false);
9344}
9345
9346/// Create an ExplicitInstantiationDecl to record source-location info for an
9347/// explicit template instantiation statement, and add it to \p CurContext.
9348///
9349/// For class templates / nested classes, the caller should build a
9350/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9351/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9352///
9353/// For function / variable templates, the caller should pass TypeAsWritten for
9354/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9355static void addExplicitInstantiationDecl(
9356 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9357 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9358 NestedNameSpecifierLoc QualifierLoc,
9359 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9360 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9361 auto *EID = ExplicitInstantiationDecl::Create(
9362 C&: Context, DC: CurContext, Specialization: Spec, ExternLoc, TemplateLoc, QualifierLoc,
9363 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9364 Context.addExplicitInstantiationDecl(Spec, EID);
9365 CurContext->addDecl(D: EID);
9366}
9367
9368/// Compute the diagnostic location for an explicit instantiation
9369// declaration or definition.
9370static SourceLocation
9371DiagLocForExplicitInstantiation(NamedDecl *D,
9372 SourceLocation PointOfInstantiation) {
9373 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(Spec: D))
9374 if (EID->getTemplateSpecializationKind() ==
9375 TSK_ExplicitInstantiationDefinition)
9376 return EID->getTemplateLoc();
9377
9378 // Explicit instantiations following a specialization have no effect and
9379 // hence no PointOfInstantiation. In that case, walk decl backwards
9380 // until a valid name loc is found.
9381 SourceLocation PrevDiagLoc = PointOfInstantiation;
9382 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9383 Prev = Prev->getPreviousDecl()) {
9384 PrevDiagLoc = Prev->getLocation();
9385 }
9386 assert(PrevDiagLoc.isValid() &&
9387 "Explicit instantiation without point of instantiation?");
9388 return PrevDiagLoc;
9389}
9390
9391bool
9392Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9393 TemplateSpecializationKind NewTSK,
9394 NamedDecl *PrevDecl,
9395 TemplateSpecializationKind PrevTSK,
9396 SourceLocation PrevPointOfInstantiation,
9397 bool &HasNoEffect) {
9398 HasNoEffect = false;
9399
9400 switch (NewTSK) {
9401 case TSK_Undeclared:
9402 case TSK_ImplicitInstantiation:
9403 assert(
9404 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9405 "previous declaration must be implicit!");
9406 return false;
9407
9408 case TSK_ExplicitSpecialization:
9409 switch (PrevTSK) {
9410 case TSK_Undeclared:
9411 case TSK_ExplicitSpecialization:
9412 // Okay, we're just specializing something that is either already
9413 // explicitly specialized or has merely been mentioned without any
9414 // instantiation.
9415 return false;
9416
9417 case TSK_ImplicitInstantiation:
9418 if (PrevPointOfInstantiation.isInvalid()) {
9419 // The declaration itself has not actually been instantiated, so it is
9420 // still okay to specialize it.
9421 StripImplicitInstantiation(
9422 D: PrevDecl, MinGW: Context.getTargetInfo().getTriple().isOSCygMing());
9423 return false;
9424 }
9425 // Fall through
9426 [[fallthrough]];
9427
9428 case TSK_ExplicitInstantiationDeclaration:
9429 case TSK_ExplicitInstantiationDefinition:
9430 assert((PrevTSK == TSK_ImplicitInstantiation ||
9431 PrevPointOfInstantiation.isValid()) &&
9432 "Explicit instantiation without point of instantiation?");
9433
9434 // C++ [temp.expl.spec]p6:
9435 // If a template, a member template or the member of a class template
9436 // is explicitly specialized then that specialization shall be declared
9437 // before the first use of that specialization that would cause an
9438 // implicit instantiation to take place, in every translation unit in
9439 // which such a use occurs; no diagnostic is required.
9440 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9441 // Is there any previous explicit specialization declaration?
9442 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization)
9443 return false;
9444 }
9445
9446 Diag(Loc: NewLoc, DiagID: diag::err_specialization_after_instantiation)
9447 << PrevDecl;
9448 Diag(Loc: PrevPointOfInstantiation, DiagID: diag::note_instantiation_required_here)
9449 << (PrevTSK != TSK_ImplicitInstantiation);
9450
9451 return true;
9452 }
9453 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9454
9455 case TSK_ExplicitInstantiationDeclaration:
9456 switch (PrevTSK) {
9457 case TSK_ExplicitInstantiationDeclaration:
9458 // This explicit instantiation declaration is redundant (that's okay).
9459 HasNoEffect = true;
9460 return false;
9461
9462 case TSK_Undeclared:
9463 case TSK_ImplicitInstantiation:
9464 // We're explicitly instantiating something that may have already been
9465 // implicitly instantiated; that's fine.
9466 return false;
9467
9468 case TSK_ExplicitSpecialization:
9469 // C++0x [temp.explicit]p4:
9470 // For a given set of template parameters, if an explicit instantiation
9471 // of a template appears after a declaration of an explicit
9472 // specialization for that template, the explicit instantiation has no
9473 // effect.
9474 HasNoEffect = true;
9475 return false;
9476
9477 case TSK_ExplicitInstantiationDefinition:
9478 // C++0x [temp.explicit]p10:
9479 // If an entity is the subject of both an explicit instantiation
9480 // declaration and an explicit instantiation definition in the same
9481 // translation unit, the definition shall follow the declaration.
9482 Diag(Loc: NewLoc,
9483 DiagID: diag::err_explicit_instantiation_declaration_after_definition);
9484
9485 // Explicit instantiations following a specialization have no effect and
9486 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9487 // until a valid name loc is found.
9488 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9489 DiagID: diag::note_explicit_instantiation_definition_here);
9490 HasNoEffect = true;
9491 return false;
9492 }
9493 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9494
9495 case TSK_ExplicitInstantiationDefinition:
9496 switch (PrevTSK) {
9497 case TSK_Undeclared:
9498 case TSK_ImplicitInstantiation:
9499 // We're explicitly instantiating something that may have already been
9500 // implicitly instantiated; that's fine.
9501 return false;
9502
9503 case TSK_ExplicitSpecialization:
9504 // C++ DR 259, C++0x [temp.explicit]p4:
9505 // For a given set of template parameters, if an explicit
9506 // instantiation of a template appears after a declaration of
9507 // an explicit specialization for that template, the explicit
9508 // instantiation has no effect.
9509 Diag(Loc: NewLoc, DiagID: diag::warn_explicit_instantiation_after_specialization)
9510 << PrevDecl;
9511 Diag(Loc: PrevDecl->getLocation(),
9512 DiagID: diag::note_previous_template_specialization);
9513 HasNoEffect = true;
9514 return false;
9515
9516 case TSK_ExplicitInstantiationDeclaration:
9517 // We're explicitly instantiating a definition for something for which we
9518 // were previously asked to suppress instantiations. That's fine.
9519
9520 // C++0x [temp.explicit]p4:
9521 // For a given set of template parameters, if an explicit instantiation
9522 // of a template appears after a declaration of an explicit
9523 // specialization for that template, the explicit instantiation has no
9524 // effect.
9525 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9526 // Is there any previous explicit specialization declaration?
9527 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9528 HasNoEffect = true;
9529 break;
9530 }
9531 }
9532
9533 return false;
9534
9535 case TSK_ExplicitInstantiationDefinition:
9536 // C++0x [temp.spec]p5:
9537 // For a given template and a given set of template-arguments,
9538 // - an explicit instantiation definition shall appear at most once
9539 // in a program,
9540
9541 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9542 Diag(Loc: NewLoc, DiagID: (getLangOpts().MSVCCompat)
9543 ? diag::ext_explicit_instantiation_duplicate
9544 : diag::err_explicit_instantiation_duplicate)
9545 << PrevDecl;
9546 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9547 DiagID: diag::note_previous_explicit_instantiation);
9548 HasNoEffect = true;
9549 return false;
9550 }
9551 }
9552
9553 llvm_unreachable("Missing specialization/instantiation case?");
9554}
9555
9556bool Sema::CheckDependentFunctionTemplateSpecialization(
9557 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9558 LookupResult &Previous) {
9559 // Remove anything from Previous that isn't a function template in
9560 // the correct context.
9561 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9562 LookupResult::Filter F = Previous.makeFilter();
9563 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9564 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9565 while (F.hasNext()) {
9566 NamedDecl *D = F.next()->getUnderlyingDecl();
9567 if (!isa<FunctionTemplateDecl>(Val: D)) {
9568 F.erase();
9569 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAFunctionTemplate, y&: D));
9570 continue;
9571 }
9572
9573 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9574 NS: D->getDeclContext()->getRedeclContext())) {
9575 F.erase();
9576 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAMemberOfEnclosing, y&: D));
9577 continue;
9578 }
9579 }
9580 F.done();
9581
9582 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9583 if (Previous.empty()) {
9584 Diag(Loc: FD->getLocation(), DiagID: diag::err_dependent_function_template_spec_no_match)
9585 << IsFriend;
9586 for (auto &P : DiscardedCandidates)
9587 Diag(Loc: P.second->getLocation(),
9588 DiagID: diag::note_dependent_function_template_spec_discard_reason)
9589 << P.first << IsFriend;
9590 return true;
9591 }
9592
9593 FD->setDependentTemplateSpecialization(Context, Templates: Previous.asUnresolvedSet(),
9594 TemplateArgs: ExplicitTemplateArgs);
9595 return false;
9596}
9597
9598bool Sema::CheckFunctionTemplateSpecialization(
9599 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9600 LookupResult &Previous, bool QualifiedFriend) {
9601 // The set of function template specializations that could match this
9602 // explicit function template specialization.
9603 UnresolvedSet<8> Candidates;
9604 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9605 /*ForTakingAddress=*/false);
9606
9607 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9608 ConvertedTemplateArgs;
9609
9610 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9611 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9612 I != E; ++I) {
9613 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9614 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Ovl)) {
9615 // Only consider templates found within the same semantic lookup scope as
9616 // FD.
9617 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9618 NS: Ovl->getDeclContext()->getRedeclContext()))
9619 continue;
9620
9621 QualType FT = FD->getType();
9622 // C++11 [dcl.constexpr]p8:
9623 // A constexpr specifier for a non-static member function that is not
9624 // a constructor declares that member function to be const.
9625 //
9626 // When matching a constexpr member function template specialization
9627 // against the primary template, we don't yet know whether the
9628 // specialization has an implicit 'const' (because we don't know whether
9629 // it will be a static member function until we know which template it
9630 // specializes). This rule was removed in C++14.
9631 if (auto *NewMD = dyn_cast<CXXMethodDecl>(Val: FD);
9632 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9633 !isa<CXXConstructorDecl, CXXDestructorDecl>(Val: NewMD)) {
9634 auto *OldMD = dyn_cast<CXXMethodDecl>(Val: FunTmpl->getTemplatedDecl());
9635 if (OldMD && OldMD->isConst()) {
9636 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9637 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9638 EPI.TypeQuals.addConst();
9639 FT = Context.getFunctionType(ResultTy: FPT->getReturnType(),
9640 Args: FPT->getParamTypes(), EPI);
9641 }
9642 }
9643
9644 TemplateArgumentListInfo Args;
9645 if (ExplicitTemplateArgs)
9646 Args = *ExplicitTemplateArgs;
9647
9648 // C++ [temp.expl.spec]p11:
9649 // A trailing template-argument can be left unspecified in the
9650 // template-id naming an explicit function template specialization
9651 // provided it can be deduced from the function argument type.
9652 // Perform template argument deduction to determine whether we may be
9653 // specializing this template.
9654 // FIXME: It is somewhat wasteful to build
9655 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9656 FunctionDecl *Specialization = nullptr;
9657 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9658 FunctionTemplate: cast<FunctionTemplateDecl>(Val: FunTmpl->getFirstDecl()),
9659 ExplicitTemplateArgs: ExplicitTemplateArgs ? &Args : nullptr, ArgFunctionType: FT, Specialization, Info);
9660 TDK != TemplateDeductionResult::Success) {
9661 // Template argument deduction failed; record why it failed, so
9662 // that we can provide nifty diagnostics.
9663 FailedCandidates.addCandidate().set(
9664 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9665 Info: MakeDeductionFailureInfo(Context, TDK, Info));
9666 (void)TDK;
9667 continue;
9668 }
9669
9670 // Target attributes are part of the cuda function signature, so
9671 // the deduced template's cuda target must match that of the
9672 // specialization. Given that C++ template deduction does not
9673 // take target attributes into account, we reject candidates
9674 // here that have a different target.
9675 if (LangOpts.CUDA &&
9676 CUDA().IdentifyTarget(D: Specialization,
9677 /* IgnoreImplicitHDAttr = */ true) !=
9678 CUDA().IdentifyTarget(D: FD, /* IgnoreImplicitHDAttr = */ true)) {
9679 FailedCandidates.addCandidate().set(
9680 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9681 Info: MakeDeductionFailureInfo(
9682 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
9683 continue;
9684 }
9685
9686 // Record this candidate.
9687 if (ExplicitTemplateArgs)
9688 ConvertedTemplateArgs[Specialization] = std::move(Args);
9689 Candidates.addDecl(D: Specialization, AS: I.getAccess());
9690 }
9691 }
9692
9693 // For a qualified friend declaration (with no explicit marker to indicate
9694 // that a template specialization was intended), note all (template and
9695 // non-template) candidates.
9696 if (QualifiedFriend && Candidates.empty()) {
9697 Diag(Loc: FD->getLocation(), DiagID: diag::err_qualified_friend_no_match)
9698 << FD->getDeclName() << FDLookupContext;
9699 // FIXME: We should form a single candidate list and diagnose all
9700 // candidates at once, to get proper sorting and limiting.
9701 for (auto *OldND : Previous) {
9702 if (auto *OldFD = dyn_cast<FunctionDecl>(Val: OldND->getUnderlyingDecl()))
9703 NoteOverloadCandidate(Found: OldND, Fn: OldFD, RewriteKind: CRK_None, DestType: FD->getType(), TakingAddress: false);
9704 }
9705 FailedCandidates.NoteCandidates(S&: *this, Loc: FD->getLocation());
9706 return true;
9707 }
9708
9709 // Find the most specialized function template.
9710 UnresolvedSetIterator Result = getMostSpecialized(
9711 SBegin: Candidates.begin(), SEnd: Candidates.end(), FailedCandidates, Loc: FD->getLocation(),
9712 NoneDiag: PDiag(DiagID: diag::err_function_template_spec_no_match) << FD->getDeclName(),
9713 AmbigDiag: PDiag(DiagID: diag::err_function_template_spec_ambiguous)
9714 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9715 CandidateDiag: PDiag(DiagID: diag::note_function_template_spec_matched));
9716
9717 if (Result == Candidates.end())
9718 return true;
9719
9720 // Ignore access information; it doesn't figure into redeclaration checking.
9721 FunctionDecl *Specialization = cast<FunctionDecl>(Val: *Result);
9722
9723 if (const auto *PT = Specialization->getPrimaryTemplate();
9724 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9725 auto Message = DSA->getMessage();
9726 Diag(Loc: FD->getLocation(), DiagID: diag::warn_invalid_specialization)
9727 << PT << !Message.empty() << Message;
9728 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
9729 }
9730
9731 // C++23 [except.spec]p13:
9732 // An exception specification is considered to be needed when:
9733 // - [...]
9734 // - the exception specification is compared to that of another declaration
9735 // (e.g., an explicit specialization or an overriding virtual function);
9736 // - [...]
9737 //
9738 // The exception specification of a defaulted function is evaluated as
9739 // described above only when needed; similarly, the noexcept-specifier of a
9740 // specialization of a function template or member function of a class
9741 // template is instantiated only when needed.
9742 //
9743 // The standard doesn't specify what the "comparison with another declaration"
9744 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9745 // not state which properties of an explicit specialization must match the
9746 // primary template.
9747 //
9748 // We assume that an explicit specialization must correspond with (per
9749 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9750 // the declaration produced by substitution into the function template.
9751 //
9752 // Since the determination whether two function declarations correspond does
9753 // not consider exception specification, we only need to instantiate it once
9754 // we determine the primary template when comparing types per
9755 // [basic.link]p11.1.
9756 auto *SpecializationFPT =
9757 Specialization->getType()->castAs<FunctionProtoType>();
9758 // If the function has a dependent exception specification, resolve it after
9759 // we have selected the primary template so we can check whether it matches.
9760 if (getLangOpts().CPlusPlus17 &&
9761 isUnresolvedExceptionSpec(ESpecType: SpecializationFPT->getExceptionSpecType()) &&
9762 !ResolveExceptionSpec(Loc: FD->getLocation(), FPT: SpecializationFPT))
9763 return true;
9764
9765 FunctionTemplateSpecializationInfo *SpecInfo
9766 = Specialization->getTemplateSpecializationInfo();
9767 assert(SpecInfo && "Function template specialization info missing?");
9768
9769 // Note: do not overwrite location info if previous template
9770 // specialization kind was explicit.
9771 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9772 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9773 Specialization->setLocation(FD->getLocation());
9774 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9775 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9776 // function can differ from the template declaration with respect to
9777 // the constexpr specifier.
9778 // FIXME: We need an update record for this AST mutation.
9779 // FIXME: What if there are multiple such prior declarations (for instance,
9780 // from different modules)?
9781 Specialization->setConstexprKind(FD->getConstexprKind());
9782 }
9783
9784 // FIXME: Check if the prior specialization has a point of instantiation.
9785 // If so, we have run afoul of .
9786
9787 // If this is a friend declaration, then we're not really declaring
9788 // an explicit specialization.
9789 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9790
9791 // Check the scope of this explicit specialization.
9792 if (!isFriend &&
9793 CheckTemplateSpecializationScope(S&: *this,
9794 Specialized: Specialization->getPrimaryTemplate(),
9795 PrevDecl: Specialization, Loc: FD->getLocation(),
9796 IsPartialSpecialization: false))
9797 return true;
9798
9799 // C++ [temp.expl.spec]p6:
9800 // If a template, a member template or the member of a class template is
9801 // explicitly specialized then that specialization shall be declared
9802 // before the first use of that specialization that would cause an implicit
9803 // instantiation to take place, in every translation unit in which such a
9804 // use occurs; no diagnostic is required.
9805 bool HasNoEffect = false;
9806 if (!isFriend &&
9807 CheckSpecializationInstantiationRedecl(NewLoc: FD->getLocation(),
9808 NewTSK: TSK_ExplicitSpecialization,
9809 PrevDecl: Specialization,
9810 PrevTSK: SpecInfo->getTemplateSpecializationKind(),
9811 PrevPointOfInstantiation: SpecInfo->getPointOfInstantiation(),
9812 HasNoEffect))
9813 return true;
9814
9815 // Mark the prior declaration as an explicit specialization, so that later
9816 // clients know that this is an explicit specialization.
9817 // A dependent friend specialization which has a definition should be treated
9818 // as explicit specialization, despite being invalid.
9819 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9820 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9821 // Since explicit specializations do not inherit '=delete' from their
9822 // primary function template - check if the 'specialization' that was
9823 // implicitly generated (during template argument deduction for partial
9824 // ordering) from the most specialized of all the function templates that
9825 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9826 // first check that it was implicitly generated during template argument
9827 // deduction by making sure it wasn't referenced, and then reset the deleted
9828 // flag to not-deleted, so that we can inherit that information from 'FD'.
9829 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9830 !Specialization->getCanonicalDecl()->isReferenced()) {
9831 // FIXME: This assert will not hold in the presence of modules.
9832 assert(
9833 Specialization->getCanonicalDecl() == Specialization &&
9834 "This must be the only existing declaration of this specialization");
9835 // FIXME: We need an update record for this AST mutation.
9836 Specialization->setDeletedAsWritten(D: false);
9837 }
9838 // FIXME: We need an update record for this AST mutation.
9839 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9840 MarkUnusedFileScopedDecl(D: Specialization);
9841 }
9842
9843 // Turn the given function declaration into a function template
9844 // specialization, with the template arguments from the previous
9845 // specialization.
9846 // Take copies of (semantic and syntactic) template argument lists.
9847 TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
9848 Context, Args: Specialization->getTemplateSpecializationArgs()->asArray());
9849 FD->setFunctionTemplateSpecialization(
9850 Template: Specialization->getPrimaryTemplate(), TemplateArgs: TemplArgs, /*InsertPos=*/nullptr,
9851 TSK: SpecInfo->getTemplateSpecializationKind(),
9852 TemplateArgsAsWritten: ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9853
9854 // A function template specialization inherits the target attributes
9855 // of its template. (We require the attributes explicitly in the
9856 // code to match, but a template may have implicit attributes by
9857 // virtue e.g. of being constexpr, and it passes these implicit
9858 // attributes on to its specializations.)
9859 if (LangOpts.CUDA)
9860 CUDA().inheritTargetAttrs(FD, TD: *Specialization->getPrimaryTemplate());
9861
9862 // The "previous declaration" for this function template specialization is
9863 // the prior function template specialization.
9864 Previous.clear();
9865 Previous.addDecl(D: Specialization);
9866 return false;
9867}
9868
9869bool
9870Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9871 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9872 "Only for non-template members");
9873
9874 // Try to find the member we are instantiating.
9875 NamedDecl *FoundInstantiation = nullptr;
9876 NamedDecl *Instantiation = nullptr;
9877 NamedDecl *InstantiatedFrom = nullptr;
9878 MemberSpecializationInfo *MSInfo = nullptr;
9879
9880 if (Previous.empty()) {
9881 // Nowhere to look anyway.
9882 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Member)) {
9883 UnresolvedSet<8> Candidates;
9884 for (NamedDecl *Candidate : Previous) {
9885 auto *Method = dyn_cast<CXXMethodDecl>(Val: Candidate->getUnderlyingDecl());
9886 // Ignore any candidates that aren't member functions.
9887 if (!Method)
9888 continue;
9889
9890 QualType Adjusted = Function->getType();
9891 if (!hasExplicitCallingConv(T: Adjusted))
9892 Adjusted = adjustCCAndNoReturn(ArgFunctionType: Adjusted, FunctionType: Method->getType());
9893 // Ignore any candidates with the wrong type.
9894 // This doesn't handle deduced return types, but both function
9895 // declarations should be undeduced at this point.
9896 // FIXME: The exception specification should probably be ignored when
9897 // comparing the types.
9898 if (!Context.hasSameType(T1: Adjusted, T2: Method->getType()))
9899 continue;
9900
9901 // Ignore any candidates with unsatisfied constraints.
9902 if (ConstraintSatisfaction Satisfaction;
9903 Method->getTrailingRequiresClause() &&
9904 (CheckFunctionConstraints(FD: Method, Satisfaction,
9905 /*UsageLoc=*/Member->getLocation(),
9906 /*ForOverloadResolution=*/true) ||
9907 !Satisfaction.IsSatisfied))
9908 continue;
9909
9910 Candidates.addDecl(D: Candidate);
9911 }
9912
9913 // If we have no viable candidates left after filtering, we are done.
9914 if (Candidates.empty())
9915 return false;
9916
9917 // Find the function that is more constrained than every other function it
9918 // has been compared to.
9919 UnresolvedSetIterator Best = Candidates.begin();
9920 CXXMethodDecl *BestMethod = nullptr;
9921 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9922 I != E; ++I) {
9923 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9924 if (I == Best ||
9925 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) == Method) {
9926 Best = I;
9927 BestMethod = Method;
9928 }
9929 }
9930
9931 FoundInstantiation = *Best;
9932 Instantiation = BestMethod;
9933 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9934 MSInfo = BestMethod->getMemberSpecializationInfo();
9935
9936 // Make sure the best candidate is more constrained than all of the others.
9937 bool Ambiguous = false;
9938 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9939 I != E; ++I) {
9940 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9941 if (I != Best &&
9942 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) != BestMethod) {
9943 Ambiguous = true;
9944 break;
9945 }
9946 }
9947
9948 if (Ambiguous) {
9949 Diag(Loc: Member->getLocation(), DiagID: diag::err_function_member_spec_ambiguous)
9950 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9951 for (NamedDecl *Candidate : Candidates) {
9952 Candidate = Candidate->getUnderlyingDecl();
9953 Diag(Loc: Candidate->getLocation(), DiagID: diag::note_function_member_spec_matched)
9954 << Candidate;
9955 }
9956 return true;
9957 }
9958 } else if (isa<VarDecl>(Val: Member)) {
9959 VarDecl *PrevVar;
9960 if (Previous.isSingleResult() &&
9961 (PrevVar = dyn_cast<VarDecl>(Val: Previous.getFoundDecl())))
9962 if (PrevVar->isStaticDataMember()) {
9963 FoundInstantiation = Previous.getRepresentativeDecl();
9964 Instantiation = PrevVar;
9965 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9966 MSInfo = PrevVar->getMemberSpecializationInfo();
9967 }
9968 } else if (isa<RecordDecl>(Val: Member)) {
9969 CXXRecordDecl *PrevRecord;
9970 if (Previous.isSingleResult() &&
9971 (PrevRecord = dyn_cast<CXXRecordDecl>(Val: Previous.getFoundDecl()))) {
9972 FoundInstantiation = Previous.getRepresentativeDecl();
9973 Instantiation = PrevRecord;
9974 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9975 MSInfo = PrevRecord->getMemberSpecializationInfo();
9976 }
9977 } else if (isa<EnumDecl>(Val: Member)) {
9978 EnumDecl *PrevEnum;
9979 if (Previous.isSingleResult() &&
9980 (PrevEnum = dyn_cast<EnumDecl>(Val: Previous.getFoundDecl()))) {
9981 FoundInstantiation = Previous.getRepresentativeDecl();
9982 Instantiation = PrevEnum;
9983 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9984 MSInfo = PrevEnum->getMemberSpecializationInfo();
9985 }
9986 }
9987
9988 if (!Instantiation) {
9989 // There is no previous declaration that matches. Since member
9990 // specializations are always out-of-line, the caller will complain about
9991 // this mismatch later.
9992 return false;
9993 }
9994
9995 // A member specialization in a friend declaration isn't really declaring
9996 // an explicit specialization, just identifying a specific (possibly implicit)
9997 // specialization. Don't change the template specialization kind.
9998 //
9999 // FIXME: Is this really valid? Other compilers reject.
10000 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10001 // Preserve instantiation information.
10002 if (InstantiatedFrom && isa<CXXMethodDecl>(Val: Member)) {
10003 cast<CXXMethodDecl>(Val: Member)->setInstantiationOfMemberFunction(
10004 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom),
10005 TSK: cast<CXXMethodDecl>(Val: Instantiation)->getTemplateSpecializationKind());
10006 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Val: Member)) {
10007 cast<CXXRecordDecl>(Val: Member)->setInstantiationOfMemberClass(
10008 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom),
10009 TSK: cast<CXXRecordDecl>(Val: Instantiation)->getTemplateSpecializationKind());
10010 }
10011
10012 Previous.clear();
10013 Previous.addDecl(D: FoundInstantiation);
10014 return false;
10015 }
10016
10017 // Make sure that this is a specialization of a member.
10018 if (!InstantiatedFrom) {
10019 Diag(Loc: Member->getLocation(), DiagID: diag::err_spec_member_not_instantiated)
10020 << Member;
10021 Diag(Loc: Instantiation->getLocation(), DiagID: diag::note_specialized_decl);
10022 return true;
10023 }
10024
10025 // C++ [temp.expl.spec]p6:
10026 // If a template, a member template or the member of a class template is
10027 // explicitly specialized then that specialization shall be declared
10028 // before the first use of that specialization that would cause an implicit
10029 // instantiation to take place, in every translation unit in which such a
10030 // use occurs; no diagnostic is required.
10031 assert(MSInfo && "Member specialization info missing?");
10032
10033 bool HasNoEffect = false;
10034 if (CheckSpecializationInstantiationRedecl(NewLoc: Member->getLocation(),
10035 NewTSK: TSK_ExplicitSpecialization,
10036 PrevDecl: Instantiation,
10037 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10038 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10039 HasNoEffect))
10040 return true;
10041
10042 // Check the scope of this explicit specialization.
10043 if (CheckTemplateSpecializationScope(S&: *this,
10044 Specialized: InstantiatedFrom,
10045 PrevDecl: Instantiation, Loc: Member->getLocation(),
10046 IsPartialSpecialization: false))
10047 return true;
10048
10049 // Note that this member specialization is an "instantiation of" the
10050 // corresponding member of the original template.
10051 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Val: Member)) {
10052 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Val: Instantiation);
10053 if (InstantiationFunction->getTemplateSpecializationKind() ==
10054 TSK_ImplicitInstantiation) {
10055 // Explicit specializations of member functions of class templates do not
10056 // inherit '=delete' from the member function they are specializing.
10057 if (InstantiationFunction->isDeleted()) {
10058 // FIXME: This assert will not hold in the presence of modules.
10059 assert(InstantiationFunction->getCanonicalDecl() ==
10060 InstantiationFunction);
10061 // FIXME: We need an update record for this AST mutation.
10062 InstantiationFunction->setDeletedAsWritten(D: false);
10063 }
10064 }
10065
10066 MemberFunction->setInstantiationOfMemberFunction(
10067 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10068 } else if (auto *MemberVar = dyn_cast<VarDecl>(Val: Member)) {
10069 MemberVar->setInstantiationOfStaticDataMember(
10070 VD: cast<VarDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10071 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
10072 MemberClass->setInstantiationOfMemberClass(
10073 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10074 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Val: Member)) {
10075 MemberEnum->setInstantiationOfMemberEnum(
10076 ED: cast<EnumDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10077 } else {
10078 llvm_unreachable("unknown member specialization kind");
10079 }
10080
10081 // Save the caller the trouble of having to figure out which declaration
10082 // this specialization matches.
10083 Previous.clear();
10084 Previous.addDecl(D: FoundInstantiation);
10085 return false;
10086}
10087
10088/// Complete the explicit specialization of a member of a class template by
10089/// updating the instantiated member to be marked as an explicit specialization.
10090///
10091/// \param OrigD The member declaration instantiated from the template.
10092/// \param Loc The location of the explicit specialization of the member.
10093template<typename DeclT>
10094static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10095 SourceLocation Loc) {
10096 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10097 return;
10098
10099 // FIXME: Inform AST mutation listeners of this AST mutation.
10100 // FIXME: If there are multiple in-class declarations of the member (from
10101 // multiple modules, or a declaration and later definition of a member type),
10102 // should we update all of them?
10103 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10104 OrigD->setLocation(Loc);
10105}
10106
10107void Sema::CompleteMemberSpecialization(NamedDecl *Member,
10108 LookupResult &Previous) {
10109 NamedDecl *Instantiation = cast<NamedDecl>(Val: Member->getCanonicalDecl());
10110 if (Instantiation == Member)
10111 return;
10112
10113 if (auto *Function = dyn_cast<CXXMethodDecl>(Val: Instantiation))
10114 completeMemberSpecializationImpl(S&: *this, OrigD: Function, Loc: Member->getLocation());
10115 else if (auto *Var = dyn_cast<VarDecl>(Val: Instantiation))
10116 completeMemberSpecializationImpl(S&: *this, OrigD: Var, Loc: Member->getLocation());
10117 else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: Instantiation))
10118 completeMemberSpecializationImpl(S&: *this, OrigD: Record, Loc: Member->getLocation());
10119 else if (auto *Enum = dyn_cast<EnumDecl>(Val: Instantiation))
10120 completeMemberSpecializationImpl(S&: *this, OrigD: Enum, Loc: Member->getLocation());
10121 else
10122 llvm_unreachable("unknown member specialization kind");
10123}
10124
10125/// Check the scope of an explicit instantiation.
10126///
10127/// \returns true if a serious error occurs, false otherwise.
10128static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
10129 SourceLocation InstLoc,
10130 bool WasQualifiedName) {
10131 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
10132 DeclContext *CurContext = S.CurContext->getRedeclContext();
10133
10134 if (CurContext->isRecord()) {
10135 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_in_class)
10136 << D;
10137 return true;
10138 }
10139
10140 // C++11 [temp.explicit]p3:
10141 // An explicit instantiation shall appear in an enclosing namespace of its
10142 // template. If the name declared in the explicit instantiation is an
10143 // unqualified name, the explicit instantiation shall appear in the
10144 // namespace where its template is declared or, if that namespace is inline
10145 // (7.3.1), any namespace from its enclosing namespace set.
10146 //
10147 // This is DR275, which we do not retroactively apply to C++98/03.
10148 if (WasQualifiedName) {
10149 if (CurContext->Encloses(DC: OrigContext))
10150 return false;
10151 } else {
10152 if (CurContext->InEnclosingNamespaceSetOf(NS: OrigContext))
10153 return false;
10154 }
10155
10156 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: OrigContext)) {
10157 if (WasQualifiedName)
10158 S.Diag(Loc: InstLoc,
10159 DiagID: S.getLangOpts().CPlusPlus11?
10160 diag::err_explicit_instantiation_out_of_scope :
10161 diag::warn_explicit_instantiation_out_of_scope_0x)
10162 << D << NS;
10163 else
10164 S.Diag(Loc: InstLoc,
10165 DiagID: S.getLangOpts().CPlusPlus11?
10166 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10167 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10168 << D << NS;
10169 } else
10170 S.Diag(Loc: InstLoc,
10171 DiagID: S.getLangOpts().CPlusPlus11?
10172 diag::err_explicit_instantiation_must_be_global :
10173 diag::warn_explicit_instantiation_must_be_global_0x)
10174 << D;
10175 S.Diag(Loc: D->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10176 return false;
10177}
10178
10179/// Common checks for whether an explicit instantiation of \p D is valid.
10180static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
10181 SourceLocation InstLoc,
10182 bool WasQualifiedName,
10183 TemplateSpecializationKind TSK) {
10184 // C++ [temp.explicit]p13:
10185 // An explicit instantiation declaration shall not name a specialization of
10186 // a template with internal linkage.
10187 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10188 D->getFormalLinkage() == Linkage::Internal) {
10189 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_internal_linkage) << D;
10190 return true;
10191 }
10192
10193 // C++11 [temp.explicit]p3: [DR 275]
10194 // An explicit instantiation shall appear in an enclosing namespace of its
10195 // template.
10196 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10197 return true;
10198
10199 return false;
10200}
10201
10202/// Determine whether the given scope specifier has a template-id in it.
10203static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
10204 // C++11 [temp.explicit]p3:
10205 // If the explicit instantiation is for a member function, a member class
10206 // or a static data member of a class template specialization, the name of
10207 // the class template specialization in the qualified-id for the member
10208 // name shall be a simple-template-id.
10209 //
10210 // C++98 has the same restriction, just worded differently.
10211 for (NestedNameSpecifier NNS = SS.getScopeRep();
10212 NNS.getKind() == NestedNameSpecifier::Kind::Type;
10213 /**/) {
10214 const Type *T = NNS.getAsType();
10215 if (isa<TemplateSpecializationType>(Val: T))
10216 return true;
10217 NNS = T->getPrefix();
10218 }
10219 return false;
10220}
10221
10222/// Make a dllexport or dllimport attr on a class template specialization take
10223/// effect.
10224static void dllExportImportClassTemplateSpecialization(
10225 Sema &S, ClassTemplateSpecializationDecl *Def) {
10226 auto *A = cast_or_null<InheritableAttr>(Val: getDLLAttr(D: Def));
10227 assert(A && "dllExportImportClassTemplateSpecialization called "
10228 "on Def without dllexport or dllimport");
10229
10230 // We reject explicit instantiations in class scope, so there should
10231 // never be any delayed exported classes to worry about.
10232 assert(S.DelayedDllExportClasses.empty() &&
10233 "delayed exports present at explicit instantiation");
10234 S.checkClassLevelDLLAttribute(Class: Def);
10235
10236 // Propagate attribute to base class templates.
10237 for (auto &B : Def->bases()) {
10238 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10239 Val: B.getType()->getAsCXXRecordDecl()))
10240 S.propagateDLLAttrToBaseClassTemplate(Class: Def, ClassAttr: A, BaseTemplateSpec: BT, BaseLoc: B.getBeginLoc());
10241 }
10242
10243 S.referenceDLLExportedClassMethods();
10244}
10245
10246DeclResult Sema::ActOnExplicitInstantiation(
10247 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10248 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10249 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10250 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10251 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10252 // Find the class template we're specializing
10253 TemplateName Name = TemplateD.get();
10254 TemplateDecl *TD = Name.getAsTemplateDecl();
10255 // Check that the specialization uses the same tag kind as the
10256 // original template.
10257 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10258 assert(Kind != TagTypeKind::Enum &&
10259 "Invalid enum tag in class template explicit instantiation!");
10260
10261 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: TD);
10262
10263 if (!ClassTemplate) {
10264 NonTagKind NTK = getNonTagTypeDeclKind(D: TD, TTK: Kind);
10265 Diag(Loc: TemplateNameLoc, DiagID: diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10266 Diag(Loc: TD->getLocation(), DiagID: diag::note_previous_use);
10267 return true;
10268 }
10269
10270 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(),
10271 NewTag: Kind, /*isDefinition*/false, NewTagLoc: KWLoc,
10272 Name: ClassTemplate->getIdentifier())) {
10273 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
10274 << ClassTemplate
10275 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
10276 Code: ClassTemplate->getTemplatedDecl()->getKindName());
10277 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
10278 DiagID: diag::note_previous_use);
10279 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10280 }
10281
10282 // C++0x [temp.explicit]p2:
10283 // There are two forms of explicit instantiation: an explicit instantiation
10284 // definition and an explicit instantiation declaration. An explicit
10285 // instantiation declaration begins with the extern keyword. [...]
10286 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10287 ? TSK_ExplicitInstantiationDefinition
10288 : TSK_ExplicitInstantiationDeclaration;
10289
10290 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10291 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10292 // Check for dllexport class template instantiation declarations,
10293 // except for MinGW mode.
10294 for (const ParsedAttr &AL : Attr) {
10295 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10296 Diag(Loc: ExternLoc,
10297 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10298 Diag(Loc: AL.getLoc(), DiagID: diag::note_attribute);
10299 break;
10300 }
10301 }
10302
10303 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10304 Diag(Loc: ExternLoc,
10305 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10306 Diag(Loc: A->getLocation(), DiagID: diag::note_attribute);
10307 }
10308 }
10309
10310 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10311 // instantiation declarations for most purposes.
10312 bool DLLImportExplicitInstantiationDef = false;
10313 if (TSK == TSK_ExplicitInstantiationDefinition &&
10314 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10315 // Check for dllimport class template instantiation definitions.
10316 bool DLLImport =
10317 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10318 for (const ParsedAttr &AL : Attr) {
10319 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10320 DLLImport = true;
10321 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10322 // dllexport trumps dllimport here.
10323 DLLImport = false;
10324 break;
10325 }
10326 }
10327 if (DLLImport) {
10328 TSK = TSK_ExplicitInstantiationDeclaration;
10329 DLLImportExplicitInstantiationDef = true;
10330 }
10331 }
10332
10333 // Translate the parser's template argument list in our AST format.
10334 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10335 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10336
10337 // Check that the template argument list is well-formed for this
10338 // template.
10339 CheckTemplateArgumentInfo CTAI;
10340 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
10341 /*DefaultArgs=*/{}, PartialTemplateArgs: false, CTAI,
10342 /*UpdateArgsWithConversions=*/true,
10343 /*ConstraintsNotSatisfied=*/nullptr))
10344 return true;
10345
10346 // Find the class template specialization declaration that
10347 // corresponds to these arguments.
10348 void *InsertPos = nullptr;
10349 ClassTemplateSpecializationDecl *PrevDecl =
10350 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
10351
10352 TemplateSpecializationKind PrevDecl_TSK
10353 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10354
10355 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10356 Context.getTargetInfo().getTriple().isOSCygMing()) {
10357 // Check for dllexport class template instantiation definitions in MinGW
10358 // mode, if a previous declaration of the instantiation was seen.
10359 for (const ParsedAttr &AL : Attr) {
10360 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10361 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10362 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attr_dllexport_explicit_inst_def);
10363 } else {
10364 Diag(Loc: AL.getLoc(),
10365 DiagID: diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10366 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_prev_decl_missing_dllexport);
10367 }
10368 break;
10369 }
10370 }
10371 }
10372
10373 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10374 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10375 llvm::none_of(Range: Attr, P: [](const ParsedAttr &AL) {
10376 return AL.getKind() == ParsedAttr::AT_DLLExport;
10377 })) {
10378 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10379 Diag(Loc: TemplateLoc, DiagID: diag::warn_dllexport_on_decl_ignored);
10380 Diag(Loc: DEA->getLoc(), DiagID: diag::note_dllexport_on_decl);
10381 }
10382 }
10383
10384 if (CheckExplicitInstantiation(S&: *this, D: ClassTemplate, InstLoc: TemplateNameLoc,
10385 WasQualifiedName: SS.isSet(), TSK))
10386 return true;
10387
10388 ClassTemplateSpecializationDecl *Specialization = nullptr;
10389
10390 bool HasNoEffect = false;
10391 if (PrevDecl) {
10392 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateNameLoc, NewTSK: TSK,
10393 PrevDecl, PrevTSK: PrevDecl_TSK,
10394 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
10395 HasNoEffect))
10396 return PrevDecl;
10397
10398 // Even though HasNoEffect == true means that this explicit instantiation
10399 // has no effect on semantics, we go on to put its syntax in the AST.
10400
10401 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10402 PrevDecl_TSK == TSK_Undeclared) {
10403 // Since the only prior class template specialization with these
10404 // arguments was referenced but not declared, reuse that
10405 // declaration node as our own, updating the source location
10406 // for the template name to reflect our new declaration.
10407 // (Other source locations will be updated later.)
10408 Specialization = PrevDecl;
10409 Specialization->setLocation(TemplateNameLoc);
10410 PrevDecl = nullptr;
10411 }
10412
10413 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10414 DLLImportExplicitInstantiationDef) {
10415 // The new specialization might add a dllimport attribute.
10416 HasNoEffect = false;
10417 }
10418 }
10419
10420 if (!Specialization) {
10421 // Create a new class template specialization declaration node for
10422 // this explicit specialization.
10423 Specialization = ClassTemplateSpecializationDecl::Create(
10424 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
10425 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
10426 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
10427
10428 // A MSInheritanceAttr attached to the previous declaration must be
10429 // propagated to the new node prior to instantiation.
10430 if (PrevDecl) {
10431 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10432 auto *Clone = A->clone(C&: getASTContext());
10433 Clone->setInherited(true);
10434 Specialization->addAttr(A: Clone);
10435 Consumer.AssignInheritanceModel(RD: Specialization);
10436 }
10437 }
10438
10439 if (!HasNoEffect && !PrevDecl) {
10440 // Insert the new specialization.
10441 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
10442 }
10443 }
10444
10445 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10446
10447 // Set source locations for keywords.
10448 Specialization->setExternKeywordLoc(ExternLoc);
10449 Specialization->setTemplateKeywordLoc(TemplateLoc);
10450 Specialization->setBraceRange(SourceRange());
10451
10452 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10453 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
10454 ProcessAPINotes(D: Specialization);
10455
10456 // Add the explicit instantiation into its lexical context. However,
10457 // since explicit instantiations are never found by name lookup, we
10458 // just put it into the declaration context directly.
10459 Specialization->setLexicalDeclContext(CurContext);
10460 CurContext->addDecl(D: Specialization);
10461
10462 // Syntax is now OK, so return if it has no other effect on semantics.
10463 if (HasNoEffect) {
10464 // Set the template specialization kind.
10465 Specialization->setTemplateSpecializationKind(TSK);
10466
10467 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
10468 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10469 Keyword: KW, ElaboratedKeywordLoc: KWLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: SourceLocation(), T: Name,
10470 TLoc: TemplateNameLoc, SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted,
10471 Canon: Context.getCanonicalTagType(TD: Specialization));
10472 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
10473 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10474 NameLoc: TemplateNameLoc, TypeAsWritten: TSI, TSK);
10475 return Specialization;
10476 }
10477
10478 // C++ [temp.explicit]p3:
10479 // A definition of a class template or class member template
10480 // shall be in scope at the point of the explicit instantiation of
10481 // the class template or class member template.
10482 //
10483 // This check comes when we actually try to perform the
10484 // instantiation.
10485 ClassTemplateSpecializationDecl *Def
10486 = cast_or_null<ClassTemplateSpecializationDecl>(
10487 Val: Specialization->getDefinition());
10488 if (!Def)
10489 InstantiateClassTemplateSpecialization(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Specialization, TSK,
10490 /*Complain=*/true,
10491 PrimaryStrictPackMatch: CTAI.StrictPackMatch);
10492 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10493 MarkVTableUsed(Loc: TemplateNameLoc, Class: Specialization, DefinitionRequired: true);
10494 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10495 }
10496
10497 // Instantiate the members of this class template specialization.
10498 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10499 Val: Specialization->getDefinition());
10500 if (Def) {
10501 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10502 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10503 // TSK_ExplicitInstantiationDefinition
10504 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10505 (TSK == TSK_ExplicitInstantiationDefinition ||
10506 DLLImportExplicitInstantiationDef)) {
10507 // FIXME: Need to notify the ASTMutationListener that we did this.
10508 Def->setTemplateSpecializationKind(TSK);
10509
10510 if (!getDLLAttr(D: Def) && getDLLAttr(D: Specialization) &&
10511 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10512 // An explicit instantiation definition can add a dll attribute to a
10513 // template with a previous instantiation declaration. MinGW doesn't
10514 // allow this.
10515 auto *A = cast<InheritableAttr>(
10516 Val: getDLLAttr(D: Specialization)->clone(C&: getASTContext()));
10517 A->setInherited(true);
10518 Def->addAttr(A);
10519 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10520 }
10521 }
10522
10523 // Fix a TSK_ImplicitInstantiation followed by a
10524 // TSK_ExplicitInstantiationDefinition
10525 bool NewlyDLLExported =
10526 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10527 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10528 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10529 // An explicit instantiation definition can add a dll attribute to a
10530 // template with a previous implicit instantiation. MinGW doesn't allow
10531 // this. We limit clang to only adding dllexport, to avoid potentially
10532 // strange codegen behavior. For example, if we extend this conditional
10533 // to dllimport, and we have a source file calling a method on an
10534 // implicitly instantiated template class instance and then declaring a
10535 // dllimport explicit instantiation definition for the same template
10536 // class, the codegen for the method call will not respect the dllimport,
10537 // while it will with cl. The Def will already have the DLL attribute,
10538 // since the Def and Specialization will be the same in the case of
10539 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10540 // attribute to the Specialization; we just need to make it take effect.
10541 assert(Def == Specialization &&
10542 "Def and Specialization should match for implicit instantiation");
10543 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10544 }
10545
10546 // In MinGW mode, export the template instantiation if the declaration
10547 // was marked dllexport.
10548 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10549 Context.getTargetInfo().getTriple().isOSCygMing() &&
10550 PrevDecl->hasAttr<DLLExportAttr>()) {
10551 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10552 }
10553
10554 // Set the template specialization kind. Make sure it is set before
10555 // instantiating the members which will trigger ASTConsumer callbacks.
10556 Specialization->setTemplateSpecializationKind(TSK);
10557 InstantiateClassTemplateSpecializationMembers(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Def, TSK);
10558 } else {
10559
10560 // Set the template specialization kind.
10561 Specialization->setTemplateSpecializationKind(TSK);
10562 }
10563
10564 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
10565 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10566 Keyword: KW, ElaboratedKeywordLoc: KWLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: SourceLocation(), T: Name,
10567 TLoc: TemplateNameLoc, SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted,
10568 Canon: Context.getCanonicalTagType(TD: Specialization));
10569 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
10570 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10571 NameLoc: TemplateNameLoc, TypeAsWritten: TSI, TSK);
10572 return Specialization;
10573}
10574
10575DeclResult
10576Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10577 SourceLocation TemplateLoc, unsigned TagSpec,
10578 SourceLocation KWLoc, CXXScopeSpec &SS,
10579 IdentifierInfo *Name, SourceLocation NameLoc,
10580 const ParsedAttributesView &Attr) {
10581
10582 bool Owned = false;
10583 bool IsDependent = false;
10584 Decl *TagD =
10585 ActOnTag(S, TagSpec, TUK: TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10586 Attr, AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10587 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent, ScopedEnumKWLoc: SourceLocation(),
10588 ScopedEnumUsesClassTag: false, UnderlyingType: TypeResult(), /*IsTypeSpecifier*/ false,
10589 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10590 .get();
10591 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10592
10593 if (!TagD)
10594 return true;
10595
10596 TagDecl *Tag = cast<TagDecl>(Val: TagD);
10597 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10598
10599 if (Tag->isInvalidDecl())
10600 return true;
10601
10602 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: Tag);
10603 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10604 if (!Pattern) {
10605 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_nontemplate_type)
10606 << Context.getCanonicalTagType(TD: Record);
10607 Diag(Loc: Record->getLocation(), DiagID: diag::note_nontemplate_decl_here);
10608 return true;
10609 }
10610
10611 // C++0x [temp.explicit]p2:
10612 // If the explicit instantiation is for a class or member class, the
10613 // elaborated-type-specifier in the declaration shall include a
10614 // simple-template-id.
10615 //
10616 // C++98 has the same restriction, just worded differently.
10617 if (!ScopeSpecifierHasTemplateId(SS))
10618 Diag(Loc: TemplateLoc, DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10619 << Record << SS.getRange();
10620
10621 // C++0x [temp.explicit]p2:
10622 // There are two forms of explicit instantiation: an explicit instantiation
10623 // definition and an explicit instantiation declaration. An explicit
10624 // instantiation declaration begins with the extern keyword. [...]
10625 TemplateSpecializationKind TSK
10626 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10627 : TSK_ExplicitInstantiationDeclaration;
10628
10629 CheckExplicitInstantiation(S&: *this, D: Record, InstLoc: NameLoc, WasQualifiedName: true, TSK);
10630
10631 // Verify that it is okay to explicitly instantiate here.
10632 CXXRecordDecl *PrevDecl
10633 = cast_or_null<CXXRecordDecl>(Val: Record->getPreviousDecl());
10634 if (!PrevDecl && Record->getDefinition())
10635 PrevDecl = Record;
10636 if (PrevDecl) {
10637 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10638 bool HasNoEffect = false;
10639 assert(MSInfo && "No member specialization information?");
10640 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateLoc, NewTSK: TSK,
10641 PrevDecl,
10642 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10643 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10644 HasNoEffect))
10645 return true;
10646 if (HasNoEffect) {
10647 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10648 ElaboratedTypeKeyword KW =
10649 TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
10650 QualType TagTy = Context.getTagType(Keyword: KW, Qualifier: SS.getScopeRep(), TD: Record, OwnsTag: false);
10651 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T: TagTy);
10652 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10653 TL.setElaboratedKeywordLoc(KWLoc);
10654 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10655 TL.setNameLoc(NameLoc);
10656 addExplicitInstantiationDecl(Context, CurContext, Spec: Record, ExternLoc,
10657 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(),
10658 ArgsAsWritten: nullptr, NameLoc, TypeAsWritten: TSI, TSK);
10659 return TagD;
10660 }
10661 }
10662
10663 CXXRecordDecl *RecordDef
10664 = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10665 if (!RecordDef) {
10666 // C++ [temp.explicit]p3:
10667 // A definition of a member class of a class template shall be in scope
10668 // at the point of an explicit instantiation of the member class.
10669 CXXRecordDecl *Def
10670 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
10671 if (!Def) {
10672 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_undefined_member)
10673 << 0 << Record->getDeclName() << Record->getDeclContext();
10674 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_forward_declaration)
10675 << Pattern;
10676 return true;
10677 } else {
10678 if (InstantiateClass(PointOfInstantiation: NameLoc, Instantiation: Record, Pattern: Def,
10679 TemplateArgs: getTemplateInstantiationArgs(D: Record),
10680 TSK))
10681 return true;
10682
10683 RecordDef = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10684 if (!RecordDef)
10685 return true;
10686 }
10687 }
10688
10689 // Instantiate all of the members of the class.
10690 InstantiateClassMembers(PointOfInstantiation: NameLoc, Instantiation: RecordDef,
10691 TemplateArgs: getTemplateInstantiationArgs(D: Record), TSK);
10692
10693 if (TSK == TSK_ExplicitInstantiationDefinition)
10694 MarkVTableUsed(Loc: NameLoc, Class: RecordDef, DefinitionRequired: true);
10695
10696 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10697 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
10698 QualType TagTy = Context.getTagType(Keyword: KW, Qualifier: SS.getScopeRep(), TD: Record, OwnsTag: false);
10699 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T: TagTy);
10700 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10701 TL.setElaboratedKeywordLoc(KWLoc);
10702 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10703 TL.setNameLoc(NameLoc);
10704 addExplicitInstantiationDecl(Context, CurContext, Spec: Record, ExternLoc,
10705 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10706 NameLoc, TypeAsWritten: TSI, TSK);
10707 return TagD;
10708}
10709
10710DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10711 SourceLocation ExternLoc,
10712 SourceLocation TemplateLoc,
10713 Declarator &D) {
10714 // Explicit instantiations always require a name.
10715 // TODO: check if/when DNInfo should replace Name.
10716 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10717 DeclarationName Name = NameInfo.getName();
10718 if (!Name) {
10719 if (!D.isInvalidType())
10720 Diag(Loc: D.getDeclSpec().getBeginLoc(),
10721 DiagID: diag::err_explicit_instantiation_requires_name)
10722 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10723
10724 return true;
10725 }
10726
10727 // Get the innermost enclosing declaration scope.
10728 S = S->getDeclParent();
10729
10730 // Determine the type of the declaration.
10731 TypeSourceInfo *T = GetTypeForDeclarator(D);
10732 QualType R = T->getType();
10733 if (R.isNull())
10734 return true;
10735
10736 // C++ [dcl.stc]p1:
10737 // A storage-class-specifier shall not be specified in [...] an explicit
10738 // instantiation (14.7.2) directive.
10739 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10740 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_of_typedef)
10741 << Name;
10742 return true;
10743 } else if (D.getDeclSpec().getStorageClassSpec()
10744 != DeclSpec::SCS_unspecified) {
10745 // Complain about then remove the storage class specifier.
10746 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_storage_class)
10747 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10748
10749 D.getMutableDeclSpec().ClearStorageClassSpecs();
10750 }
10751
10752 // C++0x [temp.explicit]p1:
10753 // [...] An explicit instantiation of a function template shall not use the
10754 // inline or constexpr specifiers.
10755 // Presumably, this also applies to member functions of class templates as
10756 // well.
10757 if (D.getDeclSpec().isInlineSpecified())
10758 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10759 DiagID: getLangOpts().CPlusPlus11 ?
10760 diag::err_explicit_instantiation_inline :
10761 diag::warn_explicit_instantiation_inline_0x)
10762 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10763 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10764 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10765 // not already specified.
10766 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10767 DiagID: diag::err_explicit_instantiation_constexpr);
10768
10769 // A deduction guide is not on the list of entities that can be explicitly
10770 // instantiated.
10771 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10772 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
10773 << /*explicit instantiation*/ 0;
10774 return true;
10775 }
10776
10777 // C++0x [temp.explicit]p2:
10778 // There are two forms of explicit instantiation: an explicit instantiation
10779 // definition and an explicit instantiation declaration. An explicit
10780 // instantiation declaration begins with the extern keyword. [...]
10781 TemplateSpecializationKind TSK
10782 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10783 : TSK_ExplicitInstantiationDeclaration;
10784
10785 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10786 LookupParsedName(R&: Previous, S, SS: &D.getCXXScopeSpec(),
10787 /*ObjectType=*/QualType());
10788
10789 if (!R->isFunctionType()) {
10790 // C++ [temp.explicit]p1:
10791 // A [...] static data member of a class template can be explicitly
10792 // instantiated from the member definition associated with its class
10793 // template.
10794 // C++1y [temp.explicit]p1:
10795 // A [...] variable [...] template specialization can be explicitly
10796 // instantiated from its template.
10797 if (Previous.isAmbiguous())
10798 return true;
10799
10800 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10801 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10802 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10803
10804 if (!PrevTemplate) {
10805 if (!Prev || !Prev->isStaticDataMember()) {
10806 // We expect to see a static data member here.
10807 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_not_known)
10808 << Name;
10809 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10810 P != PEnd; ++P)
10811 Diag(Loc: (*P)->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10812 return true;
10813 }
10814
10815 if (!Prev->getInstantiatedFromStaticDataMember()) {
10816 // FIXME: Check for explicit specialization?
10817 Diag(Loc: D.getIdentifierLoc(),
10818 DiagID: diag::err_explicit_instantiation_data_member_not_instantiated)
10819 << Prev;
10820 Diag(Loc: Prev->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10821 // FIXME: Can we provide a note showing where this was declared?
10822 return true;
10823 }
10824 } else {
10825 // Explicitly instantiate a variable template.
10826
10827 // C++1y [dcl.spec.auto]p6:
10828 // ... A program that uses auto or decltype(auto) in a context not
10829 // explicitly allowed in this section is ill-formed.
10830 //
10831 // This includes auto-typed variable template instantiations.
10832 if (R->isUndeducedType()) {
10833 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10834 DiagID: diag::err_auto_not_allowed_var_inst);
10835 return true;
10836 }
10837
10838 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10839 // C++1y [temp.explicit]p3:
10840 // If the explicit instantiation is for a variable, the unqualified-id
10841 // in the declaration shall be a template-id.
10842 Diag(Loc: D.getIdentifierLoc(),
10843 DiagID: diag::err_explicit_instantiation_without_template_id)
10844 << PrevTemplate;
10845 Diag(Loc: PrevTemplate->getLocation(),
10846 DiagID: diag::note_explicit_instantiation_here);
10847 return true;
10848 }
10849
10850 // Translate the parser's template argument list into our AST format.
10851 TemplateArgumentListInfo TemplateArgs =
10852 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10853
10854 DeclResult Res =
10855 CheckVarTemplateId(Template: PrevTemplate, TemplateLoc, TemplateNameLoc: D.getIdentifierLoc(),
10856 TemplateArgs, /*SetWrittenArgs=*/true);
10857 if (Res.isInvalid())
10858 return true;
10859
10860 if (!Res.isUsable()) {
10861 // We somehow specified dependent template arguments in an explicit
10862 // instantiation. This should probably only happen during error
10863 // recovery.
10864 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_dependent);
10865 return true;
10866 }
10867
10868 // Ignore access control bits, we don't need them for redeclaration
10869 // checking.
10870 Prev = cast<VarDecl>(Val: Res.get());
10871 ArgsAsWritten =
10872 ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
10873 }
10874
10875 // C++0x [temp.explicit]p2:
10876 // If the explicit instantiation is for a member function, a member class
10877 // or a static data member of a class template specialization, the name of
10878 // the class template specialization in the qualified-id for the member
10879 // name shall be a simple-template-id.
10880 //
10881 // C++98 has the same restriction, just worded differently.
10882 //
10883 // This does not apply to variable template specializations, where the
10884 // template-id is in the unqualified-id instead.
10885 if (!ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()) && !PrevTemplate)
10886 Diag(Loc: D.getIdentifierLoc(),
10887 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10888 << Prev << D.getCXXScopeSpec().getRange();
10889
10890 CheckExplicitInstantiation(S&: *this, D: Prev, InstLoc: D.getIdentifierLoc(), WasQualifiedName: true, TSK);
10891
10892 // Verify that it is okay to explicitly instantiate here.
10893 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10894 SourceLocation POI = Prev->getPointOfInstantiation();
10895 bool HasNoEffect = false;
10896 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK, PrevDecl: Prev,
10897 PrevTSK, PrevPointOfInstantiation: POI, HasNoEffect))
10898 return true;
10899
10900 if (!HasNoEffect) {
10901 // Instantiate static data member or variable template.
10902 Prev->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
10903 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: Prev)) {
10904 VTSD->setExternKeywordLoc(ExternLoc);
10905 VTSD->setTemplateKeywordLoc(TemplateLoc);
10906 }
10907
10908 // Merge attributes.
10909 ProcessDeclAttributeList(S, D: Prev, AttrList: D.getDeclSpec().getAttributes());
10910 if (PrevTemplate)
10911 ProcessAPINotes(D: Prev);
10912
10913 if (TSK == TSK_ExplicitInstantiationDefinition)
10914 InstantiateVariableDefinition(PointOfInstantiation: D.getIdentifierLoc(), Var: Prev);
10915 }
10916
10917 // Check the new variable specialization against the parsed input.
10918 if (PrevTemplate && !Context.hasSameType(T1: Prev->getType(), T2: R)) {
10919 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10920 DiagID: diag::err_invalid_var_template_spec_type)
10921 << 0 << PrevTemplate << R << Prev->getType();
10922 Diag(Loc: PrevTemplate->getLocation(), DiagID: diag::note_template_declared_here)
10923 << 2 << PrevTemplate->getDeclName();
10924 return true;
10925 }
10926
10927 addExplicitInstantiationDecl(
10928 Context, CurContext, Spec: Prev, ExternLoc, TemplateLoc,
10929 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
10930 NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
10931 return (Decl *)nullptr;
10932 }
10933
10934 // If the declarator is a template-id, translate the parser's template
10935 // argument list into our AST format.
10936 bool HasExplicitTemplateArgs = false;
10937 TemplateArgumentListInfo TemplateArgs;
10938 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10939 TemplateArgs = makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10940 HasExplicitTemplateArgs = true;
10941 }
10942
10943 // C++ [temp.explicit]p1:
10944 // A [...] function [...] can be explicitly instantiated from its template.
10945 // A member function [...] of a class template can be explicitly
10946 // instantiated from the member definition associated with its class
10947 // template.
10948 UnresolvedSet<8> TemplateMatches;
10949 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10950 OverloadCandidateSet::CSK_Normal);
10951 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10952 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10953 P != PEnd; ++P) {
10954 NamedDecl *Prev = *P;
10955 if (!HasExplicitTemplateArgs) {
10956 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Prev)) {
10957 QualType Adjusted = adjustCCAndNoReturn(ArgFunctionType: R, FunctionType: Method->getType(),
10958 /*AdjustExceptionSpec*/true);
10959 if (Context.hasSameUnqualifiedType(T1: Method->getType(), T2: Adjusted)) {
10960 if (Method->getPrimaryTemplate()) {
10961 TemplateMatches.addDecl(D: Method, AS: P.getAccess());
10962 } else {
10963 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10964 C.FoundDecl = P.getPair();
10965 C.Function = Method;
10966 C.Viable = true;
10967 ConstraintSatisfaction S;
10968 if (Method->getTrailingRequiresClause() &&
10969 (CheckFunctionConstraints(FD: Method, Satisfaction&: S, UsageLoc: D.getIdentifierLoc(),
10970 /*ForOverloadResolution=*/true) ||
10971 !S.IsSatisfied)) {
10972 C.Viable = false;
10973 C.FailureKind = ovl_fail_constraints_not_satisfied;
10974 }
10975 }
10976 }
10977 }
10978 }
10979
10980 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Prev);
10981 if (!FunTmpl)
10982 continue;
10983
10984 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10985 FunctionDecl *Specialization = nullptr;
10986 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
10987 FunctionTemplate: FunTmpl, ExplicitTemplateArgs: (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), ArgFunctionType: R,
10988 Specialization, Info);
10989 TDK != TemplateDeductionResult::Success) {
10990 // Keep track of almost-matches.
10991 FailedTemplateCandidates.addCandidate().set(
10992 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
10993 Info: MakeDeductionFailureInfo(Context, TDK, Info));
10994 (void)TDK;
10995 continue;
10996 }
10997
10998 // Target attributes are part of the cuda function signature, so
10999 // the cuda target of the instantiated function must match that of its
11000 // template. Given that C++ template deduction does not take
11001 // target attributes into account, we reject candidates here that
11002 // have a different target.
11003 if (LangOpts.CUDA &&
11004 CUDA().IdentifyTarget(D: Specialization,
11005 /* IgnoreImplicitHDAttr = */ true) !=
11006 CUDA().IdentifyTarget(Attrs: D.getDeclSpec().getAttributes())) {
11007 FailedTemplateCandidates.addCandidate().set(
11008 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
11009 Info: MakeDeductionFailureInfo(
11010 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
11011 continue;
11012 }
11013
11014 TemplateMatches.addDecl(D: Specialization, AS: P.getAccess());
11015 }
11016
11017 FunctionDecl *Specialization = nullptr;
11018 if (!NonTemplateMatches.empty()) {
11019 unsigned Msg = 0;
11020 OverloadCandidateDisplayKind DisplayKind;
11021 OverloadCandidateSet::iterator Best;
11022 switch (NonTemplateMatches.BestViableFunction(S&: *this, Loc: D.getIdentifierLoc(),
11023 Best)) {
11024 case OR_Success:
11025 case OR_Deleted:
11026 Specialization = cast<FunctionDecl>(Val: Best->Function);
11027 break;
11028 case OR_Ambiguous:
11029 Msg = diag::err_explicit_instantiation_ambiguous;
11030 DisplayKind = OCD_AmbiguousCandidates;
11031 break;
11032 case OR_No_Viable_Function:
11033 Msg = diag::err_explicit_instantiation_no_candidate;
11034 DisplayKind = OCD_AllCandidates;
11035 break;
11036 }
11037 if (Msg) {
11038 PartialDiagnostic Diag = PDiag(DiagID: Msg) << Name;
11039 NonTemplateMatches.NoteCandidates(
11040 PA: PartialDiagnosticAt(D.getIdentifierLoc(), Diag), S&: *this, OCD: DisplayKind,
11041 Args: {});
11042 return true;
11043 }
11044 }
11045
11046 if (!Specialization) {
11047 // Find the most specialized function template specialization.
11048 UnresolvedSetIterator Result = getMostSpecialized(
11049 SBegin: TemplateMatches.begin(), SEnd: TemplateMatches.end(),
11050 FailedCandidates&: FailedTemplateCandidates, Loc: D.getIdentifierLoc(),
11051 NoneDiag: PDiag(DiagID: diag::err_explicit_instantiation_not_known) << Name,
11052 AmbigDiag: PDiag(DiagID: diag::err_explicit_instantiation_ambiguous) << Name,
11053 CandidateDiag: PDiag(DiagID: diag::note_explicit_instantiation_candidate));
11054
11055 if (Result == TemplateMatches.end())
11056 return true;
11057
11058 // Ignore access control bits, we don't need them for redeclaration checking.
11059 Specialization = cast<FunctionDecl>(Val: *Result);
11060 }
11061
11062 // C++11 [except.spec]p4
11063 // In an explicit instantiation an exception-specification may be specified,
11064 // but is not required.
11065 // If an exception-specification is specified in an explicit instantiation
11066 // directive, it shall be compatible with the exception-specifications of
11067 // other declarations of that function.
11068 if (auto *FPT = R->getAs<FunctionProtoType>())
11069 if (FPT->hasExceptionSpec()) {
11070 unsigned DiagID =
11071 diag::err_mismatched_exception_spec_explicit_instantiation;
11072 if (getLangOpts().MicrosoftExt)
11073 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11074 bool Result = CheckEquivalentExceptionSpec(
11075 DiagID: PDiag(DiagID) << Specialization->getType(),
11076 NoteID: PDiag(DiagID: diag::note_explicit_instantiation_here),
11077 Old: Specialization->getType()->getAs<FunctionProtoType>(),
11078 OldLoc: Specialization->getLocation(), New: FPT, NewLoc: D.getBeginLoc());
11079 // In Microsoft mode, mismatching exception specifications just cause a
11080 // warning.
11081 if (!getLangOpts().MicrosoftExt && Result)
11082 return true;
11083 }
11084
11085 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11086 Diag(Loc: D.getIdentifierLoc(),
11087 DiagID: diag::err_explicit_instantiation_member_function_not_instantiated)
11088 << Specialization
11089 << (Specialization->getTemplateSpecializationKind() ==
11090 TSK_ExplicitSpecialization);
11091 Diag(Loc: Specialization->getLocation(), DiagID: diag::note_explicit_instantiation_here);
11092 return true;
11093 }
11094
11095 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11096 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11097 PrevDecl = Specialization;
11098
11099 if (PrevDecl) {
11100 bool HasNoEffect = false;
11101 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK,
11102 PrevDecl,
11103 PrevTSK: PrevDecl->getTemplateSpecializationKind(),
11104 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
11105 HasNoEffect))
11106 return true;
11107
11108 if (HasNoEffect) {
11109 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11110 if (HasExplicitTemplateArgs)
11111 ArgsAsWritten =
11112 ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
11113 addExplicitInstantiationDecl(
11114 Context, CurContext, Spec: Specialization, ExternLoc, TemplateLoc,
11115 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11116 NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
11117 return (Decl *)nullptr;
11118 }
11119 }
11120
11121 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11122 // functions
11123 // valarray<size_t>::valarray(size_t) and
11124 // valarray<size_t>::~valarray()
11125 // that it declared to have internal linkage with the internal_linkage
11126 // attribute. Ignore the explicit instantiation declaration in this case.
11127 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11128 TSK == TSK_ExplicitInstantiationDeclaration) {
11129 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getDeclContext()))
11130 if (RD->getIdentifier() && RD->getIdentifier()->isStr(Str: "valarray") &&
11131 RD->isInStdNamespace())
11132 return (Decl*) nullptr;
11133 }
11134
11135 ProcessDeclAttributeList(S, D: Specialization, AttrList: D.getDeclSpec().getAttributes());
11136 ProcessAPINotes(D: Specialization);
11137
11138 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11139 // instantiation declarations.
11140 if (TSK == TSK_ExplicitInstantiationDefinition &&
11141 Specialization->hasAttr<DLLImportAttr>() &&
11142 Context.getTargetInfo().getCXXABI().isMicrosoft())
11143 TSK = TSK_ExplicitInstantiationDeclaration;
11144
11145 Specialization->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
11146 if (Specialization->isDefined()) {
11147 // Let the ASTConsumer know that this function has been explicitly
11148 // instantiated now, and its linkage might have changed.
11149 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Specialization));
11150 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11151 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11152 // be explicitly instantiated.
11153 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getParent());
11154 RD && RD->isLambda()) {
11155 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_lambda_explicit_temp_spec)
11156 << /*instantiation*/ 1;
11157 Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here) << RD;
11158 return (Decl *)nullptr;
11159 }
11160 InstantiateFunctionDefinition(PointOfInstantiation: D.getIdentifierLoc(), Function: Specialization);
11161 }
11162
11163 // C++0x [temp.explicit]p2:
11164 // If the explicit instantiation is for a member function, a member class
11165 // or a static data member of a class template specialization, the name of
11166 // the class template specialization in the qualified-id for the member
11167 // name shall be a simple-template-id.
11168 //
11169 // C++98 has the same restriction, just worded differently.
11170 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11171 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11172 D.getCXXScopeSpec().isSet() &&
11173 !ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()))
11174 Diag(Loc: D.getIdentifierLoc(),
11175 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
11176 << Specialization << D.getCXXScopeSpec().getRange();
11177
11178 CheckExplicitInstantiation(
11179 S&: *this,
11180 D: FunTmpl ? (NamedDecl *)FunTmpl
11181 : Specialization->getInstantiatedFromMemberFunction(),
11182 InstLoc: D.getIdentifierLoc(), WasQualifiedName: D.getCXXScopeSpec().isSet(), TSK);
11183
11184 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11185 if (HasExplicitTemplateArgs)
11186 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
11187 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
11188 TemplateLoc,
11189 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context),
11190 ArgsAsWritten, NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
11191 return (Decl *)nullptr;
11192}
11193
11194TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11195 const CXXScopeSpec &SS,
11196 const IdentifierInfo *Name,
11197 SourceLocation TagLoc,
11198 SourceLocation NameLoc) {
11199 // This has to hold, because SS is expected to be defined.
11200 assert(Name && "Expected a name in a dependent tag");
11201
11202 NestedNameSpecifier NNS = SS.getScopeRep();
11203 if (!NNS)
11204 return true;
11205
11206 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
11207
11208 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11209 Diag(Loc: NameLoc, DiagID: diag::err_dependent_tag_decl)
11210 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11211 return true;
11212 }
11213
11214 // Create the resulting type.
11215 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
11216 QualType Result = Context.getDependentNameType(Keyword: Kwd, NNS, Name);
11217
11218 // Create type-source location information for this type.
11219 TypeLocBuilder TLB;
11220 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: Result);
11221 TL.setElaboratedKeywordLoc(TagLoc);
11222 TL.setQualifierLoc(SS.getWithLocInContext(Context));
11223 TL.setNameLoc(NameLoc);
11224 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
11225}
11226
11227TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11228 const CXXScopeSpec &SS,
11229 const IdentifierInfo &II,
11230 SourceLocation IdLoc,
11231 ImplicitTypenameContext IsImplicitTypename) {
11232 if (SS.isInvalid())
11233 return true;
11234
11235 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11236 DiagCompat(Loc: TypenameLoc, CompatDiagId: diag_compat::typename_outside_of_template)
11237 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11238
11239 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11240 TypeSourceInfo *TSI = nullptr;
11241 QualType T =
11242 CheckTypenameType(Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11243 : ElaboratedTypeKeyword::None,
11244 KeywordLoc: TypenameLoc, QualifierLoc, II, IILoc: IdLoc, TSI: &TSI,
11245 /*DeducedTSTContext=*/true);
11246 if (T.isNull())
11247 return true;
11248 return CreateParsedType(T, TInfo: TSI);
11249}
11250
11251TypeResult
11252Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11253 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11254 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11255 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11256 ASTTemplateArgsPtr TemplateArgsIn,
11257 SourceLocation RAngleLoc) {
11258 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11259 Diag(Loc: TypenameLoc, DiagID: getLangOpts().CPlusPlus11
11260 ? diag::compat_cxx11_typename_outside_of_template
11261 : diag::compat_pre_cxx11_typename_outside_of_template)
11262 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11263
11264 // Strangely, non-type results are not ignored by this lookup, so the
11265 // program is ill-formed if it finds an injected-class-name.
11266 if (TypenameLoc.isValid()) {
11267 auto *LookupRD =
11268 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: false));
11269 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11270 Diag(Loc: TemplateIILoc,
11271 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
11272 << TemplateII << 0 /*injected-class-name used as template name*/
11273 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11274 }
11275 }
11276
11277 // Translate the parser's template argument list in our AST format.
11278 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11279 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11280
11281 QualType T = CheckTemplateIdType(
11282 Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11283 : ElaboratedTypeKeyword::None,
11284 Name: TemplateIn.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
11285 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11286 if (T.isNull())
11287 return true;
11288
11289 // Provide source-location information for the template specialization type.
11290 TypeLocBuilder Builder;
11291 TemplateSpecializationTypeLoc SpecTL
11292 = Builder.push<TemplateSpecializationTypeLoc>(T);
11293 SpecTL.set(ElaboratedKeywordLoc: TypenameLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
11294 NameLoc: TemplateIILoc, TAL: TemplateArgs);
11295 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11296 return CreateParsedType(T, TInfo: TSI);
11297}
11298
11299/// Determine whether this failed name lookup should be treated as being
11300/// disabled by a usage of std::enable_if.
11301static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
11302 SourceRange &CondRange, Expr *&Cond) {
11303 // We must be looking for a ::type...
11304 if (!II.isStr(Str: "type"))
11305 return false;
11306
11307 // ... within an explicitly-written template specialization...
11308 if (NNS.getNestedNameSpecifier().getKind() != NestedNameSpecifier::Kind::Type)
11309 return false;
11310
11311 // FIXME: Look through sugar.
11312 auto EnableIfTSTLoc =
11313 NNS.castAsTypeLoc().getAs<TemplateSpecializationTypeLoc>();
11314 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11315 return false;
11316 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11317
11318 // ... which names a complete class template declaration...
11319 const TemplateDecl *EnableIfDecl =
11320 EnableIfTST->getTemplateName().getAsTemplateDecl();
11321 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11322 return false;
11323
11324 // ... called "enable_if".
11325 const IdentifierInfo *EnableIfII =
11326 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11327 if (!EnableIfII || !EnableIfII->isStr(Str: "enable_if"))
11328 return false;
11329
11330 // Assume the first template argument is the condition.
11331 CondRange = EnableIfTSTLoc.getArgLoc(i: 0).getSourceRange();
11332
11333 // Dig out the condition.
11334 Cond = nullptr;
11335 if (EnableIfTSTLoc.getArgLoc(i: 0).getArgument().getKind()
11336 != TemplateArgument::Expression)
11337 return true;
11338
11339 Cond = EnableIfTSTLoc.getArgLoc(i: 0).getSourceExpression();
11340
11341 // Ignore Boolean literals; they add no value.
11342 if (isa<CXXBoolLiteralExpr>(Val: Cond->IgnoreParenCasts()))
11343 Cond = nullptr;
11344
11345 return true;
11346}
11347
11348QualType
11349Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11350 SourceLocation KeywordLoc,
11351 NestedNameSpecifierLoc QualifierLoc,
11352 const IdentifierInfo &II,
11353 SourceLocation IILoc,
11354 TypeSourceInfo **TSI,
11355 bool DeducedTSTContext) {
11356 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11357 DeducedTSTContext);
11358 if (T.isNull())
11359 return QualType();
11360
11361 TypeLocBuilder TLB;
11362 if (isa<DependentNameType>(Val: T)) {
11363 auto TL = TLB.push<DependentNameTypeLoc>(T);
11364 TL.setElaboratedKeywordLoc(KeywordLoc);
11365 TL.setQualifierLoc(QualifierLoc);
11366 TL.setNameLoc(IILoc);
11367 } else if (isa<DeducedTemplateSpecializationType>(Val: T)) {
11368 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
11369 TL.setElaboratedKeywordLoc(KeywordLoc);
11370 TL.setQualifierLoc(QualifierLoc);
11371 TL.setNameLoc(IILoc);
11372 } else if (isa<TemplateTypeParmType>(Val: T)) {
11373 // FIXME: There might be a 'typename' keyword here, but we just drop it
11374 // as it can't be represented.
11375 assert(!QualifierLoc);
11376 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11377 } else if (isa<TagType>(Val: T)) {
11378 auto TL = TLB.push<TagTypeLoc>(T);
11379 TL.setElaboratedKeywordLoc(KeywordLoc);
11380 TL.setQualifierLoc(QualifierLoc);
11381 TL.setNameLoc(IILoc);
11382 } else if (isa<TypedefType>(Val: T)) {
11383 TLB.push<TypedefTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11384 } else {
11385 TLB.push<UnresolvedUsingTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11386 }
11387 *TSI = TLB.getTypeSourceInfo(Context, T);
11388 return T;
11389}
11390
11391/// Build the type that describes a C++ typename specifier,
11392/// e.g., "typename T::type".
11393QualType
11394Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11395 SourceLocation KeywordLoc,
11396 NestedNameSpecifierLoc QualifierLoc,
11397 const IdentifierInfo &II,
11398 SourceLocation IILoc, bool DeducedTSTContext) {
11399 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11400
11401 CXXScopeSpec SS;
11402 SS.Adopt(Other: QualifierLoc);
11403
11404 DeclContext *Ctx = nullptr;
11405 if (QualifierLoc) {
11406 Ctx = computeDeclContext(SS);
11407 if (!Ctx) {
11408 // If the nested-name-specifier is dependent and couldn't be
11409 // resolved to a type, build a typename type.
11410 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11411 return Context.getDependentNameType(Keyword,
11412 NNS: QualifierLoc.getNestedNameSpecifier(),
11413 Name: &II);
11414 }
11415
11416 // If the nested-name-specifier refers to the current instantiation,
11417 // the "typename" keyword itself is superfluous. In C++03, the
11418 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11419 // allows such extraneous "typename" keywords, and we retroactively
11420 // apply this DR to C++03 code with only a warning. In any case we continue.
11421
11422 if (RequireCompleteDeclContext(SS, DC: Ctx))
11423 return QualType();
11424 }
11425
11426 DeclarationName Name(&II);
11427 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11428 if (Ctx)
11429 LookupQualifiedName(R&: Result, LookupCtx: Ctx, SS);
11430 else
11431 LookupName(R&: Result, S: CurScope);
11432 unsigned DiagID = 0;
11433 Decl *Referenced = nullptr;
11434 switch (Result.getResultKind()) {
11435 case LookupResultKind::NotFound: {
11436 // If we're looking up 'type' within a template named 'enable_if', produce
11437 // a more specific diagnostic.
11438 SourceRange CondRange;
11439 Expr *Cond = nullptr;
11440 if (Ctx && isEnableIf(NNS: QualifierLoc, II, CondRange, Cond)) {
11441 // If we have a condition, narrow it down to the specific failed
11442 // condition.
11443 if (Cond) {
11444 Expr *FailedCond;
11445 std::string FailedDescription;
11446 std::tie(args&: FailedCond, args&: FailedDescription) =
11447 findFailedBooleanCondition(Cond);
11448
11449 Diag(Loc: FailedCond->getExprLoc(),
11450 DiagID: diag::err_typename_nested_not_found_requirement)
11451 << FailedDescription
11452 << FailedCond->getSourceRange();
11453 return QualType();
11454 }
11455
11456 Diag(Loc: CondRange.getBegin(),
11457 DiagID: diag::err_typename_nested_not_found_enable_if)
11458 << Ctx << CondRange;
11459 return QualType();
11460 }
11461
11462 DiagID = Ctx ? diag::err_typename_nested_not_found
11463 : diag::err_unknown_typename;
11464 break;
11465 }
11466
11467 case LookupResultKind::FoundUnresolvedValue: {
11468 // We found a using declaration that is a value. Most likely, the using
11469 // declaration itself is meant to have the 'typename' keyword.
11470 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11471 IILoc);
11472 Diag(Loc: IILoc, DiagID: diag::err_typename_refers_to_using_value_decl)
11473 << Name << Ctx << FullRange;
11474 if (UnresolvedUsingValueDecl *Using
11475 = dyn_cast<UnresolvedUsingValueDecl>(Val: Result.getRepresentativeDecl())){
11476 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11477 Diag(Loc, DiagID: diag::note_using_value_decl_missing_typename)
11478 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
11479 }
11480 }
11481 // Fall through to create a dependent typename type, from which we can
11482 // recover better.
11483 [[fallthrough]];
11484
11485 case LookupResultKind::NotFoundInCurrentInstantiation:
11486 // Okay, it's a member of an unknown instantiation.
11487 return Context.getDependentNameType(Keyword,
11488 NNS: QualifierLoc.getNestedNameSpecifier(),
11489 Name: &II);
11490
11491 case LookupResultKind::Found:
11492 // FXIME: Missing support for UsingShadowDecl on this path?
11493 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: Result.getFoundDecl())) {
11494 // C++ [class.qual]p2:
11495 // In a lookup in which function names are not ignored and the
11496 // nested-name-specifier nominates a class C, if the name specified
11497 // after the nested-name-specifier, when looked up in C, is the
11498 // injected-class-name of C [...] then the name is instead considered
11499 // to name the constructor of class C.
11500 //
11501 // Unlike in an elaborated-type-specifier, function names are not ignored
11502 // in typename-specifier lookup. However, they are ignored in all the
11503 // contexts where we form a typename type with no keyword (that is, in
11504 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11505 //
11506 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11507 // ignore functions, but that appears to be an oversight.
11508 checkTypeDeclType(LookupCtx: Ctx,
11509 DCK: Keyword == ElaboratedTypeKeyword::Typename
11510 ? DiagCtorKind::Typename
11511 : DiagCtorKind::None,
11512 TD: Type, NameLoc: IILoc);
11513 // FIXME: This appears to be the only case where a template type parameter
11514 // can have an elaborated keyword. We should preserve it somehow.
11515 if (isa<TemplateTypeParmDecl>(Val: Type)) {
11516 assert(Keyword == ElaboratedTypeKeyword::Typename);
11517 assert(!QualifierLoc);
11518 Keyword = ElaboratedTypeKeyword::None;
11519 }
11520 return Context.getTypeDeclType(
11521 Keyword, Qualifier: QualifierLoc.getNestedNameSpecifier(), Decl: Type);
11522 }
11523
11524 // C++ [dcl.type.simple]p2:
11525 // A type-specifier of the form
11526 // typename[opt] nested-name-specifier[opt] template-name
11527 // is a placeholder for a deduced class type [...].
11528 if (getLangOpts().CPlusPlus17) {
11529 if (auto *TD = getAsTypeTemplateDecl(D: Result.getFoundDecl())) {
11530 if (!DeducedTSTContext) {
11531 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11532 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11533 Diag(Loc: IILoc, DiagID: diag::err_dependent_deduced_tst)
11534 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
11535 << QualType(Qualifier.getAsType(), 0);
11536 else
11537 Diag(Loc: IILoc, DiagID: diag::err_deduced_tst)
11538 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD));
11539 NoteTemplateLocation(Decl: *TD);
11540 return QualType();
11541 }
11542 TemplateName Name = Context.getQualifiedTemplateName(
11543 Qualifier: QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11544 Template: TemplateName(TD));
11545 return Context.getDeducedTemplateSpecializationType(
11546 DK: DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11547 Template: Name);
11548 }
11549 }
11550
11551 DiagID = Ctx ? diag::err_typename_nested_not_type
11552 : diag::err_typename_not_type;
11553 Referenced = Result.getFoundDecl();
11554 break;
11555
11556 case LookupResultKind::FoundOverloaded:
11557 DiagID = Ctx ? diag::err_typename_nested_not_type
11558 : diag::err_typename_not_type;
11559 Referenced = *Result.begin();
11560 break;
11561
11562 case LookupResultKind::Ambiguous:
11563 return QualType();
11564 }
11565
11566 // If we get here, it's because name lookup did not find a
11567 // type. Emit an appropriate diagnostic and return an error.
11568 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11569 IILoc);
11570 if (Ctx)
11571 Diag(Loc: IILoc, DiagID) << FullRange << Name << Ctx;
11572 else
11573 Diag(Loc: IILoc, DiagID) << FullRange << Name;
11574 if (Referenced)
11575 Diag(Loc: Referenced->getLocation(),
11576 DiagID: Ctx ? diag::note_typename_member_refers_here
11577 : diag::note_typename_refers_here)
11578 << Name;
11579 return QualType();
11580}
11581
11582namespace {
11583 // See Sema::RebuildTypeInCurrentInstantiation
11584 class CurrentInstantiationRebuilder
11585 : public TreeTransform<CurrentInstantiationRebuilder> {
11586 SourceLocation Loc;
11587 DeclarationName Entity;
11588
11589 public:
11590 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11591
11592 CurrentInstantiationRebuilder(Sema &SemaRef,
11593 SourceLocation Loc,
11594 DeclarationName Entity)
11595 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11596 Loc(Loc), Entity(Entity) { }
11597
11598 /// Determine whether the given type \p T has already been
11599 /// transformed.
11600 ///
11601 /// For the purposes of type reconstruction, a type has already been
11602 /// transformed if it is NULL or if it is not dependent.
11603 bool AlreadyTransformed(QualType T) {
11604 return T.isNull() || !T->isInstantiationDependentType();
11605 }
11606
11607 /// Returns the location of the entity whose type is being
11608 /// rebuilt.
11609 SourceLocation getBaseLocation() { return Loc; }
11610
11611 /// Returns the name of the entity whose type is being rebuilt.
11612 DeclarationName getBaseEntity() { return Entity; }
11613
11614 /// Sets the "base" location and entity when that
11615 /// information is known based on another transformation.
11616 void setBase(SourceLocation Loc, DeclarationName Entity) {
11617 this->Loc = Loc;
11618 this->Entity = Entity;
11619 }
11620
11621 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11622 // Lambdas never need to be transformed.
11623 return E;
11624 }
11625 };
11626} // end anonymous namespace
11627
11628TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11629 SourceLocation Loc,
11630 DeclarationName Name) {
11631 if (!T || !T->getType()->isInstantiationDependentType())
11632 return T;
11633
11634 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11635 return Rebuilder.TransformType(TSI: T);
11636}
11637
11638ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11639 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11640 DeclarationName());
11641 return Rebuilder.TransformExpr(E);
11642}
11643
11644bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11645 if (SS.isInvalid())
11646 return true;
11647
11648 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11649 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11650 DeclarationName());
11651 NestedNameSpecifierLoc Rebuilt
11652 = Rebuilder.TransformNestedNameSpecifierLoc(NNS: QualifierLoc);
11653 if (!Rebuilt)
11654 return true;
11655
11656 SS.Adopt(Other: Rebuilt);
11657 return false;
11658}
11659
11660bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11661 TemplateParameterList *Params) {
11662 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11663 Decl *Param = Params->getParam(Idx: I);
11664
11665 // There is nothing to rebuild in a type parameter.
11666 if (isa<TemplateTypeParmDecl>(Val: Param))
11667 continue;
11668
11669 // Rebuild the template parameter list of a template template parameter.
11670 if (TemplateTemplateParmDecl *TTP
11671 = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) {
11672 if (RebuildTemplateParamsInCurrentInstantiation(
11673 Params: TTP->getTemplateParameters()))
11674 return true;
11675
11676 continue;
11677 }
11678
11679 // Rebuild the type of a non-type template parameter.
11680 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Val: Param);
11681 TypeSourceInfo *NewTSI
11682 = RebuildTypeInCurrentInstantiation(T: NTTP->getTypeSourceInfo(),
11683 Loc: NTTP->getLocation(),
11684 Name: NTTP->getDeclName());
11685 if (!NewTSI)
11686 return true;
11687
11688 if (NewTSI->getType()->isUndeducedType()) {
11689 // C++17 [temp.dep.expr]p3:
11690 // An id-expression is type-dependent if it contains
11691 // - an identifier associated by name lookup with a non-type
11692 // template-parameter declared with a type that contains a
11693 // placeholder type (7.1.7.4),
11694 NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: NewTSI);
11695 }
11696
11697 if (NewTSI != NTTP->getTypeSourceInfo()) {
11698 NTTP->setTypeSourceInfo(NewTSI);
11699 NTTP->setType(NewTSI->getType());
11700 }
11701 }
11702
11703 return false;
11704}
11705
11706std::string
11707Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11708 const TemplateArgumentList &Args) {
11709 return getTemplateArgumentBindingsText(Params, Args: Args.data(), NumArgs: Args.size());
11710}
11711
11712std::string
11713Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11714 const TemplateArgument *Args,
11715 unsigned NumArgs) {
11716 SmallString<128> Str;
11717 llvm::raw_svector_ostream Out(Str);
11718
11719 if (!Params || Params->size() == 0 || NumArgs == 0)
11720 return std::string();
11721
11722 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11723 if (I >= NumArgs)
11724 break;
11725
11726 if (I == 0)
11727 Out << "[with ";
11728 else
11729 Out << ", ";
11730
11731 if (const IdentifierInfo *Id = Params->getParam(Idx: I)->getIdentifier()) {
11732 Out << Id->getName();
11733 } else {
11734 Out << '$' << I;
11735 }
11736
11737 Out << " = ";
11738 Args[I].print(Policy: getPrintingPolicy(), Out,
11739 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
11740 Policy: getPrintingPolicy(), TPL: Params, Idx: I));
11741 }
11742
11743 Out << ']';
11744 return std::string(Out.str());
11745}
11746
11747void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11748 CachedTokens &Toks) {
11749 if (!FD)
11750 return;
11751
11752 auto LPT = std::make_unique<LateParsedTemplate>();
11753
11754 // Take tokens to avoid allocations
11755 LPT->Toks.swap(RHS&: Toks);
11756 LPT->D = FnD;
11757 LPT->FPO = getCurFPFeatures();
11758 LateParsedTemplateMap.insert(KV: std::make_pair(x&: FD, y: std::move(LPT)));
11759
11760 FD->setLateTemplateParsed(true);
11761}
11762
11763void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11764 if (!FD)
11765 return;
11766 FD->setLateTemplateParsed(false);
11767}
11768
11769bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11770 DeclContext *DC = CurContext;
11771
11772 while (DC) {
11773 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
11774 const FunctionDecl *FD = RD->isLocalClass();
11775 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11776 } else if (DC->isTranslationUnit() || DC->isNamespace())
11777 return false;
11778
11779 DC = DC->getParent();
11780 }
11781 return false;
11782}
11783
11784namespace {
11785/// Walk the path from which a declaration was instantiated, and check
11786/// that every explicit specialization along that path is visible. This enforces
11787/// C++ [temp.expl.spec]/6:
11788///
11789/// If a template, a member template or a member of a class template is
11790/// explicitly specialized then that specialization shall be declared before
11791/// the first use of that specialization that would cause an implicit
11792/// instantiation to take place, in every translation unit in which such a
11793/// use occurs; no diagnostic is required.
11794///
11795/// and also C++ [temp.class.spec]/1:
11796///
11797/// A partial specialization shall be declared before the first use of a
11798/// class template specialization that would make use of the partial
11799/// specialization as the result of an implicit or explicit instantiation
11800/// in every translation unit in which such a use occurs; no diagnostic is
11801/// required.
11802class ExplicitSpecializationVisibilityChecker {
11803 Sema &S;
11804 SourceLocation Loc;
11805 llvm::SmallVector<Module *, 8> Modules;
11806 Sema::AcceptableKind Kind;
11807
11808public:
11809 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11810 Sema::AcceptableKind Kind)
11811 : S(S), Loc(Loc), Kind(Kind) {}
11812
11813 void check(NamedDecl *ND) {
11814 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
11815 return checkImpl(Spec: FD);
11816 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
11817 return checkImpl(Spec: RD);
11818 if (auto *VD = dyn_cast<VarDecl>(Val: ND))
11819 return checkImpl(Spec: VD);
11820 if (auto *ED = dyn_cast<EnumDecl>(Val: ND))
11821 return checkImpl(Spec: ED);
11822 }
11823
11824private:
11825 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11826 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11827 : Sema::MissingImportKind::ExplicitSpecialization;
11828 const bool Recover = true;
11829
11830 // If we got a custom set of modules (because only a subset of the
11831 // declarations are interesting), use them, otherwise let
11832 // diagnoseMissingImport intelligently pick some.
11833 if (Modules.empty())
11834 S.diagnoseMissingImport(Loc, Decl: D, MIK: Kind, Recover);
11835 else
11836 S.diagnoseMissingImport(Loc, Decl: D, DeclLoc: D->getLocation(), Modules, MIK: Kind, Recover);
11837 }
11838
11839 bool CheckMemberSpecialization(const NamedDecl *D) {
11840 return Kind == Sema::AcceptableKind::Visible
11841 ? S.hasVisibleMemberSpecialization(D)
11842 : S.hasReachableMemberSpecialization(D);
11843 }
11844
11845 bool CheckExplicitSpecialization(const NamedDecl *D) {
11846 return Kind == Sema::AcceptableKind::Visible
11847 ? S.hasVisibleExplicitSpecialization(D)
11848 : S.hasReachableExplicitSpecialization(D);
11849 }
11850
11851 bool CheckDeclaration(const NamedDecl *D) {
11852 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11853 : S.hasReachableDeclaration(D);
11854 }
11855
11856 // Check a specific declaration. There are three problematic cases:
11857 //
11858 // 1) The declaration is an explicit specialization of a template
11859 // specialization.
11860 // 2) The declaration is an explicit specialization of a member of an
11861 // templated class.
11862 // 3) The declaration is an instantiation of a template, and that template
11863 // is an explicit specialization of a member of a templated class.
11864 //
11865 // We don't need to go any deeper than that, as the instantiation of the
11866 // surrounding class / etc is not triggered by whatever triggered this
11867 // instantiation, and thus should be checked elsewhere.
11868 template<typename SpecDecl>
11869 void checkImpl(SpecDecl *Spec) {
11870 bool IsHiddenExplicitSpecialization = false;
11871 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11872 // Some invalid friend declarations are written as specializations but are
11873 // instantiated implicitly.
11874 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11875 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11876 if (SpecKind == TSK_ExplicitSpecialization) {
11877 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11878 ? !CheckMemberSpecialization(D: Spec)
11879 : !CheckExplicitSpecialization(D: Spec);
11880 } else {
11881 checkInstantiated(Spec);
11882 }
11883
11884 if (IsHiddenExplicitSpecialization)
11885 diagnose(D: Spec->getMostRecentDecl(), IsPartialSpec: false);
11886 }
11887
11888 void checkInstantiated(FunctionDecl *FD) {
11889 if (auto *TD = FD->getPrimaryTemplate())
11890 checkTemplate(TD);
11891 }
11892
11893 void checkInstantiated(CXXRecordDecl *RD) {
11894 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD);
11895 if (!SD)
11896 return;
11897
11898 auto From = SD->getSpecializedTemplateOrPartial();
11899 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11900 checkTemplate(TD);
11901 else if (auto *TD =
11902 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11903 if (!CheckDeclaration(D: TD))
11904 diagnose(D: TD, IsPartialSpec: true);
11905 checkTemplate(TD);
11906 }
11907 }
11908
11909 void checkInstantiated(VarDecl *RD) {
11910 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(Val: RD);
11911 if (!SD)
11912 return;
11913
11914 auto From = SD->getSpecializedTemplateOrPartial();
11915 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11916 checkTemplate(TD);
11917 else if (auto *TD =
11918 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11919 if (!CheckDeclaration(D: TD))
11920 diagnose(D: TD, IsPartialSpec: true);
11921 checkTemplate(TD);
11922 }
11923 }
11924
11925 void checkInstantiated(EnumDecl *FD) {}
11926
11927 template<typename TemplDecl>
11928 void checkTemplate(TemplDecl *TD) {
11929 if (TD->isMemberSpecialization()) {
11930 if (!CheckMemberSpecialization(D: TD))
11931 diagnose(D: TD->getMostRecentDecl(), IsPartialSpec: false);
11932 }
11933 }
11934};
11935} // end anonymous namespace
11936
11937void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11938 if (!getLangOpts().Modules)
11939 return;
11940
11941 ExplicitSpecializationVisibilityChecker(*this, Loc,
11942 Sema::AcceptableKind::Visible)
11943 .check(ND: Spec);
11944}
11945
11946void Sema::checkSpecializationReachability(SourceLocation Loc,
11947 NamedDecl *Spec) {
11948 if (!getLangOpts().CPlusPlusModules)
11949 return checkSpecializationVisibility(Loc, Spec);
11950
11951 ExplicitSpecializationVisibilityChecker(*this, Loc,
11952 Sema::AcceptableKind::Reachable)
11953 .check(ND: Spec);
11954}
11955
11956SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
11957 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11958 return N->getLocation();
11959 if (const auto *FD = dyn_cast<FunctionDecl>(Val: N)) {
11960 if (!FD->isFunctionTemplateSpecialization())
11961 return FD->getLocation();
11962 } else if (!isa<ClassTemplateSpecializationDecl,
11963 VarTemplateSpecializationDecl>(Val: N)) {
11964 return N->getLocation();
11965 }
11966 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11967 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11968 continue;
11969 return CSC.PointOfInstantiation;
11970 }
11971 return N->getLocation();
11972}
11973