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/DeclCXX.h"
17#include "clang/AST/DeclFriend.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/DynamicRecursiveASTVisitor.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/Mangle.h"
23#include "clang/AST/TemplateName.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeOrdering.h"
26#include "clang/AST/TypeVisitor.h"
27#include "clang/Basic/Builtins.h"
28#include "clang/Basic/DiagnosticSema.h"
29#include "clang/Basic/LangOptions.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/SourceLocation.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/EnterExpressionEvaluationContext.h"
35#include "clang/Sema/Initialization.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/Overload.h"
38#include "clang/Sema/ParsedTemplate.h"
39#include "clang/Sema/Scope.h"
40#include "clang/Sema/SemaCUDA.h"
41#include "clang/Sema/SemaInternal.h"
42#include "clang/Sema/Template.h"
43#include "clang/Sema/TemplateDeduction.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/SmallBitVector.h"
46#include "llvm/ADT/StringExtras.h"
47#include "llvm/Support/Casting.h"
48#include "llvm/Support/SaveAndRestore.h"
49
50#include <optional>
51using namespace clang;
52using namespace sema;
53
54// Exported for use by Parser.
55SourceRange
56clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
57 unsigned N) {
58 if (!N) return SourceRange();
59 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
60}
61
62unsigned Sema::getTemplateDepth(Scope *S) const {
63 unsigned Depth = 0;
64
65 // Each template parameter scope represents one level of template parameter
66 // depth.
67 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
68 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
69 ++Depth;
70 }
71
72 // Note that there are template parameters with the given depth.
73 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(a: Depth, b: D + 1); };
74
75 // Look for parameters of an enclosing generic lambda. We don't create a
76 // template parameter scope for these.
77 for (FunctionScopeInfo *FSI : getFunctionScopes()) {
78 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FSI)) {
79 if (!LSI->TemplateParams.empty()) {
80 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
81 break;
82 }
83 if (LSI->GLTemplateParameterList) {
84 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
85 break;
86 }
87 }
88 }
89
90 // Look for parameters of an enclosing terse function template. We don't
91 // create a template parameter scope for these either.
92 for (const InventedTemplateParameterInfo &Info :
93 getInventedParameterInfos()) {
94 if (!Info.TemplateParams.empty()) {
95 ParamsAtDepth(Info.AutoTemplateParameterDepth);
96 break;
97 }
98 }
99
100 return Depth;
101}
102
103/// \brief Determine whether the declaration found is acceptable as the name
104/// of a template and, if so, return that template declaration. Otherwise,
105/// returns null.
106///
107/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
108/// is true. In all other cases it will return a TemplateDecl (or null).
109NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
110 bool AllowFunctionTemplates,
111 bool AllowDependent) {
112 D = D->getUnderlyingDecl();
113
114 if (isa<TemplateDecl>(Val: D)) {
115 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(Val: D))
116 return nullptr;
117
118 return D;
119 }
120
121 if (const auto *Record = dyn_cast<CXXRecordDecl>(Val: D)) {
122 // C++ [temp.local]p1:
123 // Like normal (non-template) classes, class templates have an
124 // injected-class-name (Clause 9). The injected-class-name
125 // can be used with or without a template-argument-list. When
126 // it is used without a template-argument-list, it is
127 // equivalent to the injected-class-name followed by the
128 // template-parameters of the class template enclosed in
129 // <>. When it is used with a template-argument-list, it
130 // refers to the specified class template specialization,
131 // which could be the current specialization or another
132 // specialization.
133 if (Record->isInjectedClassName()) {
134 Record = cast<CXXRecordDecl>(Val: Record->getDeclContext());
135 if (Record->getDescribedClassTemplate())
136 return Record->getDescribedClassTemplate();
137
138 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record))
139 return Spec->getSpecializedTemplate();
140 }
141
142 return nullptr;
143 }
144
145 // 'using Dependent::foo;' can resolve to a template name.
146 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
147 // injected-class-name).
148 if (AllowDependent && isa<UnresolvedUsingValueDecl>(Val: D))
149 return D;
150
151 return nullptr;
152}
153
154void Sema::FilterAcceptableTemplateNames(LookupResult &R,
155 bool AllowFunctionTemplates,
156 bool AllowDependent) {
157 LookupResult::Filter filter = R.makeFilter();
158 while (filter.hasNext()) {
159 NamedDecl *Orig = filter.next();
160 if (!getAsTemplateNameDecl(D: Orig, AllowFunctionTemplates, AllowDependent))
161 filter.erase();
162 }
163 filter.done();
164}
165
166bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
167 bool AllowFunctionTemplates,
168 bool AllowDependent,
169 bool AllowNonTemplateFunctions) {
170 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
171 if (getAsTemplateNameDecl(D: *I, AllowFunctionTemplates, AllowDependent))
172 return true;
173 if (AllowNonTemplateFunctions &&
174 isa<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
175 return true;
176 }
177
178 return false;
179}
180
181TemplateNameKind
182Sema::isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword,
183 const UnqualifiedId &Name, ParsedType ObjectTypePtr,
184 bool EnteringContext, TemplateTy &TemplateResult,
185 bool &MemberOfUnknownSpecialization,
186 bool AllowTypoCorrection) {
187 assert(getLangOpts().CPlusPlus && "No template names in C!");
188
189 DeclarationName TName;
190 MemberOfUnknownSpecialization = false;
191
192 switch (Name.getKind()) {
193 case UnqualifiedIdKind::IK_Identifier:
194 TName = DeclarationName(Name.Identifier);
195 break;
196
197 case UnqualifiedIdKind::IK_OperatorFunctionId:
198 TName = Context.DeclarationNames.getCXXOperatorName(
199 Op: Name.OperatorFunctionId.Operator);
200 break;
201
202 case UnqualifiedIdKind::IK_LiteralOperatorId:
203 TName = Context.DeclarationNames.getCXXLiteralOperatorName(II: Name.Identifier);
204 break;
205
206 default:
207 return TNK_Non_template;
208 }
209
210 QualType ObjectType = ObjectTypePtr.get();
211
212 AssumedTemplateKind AssumedTemplate;
213 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
214 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
215 /*RequiredTemplate=*/SourceLocation(),
216 ATK: &AssumedTemplate, AllowTypoCorrection))
217 return TNK_Non_template;
218 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
219
220 if (AssumedTemplate != AssumedTemplateKind::None) {
221 TemplateResult = TemplateTy::make(P: Context.getAssumedTemplateName(Name: TName));
222 // Let the parser know whether we found nothing or found functions; if we
223 // found nothing, we want to more carefully check whether this is actually
224 // a function template name versus some other kind of undeclared identifier.
225 return AssumedTemplate == AssumedTemplateKind::FoundNothing
226 ? TNK_Undeclared_template
227 : TNK_Function_template;
228 }
229
230 if (R.empty())
231 return TNK_Non_template;
232
233 NamedDecl *D = nullptr;
234 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *R.begin());
235 if (R.isAmbiguous()) {
236 // If we got an ambiguity involving a non-function template, treat this
237 // as a template name, and pick an arbitrary template for error recovery.
238 bool AnyFunctionTemplates = false;
239 for (NamedDecl *FoundD : R) {
240 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(D: FoundD)) {
241 if (isa<FunctionTemplateDecl>(Val: FoundTemplate))
242 AnyFunctionTemplates = true;
243 else {
244 D = FoundTemplate;
245 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: FoundD);
246 break;
247 }
248 }
249 }
250
251 // If we didn't find any templates at all, this isn't a template name.
252 // Leave the ambiguity for a later lookup to diagnose.
253 if (!D && !AnyFunctionTemplates) {
254 R.suppressDiagnostics();
255 return TNK_Non_template;
256 }
257
258 // If the only templates were function templates, filter out the rest.
259 // We'll diagnose the ambiguity later.
260 if (!D)
261 FilterAcceptableTemplateNames(R);
262 }
263
264 // At this point, we have either picked a single template name declaration D
265 // or we have a non-empty set of results R containing either one template name
266 // declaration or a set of function templates.
267
268 TemplateName Template;
269 TemplateNameKind TemplateKind;
270
271 unsigned ResultCount = R.end() - R.begin();
272 if (!D && ResultCount > 1) {
273 // We assume that we'll preserve the qualifier from a function
274 // template name in other ways.
275 Template = Context.getOverloadedTemplateName(Begin: R.begin(), End: R.end());
276 TemplateKind = TNK_Function_template;
277
278 // We'll do this lookup again later.
279 R.suppressDiagnostics();
280 } else {
281 if (!D) {
282 D = getAsTemplateNameDecl(D: *R.begin());
283 assert(D && "unambiguous result is not a template name");
284 }
285
286 if (isa<UnresolvedUsingValueDecl>(Val: D)) {
287 // We don't yet know whether this is a template-name or not.
288 MemberOfUnknownSpecialization = true;
289 return TNK_Non_template;
290 }
291
292 TemplateDecl *TD = cast<TemplateDecl>(Val: D);
293 Template =
294 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
295 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
296 if (!SS.isInvalid()) {
297 NestedNameSpecifier Qualifier = SS.getScopeRep();
298 Template = Context.getQualifiedTemplateName(Qualifier, TemplateKeyword: hasTemplateKeyword,
299 Template);
300 }
301
302 if (isa<FunctionTemplateDecl>(Val: TD)) {
303 TemplateKind = TNK_Function_template;
304
305 // We'll do this lookup again later.
306 R.suppressDiagnostics();
307 } else {
308 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
309 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
310 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
311 TemplateKind =
312 isa<TemplateTemplateParmDecl>(Val: TD)
313 ? dyn_cast<TemplateTemplateParmDecl>(Val: TD)->templateParameterKind()
314 : isa<VarTemplateDecl>(Val: TD) ? TNK_Var_template
315 : isa<ConceptDecl>(Val: TD) ? TNK_Concept_template
316 : TNK_Type_template;
317 }
318 }
319
320 if (isPackProducingBuiltinTemplateName(N: Template) && S &&
321 S->getTemplateParamParent() == nullptr)
322 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_builtin_pack_outside_template) << TName;
323 // Recover by returning the template, even though we would never be able to
324 // substitute it.
325
326 TemplateResult = TemplateTy::make(P: Template);
327 return TemplateKind;
328}
329
330bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
331 SourceLocation NameLoc, CXXScopeSpec &SS,
332 ParsedTemplateTy *Template /*=nullptr*/) {
333 // We could use redeclaration lookup here, but we don't need to: the
334 // syntactic form of a deduction guide is enough to identify it even
335 // if we can't look up the template name at all.
336 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
337 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
338 /*EnteringContext*/ false))
339 return false;
340
341 if (R.empty()) return false;
342 if (R.isAmbiguous()) {
343 // FIXME: Diagnose an ambiguity if we find at least one template.
344 R.suppressDiagnostics();
345 return false;
346 }
347
348 // We only treat template-names that name type templates as valid deduction
349 // guide names.
350 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
351 if (!TD || !getAsTypeTemplateDecl(D: TD))
352 return false;
353
354 if (Template) {
355 TemplateName Name = Context.getQualifiedTemplateName(
356 Qualifier: SS.getScopeRep(), /*TemplateKeyword=*/false, Template: TemplateName(TD));
357 *Template = TemplateTy::make(P: Name);
358 }
359 return true;
360}
361
362bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
363 SourceLocation IILoc,
364 Scope *S,
365 const CXXScopeSpec *SS,
366 TemplateTy &SuggestedTemplate,
367 TemplateNameKind &SuggestedKind) {
368 // We can't recover unless there's a dependent scope specifier preceding the
369 // template name.
370 // FIXME: Typo correction?
371 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(SS: *SS) ||
372 computeDeclContext(SS: *SS))
373 return false;
374
375 // The code is missing a 'template' keyword prior to the dependent template
376 // name.
377 SuggestedTemplate = TemplateTy::make(P: Context.getDependentTemplateName(
378 Name: {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
379 Diag(Loc: IILoc, DiagID: diag::err_template_kw_missing)
380 << SuggestedTemplate.get()
381 << FixItHint::CreateInsertion(InsertionLoc: IILoc, Code: "template ");
382 SuggestedKind = TNK_Dependent_template_name;
383 return true;
384}
385
386bool Sema::LookupTemplateName(LookupResult &Found, Scope *S, CXXScopeSpec &SS,
387 QualType ObjectType, bool EnteringContext,
388 RequiredTemplateKind RequiredTemplate,
389 AssumedTemplateKind *ATK,
390 bool AllowTypoCorrection) {
391 if (ATK)
392 *ATK = AssumedTemplateKind::None;
393
394 if (SS.isInvalid())
395 return true;
396
397 Found.setTemplateNameLookup(true);
398
399 // Determine where to perform name lookup
400 DeclContext *LookupCtx = nullptr;
401 bool IsDependent = false;
402 if (!ObjectType.isNull()) {
403 // This nested-name-specifier occurs in a member access expression, e.g.,
404 // x->B::f, and we are looking into the type of the object.
405 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
406 LookupCtx = computeDeclContext(T: ObjectType);
407 IsDependent = !LookupCtx && ObjectType->isDependentType();
408 assert((IsDependent || !ObjectType->isIncompleteType() ||
409 !ObjectType->getAs<TagType>() ||
410 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
411 "Caller should have completed object type");
412
413 // Template names cannot appear inside an Objective-C class or object type
414 // or a vector type.
415 //
416 // FIXME: This is wrong. For example:
417 //
418 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
419 // Vec<int> vi;
420 // vi.Vec<int>::~Vec<int>();
421 //
422 // ... should be accepted but we will not treat 'Vec' as a template name
423 // here. The right thing to do would be to check if the name is a valid
424 // vector component name, and look up a template name if not. And similarly
425 // for lookups into Objective-C class and object types, where the same
426 // problem can arise.
427 if (ObjectType->isObjCObjectOrInterfaceType() ||
428 ObjectType->isVectorType()) {
429 Found.clear();
430 return false;
431 }
432 } else if (SS.isNotEmpty()) {
433 // This nested-name-specifier occurs after another nested-name-specifier,
434 // so long into the context associated with the prior nested-name-specifier.
435 LookupCtx = computeDeclContext(SS, EnteringContext);
436 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
437
438 // The declaration context must be complete.
439 if (LookupCtx && RequireCompleteDeclContext(SS, DC: LookupCtx))
440 return true;
441 }
442
443 bool ObjectTypeSearchedInScope = false;
444 bool AllowFunctionTemplatesInLookup = true;
445 if (LookupCtx) {
446 // Perform "qualified" name lookup into the declaration context we
447 // computed, which is either the type of the base of a member access
448 // expression or the declaration context associated with a prior
449 // nested-name-specifier.
450 LookupQualifiedName(R&: Found, LookupCtx);
451
452 // FIXME: The C++ standard does not clearly specify what happens in the
453 // case where the object type is dependent, and implementations vary. In
454 // Clang, we treat a name after a . or -> as a template-name if lookup
455 // finds a non-dependent member or member of the current instantiation that
456 // is a type template, or finds no such members and lookup in the context
457 // of the postfix-expression finds a type template. In the latter case, the
458 // name is nonetheless dependent, and we may resolve it to a member of an
459 // unknown specialization when we come to instantiate the template.
460 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
461 }
462
463 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
464 // C++ [basic.lookup.classref]p1:
465 // In a class member access expression (5.2.5), if the . or -> token is
466 // immediately followed by an identifier followed by a <, the
467 // identifier must be looked up to determine whether the < is the
468 // beginning of a template argument list (14.2) or a less-than operator.
469 // The identifier is first looked up in the class of the object
470 // expression. If the identifier is not found, it is then looked up in
471 // the context of the entire postfix-expression and shall name a class
472 // template.
473 if (S)
474 LookupName(R&: Found, S);
475
476 if (!ObjectType.isNull()) {
477 // FIXME: We should filter out all non-type templates here, particularly
478 // variable templates and concepts. But the exclusion of alias templates
479 // and template template parameters is a wording defect.
480 AllowFunctionTemplatesInLookup = false;
481 ObjectTypeSearchedInScope = true;
482 }
483
484 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
485 }
486
487 if (Found.isAmbiguous())
488 return false;
489
490 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
491 !RequiredTemplate.hasTemplateKeyword()) {
492 // C++2a [temp.names]p2:
493 // A name is also considered to refer to a template if it is an
494 // unqualified-id followed by a < and name lookup finds either one or more
495 // functions or finds nothing.
496 //
497 // To keep our behavior consistent, we apply the "finds nothing" part in
498 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
499 // successfully form a call to an undeclared template-id.
500 bool AllFunctions =
501 getLangOpts().CPlusPlus20 && llvm::all_of(Range&: Found, P: [](NamedDecl *ND) {
502 return isa<FunctionDecl>(Val: ND->getUnderlyingDecl());
503 });
504 if (AllFunctions || (Found.empty() && !IsDependent)) {
505 // If lookup found any functions, or if this is a name that can only be
506 // used for a function, then strongly assume this is a function
507 // template-id.
508 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
509 ? AssumedTemplateKind::FoundNothing
510 : AssumedTemplateKind::FoundFunctions;
511 Found.clear();
512 return false;
513 }
514 }
515
516 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
517 // If we did not find any names, and this is not a disambiguation, attempt
518 // to correct any typos.
519 DeclarationName Name = Found.getLookupName();
520 Found.clear();
521
522 class TemplateNameLookupValidatorCCC final
523 : public QualifiedLookupValidatorCCC {
524 public:
525 using QualifiedLookupValidatorCCC::QualifiedLookupValidatorCCC;
526
527 bool ValidateCandidate(const TypoCorrection &Candidate) final {
528 if (const NamedDecl *ND = Candidate.getCorrectionDecl();
529 !ND || !isa<TemplateDecl>(Val: ND))
530 return false;
531 return QualifiedLookupValidatorCCC::ValidateCandidate(Candidate);
532 }
533
534 std::unique_ptr<CorrectionCandidateCallback> clone() final {
535 return std::make_unique<TemplateNameLookupValidatorCCC>(args&: *this);
536 }
537 };
538
539 TemplateNameLookupValidatorCCC FilterCCC(!SS.isEmpty());
540 FilterCCC.WantTypeSpecifiers = false;
541 FilterCCC.WantExpressionKeywords = false;
542 FilterCCC.WantRemainingKeywords = false;
543 FilterCCC.WantCXXNamedCasts = true;
544 if (TypoCorrection Corrected = CorrectTypo(
545 Typo: Found.getLookupNameInfo(), LookupKind: Found.getLookupKind(), S, SS: &SS, CCC&: FilterCCC,
546 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
547 if (auto *ND = Corrected.getFoundDecl())
548 Found.addDecl(D: ND);
549 FilterAcceptableTemplateNames(R&: Found);
550 if (Found.isAmbiguous()) {
551 Found.clear();
552 } else if (!Found.empty()) {
553 // Do not erase the typo-corrected result to avoid duplicated
554 // diagnostics.
555 AllowFunctionTemplatesInLookup = true;
556 Found.setLookupName(Corrected.getCorrection());
557 if (LookupCtx) {
558 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
559 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
560 Name.getAsString() == CorrectedStr;
561 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_template_suggest)
562 << Name << LookupCtx << DroppedSpecifier
563 << SS.getRange());
564 } else {
565 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_template_suggest) << Name);
566 }
567
568 if (Corrected.WillReplaceSpecifier()) {
569 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
570 // In order to be valid, a non-empty CXXScopeSpec needs a source
571 // range.
572 SS.MakeTrivial(Context, Qualifier: NNS,
573 R: NNS ? Found.getNameLoc() : SourceRange());
574 }
575 }
576 }
577 }
578
579 NamedDecl *ExampleLookupResult =
580 Found.empty() ? nullptr : Found.getRepresentativeDecl();
581 FilterAcceptableTemplateNames(R&: Found, AllowFunctionTemplates: AllowFunctionTemplatesInLookup);
582 if (Found.empty()) {
583 if (IsDependent) {
584 Found.setNotFoundInCurrentInstantiation();
585 return false;
586 }
587
588 // If a 'template' keyword was used, a lookup that finds only non-template
589 // names is an error.
590 if (ExampleLookupResult && RequiredTemplate) {
591 Diag(Loc: Found.getNameLoc(), DiagID: diag::err_template_kw_refers_to_non_template)
592 << Found.getLookupName() << SS.getRange()
593 << RequiredTemplate.hasTemplateKeyword()
594 << RequiredTemplate.getTemplateKeywordLoc();
595 Diag(Loc: ExampleLookupResult->getUnderlyingDecl()->getLocation(),
596 DiagID: diag::note_template_kw_refers_to_non_template)
597 << Found.getLookupName();
598 return true;
599 }
600
601 return false;
602 }
603
604 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
605 !getLangOpts().CPlusPlus11) {
606 // C++03 [basic.lookup.classref]p1:
607 // [...] If the lookup in the class of the object expression finds a
608 // template, the name is also looked up in the context of the entire
609 // postfix-expression and [...]
610 //
611 // Note: C++11 does not perform this second lookup.
612 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
613 LookupOrdinaryName);
614 FoundOuter.setTemplateNameLookup(true);
615 LookupName(R&: FoundOuter, S);
616 // FIXME: We silently accept an ambiguous lookup here, in violation of
617 // [basic.lookup]/1.
618 FilterAcceptableTemplateNames(R&: FoundOuter, /*AllowFunctionTemplates=*/false);
619
620 NamedDecl *OuterTemplate;
621 if (FoundOuter.empty()) {
622 // - if the name is not found, the name found in the class of the
623 // object expression is used, otherwise
624 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
625 !(OuterTemplate =
626 getAsTemplateNameDecl(D: FoundOuter.getFoundDecl()))) {
627 // - if the name is found in the context of the entire
628 // postfix-expression and does not name a class template, the name
629 // found in the class of the object expression is used, otherwise
630 FoundOuter.clear();
631 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
632 // - if the name found is a class template, it must refer to the same
633 // entity as the one found in the class of the object expression,
634 // otherwise the program is ill-formed.
635 if (!Found.isSingleResult() ||
636 getAsTemplateNameDecl(D: Found.getFoundDecl())->getCanonicalDecl() !=
637 OuterTemplate->getCanonicalDecl()) {
638 Diag(Loc: Found.getNameLoc(),
639 DiagID: diag::ext_nested_name_member_ref_lookup_ambiguous)
640 << Found.getLookupName()
641 << ObjectType;
642 Diag(Loc: Found.getRepresentativeDecl()->getLocation(),
643 DiagID: diag::note_ambig_member_ref_object_type)
644 << ObjectType;
645 Diag(Loc: FoundOuter.getFoundDecl()->getLocation(),
646 DiagID: diag::note_ambig_member_ref_scope);
647
648 // Recover by taking the template that we found in the object
649 // expression's type.
650 }
651 }
652 }
653
654 return false;
655}
656
657void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
658 SourceLocation Less,
659 SourceLocation Greater) {
660 if (TemplateName.isInvalid())
661 return;
662
663 DeclarationNameInfo NameInfo;
664 CXXScopeSpec SS;
665 LookupNameKind LookupKind;
666
667 DeclContext *LookupCtx = nullptr;
668 NamedDecl *Found = nullptr;
669 bool MissingTemplateKeyword = false;
670
671 // Figure out what name we looked up.
672 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: TemplateName.get())) {
673 NameInfo = DRE->getNameInfo();
674 SS.Adopt(Other: DRE->getQualifierLoc());
675 LookupKind = LookupOrdinaryName;
676 Found = DRE->getFoundDecl();
677 } else if (auto *ME = dyn_cast<MemberExpr>(Val: TemplateName.get())) {
678 NameInfo = ME->getMemberNameInfo();
679 SS.Adopt(Other: ME->getQualifierLoc());
680 LookupKind = LookupMemberName;
681 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
682 Found = ME->getMemberDecl();
683 } else if (auto *DSDRE =
684 dyn_cast<DependentScopeDeclRefExpr>(Val: TemplateName.get())) {
685 NameInfo = DSDRE->getNameInfo();
686 SS.Adopt(Other: DSDRE->getQualifierLoc());
687 MissingTemplateKeyword = true;
688 } else if (auto *DSME =
689 dyn_cast<CXXDependentScopeMemberExpr>(Val: TemplateName.get())) {
690 NameInfo = DSME->getMemberNameInfo();
691 SS.Adopt(Other: DSME->getQualifierLoc());
692 MissingTemplateKeyword = true;
693 } else {
694 llvm_unreachable("unexpected kind of potential template name");
695 }
696
697 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
698 // was missing.
699 if (MissingTemplateKeyword) {
700 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_template_kw_missing)
701 << NameInfo.getName() << SourceRange(Less, Greater);
702 return;
703 }
704
705 // Try to correct the name by looking for templates and C++ named casts.
706 struct TemplateCandidateFilter : CorrectionCandidateCallback {
707 Sema &S;
708 TemplateCandidateFilter(Sema &S) : S(S) {
709 WantTypeSpecifiers = false;
710 WantExpressionKeywords = false;
711 WantRemainingKeywords = false;
712 WantCXXNamedCasts = true;
713 };
714 bool ValidateCandidate(const TypoCorrection &Candidate) override {
715 if (auto *ND = Candidate.getCorrectionDecl())
716 return S.getAsTemplateNameDecl(D: ND);
717 return Candidate.isKeyword();
718 }
719
720 std::unique_ptr<CorrectionCandidateCallback> clone() override {
721 return std::make_unique<TemplateCandidateFilter>(args&: *this);
722 }
723 };
724
725 DeclarationName Name = NameInfo.getName();
726 TemplateCandidateFilter CCC(*this);
727 if (TypoCorrection Corrected =
728 CorrectTypo(Typo: NameInfo, LookupKind, S, SS: &SS, CCC,
729 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
730 auto *ND = Corrected.getFoundDecl();
731 if (ND)
732 ND = getAsTemplateNameDecl(D: ND);
733 if (ND || Corrected.isKeyword()) {
734 if (LookupCtx) {
735 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
736 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
737 Name.getAsString() == CorrectedStr;
738 diagnoseTypo(Correction: Corrected,
739 TypoDiag: PDiag(DiagID: diag::err_non_template_in_member_template_id_suggest)
740 << Name << LookupCtx << DroppedSpecifier
741 << SS.getRange(), ErrorRecovery: false);
742 } else {
743 diagnoseTypo(Correction: Corrected,
744 TypoDiag: PDiag(DiagID: diag::err_non_template_in_template_id_suggest)
745 << Name, ErrorRecovery: false);
746 }
747 if (Found)
748 Diag(Loc: Found->getLocation(),
749 DiagID: diag::note_non_template_in_template_id_found);
750 return;
751 }
752 }
753
754 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_non_template_in_template_id)
755 << Name << SourceRange(Less, Greater);
756 if (Found)
757 Diag(Loc: Found->getLocation(), DiagID: diag::note_non_template_in_template_id_found);
758}
759
760ExprResult
761Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
762 SourceLocation TemplateKWLoc,
763 const DeclarationNameInfo &NameInfo,
764 bool isAddressOfOperand,
765 const TemplateArgumentListInfo *TemplateArgs) {
766 if (SS.isEmpty()) {
767 // FIXME: This codepath is only used by dependent unqualified names
768 // (e.g. a dependent conversion-function-id, or operator= once we support
769 // it). It doesn't quite do the right thing, and it will silently fail if
770 // getCurrentThisType() returns null.
771 QualType ThisType = getCurrentThisType();
772 if (ThisType.isNull())
773 return ExprError();
774
775 return CXXDependentScopeMemberExpr::Create(
776 Ctx: Context, /*Base=*/nullptr, BaseType: ThisType,
777 /*IsArrow=*/!Context.getLangOpts().HLSL,
778 /*OperatorLoc=*/SourceLocation(),
779 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
780 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
781 }
782 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
783}
784
785ExprResult
786Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
787 SourceLocation TemplateKWLoc,
788 const DeclarationNameInfo &NameInfo,
789 const TemplateArgumentListInfo *TemplateArgs) {
790 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
791 if (!SS.isValid())
792 return CreateRecoveryExpr(
793 Begin: SS.getBeginLoc(),
794 End: TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), SubExprs: {});
795
796 return DependentScopeDeclRefExpr::Create(
797 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
798 TemplateArgs);
799}
800
801ExprResult
802Sema::BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
803 QualType ParamType, SourceLocation Loc,
804 TemplateArgument Arg,
805 UnsignedOrNone PackIndex, bool Final) {
806 // The template argument itself might be an expression, in which case we just
807 // return that expression. This happens when substituting into an alias
808 // template.
809 Expr *Replacement;
810 if (Arg.getKind() == TemplateArgument::Expression) {
811 Replacement = Arg.getAsExpr();
812 } else {
813 ExprResult result =
814 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
815 if (result.isInvalid())
816 return ExprError();
817 Replacement = result.get();
818 }
819 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
820 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
821 AssociatedDecl, ParamType, Index, PackIndex, Final);
822}
823
824bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
825 NamedDecl *Instantiation,
826 bool InstantiatedFromMember,
827 const NamedDecl *Pattern,
828 const NamedDecl *PatternDef,
829 TemplateSpecializationKind TSK,
830 bool Complain, bool *Unreachable) {
831 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
832 isa<VarDecl>(Instantiation));
833
834 bool IsEntityBeingDefined = false;
835 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(Val: PatternDef))
836 IsEntityBeingDefined = TD->isBeingDefined();
837
838 if (PatternDef && !IsEntityBeingDefined) {
839 NamedDecl *SuggestedDef = nullptr;
840 if (!hasReachableDefinition(D: const_cast<NamedDecl *>(PatternDef),
841 Suggested: &SuggestedDef,
842 /*OnlyNeedComplete*/ false)) {
843 if (Unreachable)
844 *Unreachable = true;
845 // If we're allowed to diagnose this and recover, do so.
846 bool Recover = Complain && !isSFINAEContext();
847 if (Complain)
848 diagnoseMissingImport(Loc: PointOfInstantiation, Decl: SuggestedDef,
849 MIK: Sema::MissingImportKind::Definition, Recover);
850 return !Recover;
851 }
852 return false;
853 }
854
855 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
856 return true;
857
858 CanQualType InstantiationTy;
859 if (TagDecl *TD = dyn_cast<TagDecl>(Val: Instantiation))
860 InstantiationTy = Context.getCanonicalTagType(TD);
861 if (PatternDef) {
862 Diag(Loc: PointOfInstantiation,
863 DiagID: diag::err_template_instantiate_within_definition)
864 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
865 << InstantiationTy;
866 // Not much point in noting the template declaration here, since
867 // we're lexically inside it.
868 Instantiation->setInvalidDecl();
869 } else if (InstantiatedFromMember) {
870 if (isa<FunctionDecl>(Val: Instantiation)) {
871 Diag(Loc: PointOfInstantiation,
872 DiagID: diag::err_explicit_instantiation_undefined_member)
873 << /*member function*/ 1 << Instantiation->getDeclName()
874 << Instantiation->getDeclContext();
875 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
876 } else {
877 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
878 Diag(Loc: PointOfInstantiation,
879 DiagID: diag::err_implicit_instantiate_member_undefined)
880 << InstantiationTy;
881 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_member_declared_at);
882 }
883 } else {
884 if (isa<FunctionDecl>(Val: Instantiation)) {
885 Diag(Loc: PointOfInstantiation,
886 DiagID: diag::err_explicit_instantiation_undefined_func_template)
887 << Pattern;
888 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
889 } else if (isa<TagDecl>(Val: Instantiation)) {
890 Diag(Loc: PointOfInstantiation, DiagID: diag::err_template_instantiate_undefined)
891 << (TSK != TSK_ImplicitInstantiation)
892 << InstantiationTy;
893 NoteTemplateLocation(Decl: *Pattern);
894 } else {
895 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
896 if (isa<VarTemplateSpecializationDecl>(Val: Instantiation)) {
897 Diag(Loc: PointOfInstantiation,
898 DiagID: diag::err_explicit_instantiation_undefined_var_template)
899 << Instantiation;
900 Instantiation->setInvalidDecl();
901 } else
902 Diag(Loc: PointOfInstantiation,
903 DiagID: diag::err_explicit_instantiation_undefined_member)
904 << /*static data member*/ 2 << Instantiation->getDeclName()
905 << Instantiation->getDeclContext();
906 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
907 }
908 }
909
910 // In general, Instantiation isn't marked invalid to get more than one
911 // error for multiple undefined instantiations. But the code that does
912 // explicit declaration -> explicit definition conversion can't handle
913 // invalid declarations, so mark as invalid in that case.
914 if (TSK == TSK_ExplicitInstantiationDeclaration)
915 Instantiation->setInvalidDecl();
916 return true;
917}
918
919void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
920 bool SupportedForCompatibility) {
921 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
922
923 // C++23 [temp.local]p6:
924 // The name of a template-parameter shall not be bound to any following.
925 // declaration whose locus is contained by the scope to which the
926 // template-parameter belongs.
927 //
928 // When MSVC compatibility is enabled, the diagnostic is always a warning
929 // by default. Otherwise, it an error unless SupportedForCompatibility is
930 // true, in which case it is a default-to-error warning.
931 unsigned DiagId =
932 getLangOpts().MSVCCompat
933 ? diag::ext_template_param_shadow
934 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
935 : diag::err_template_param_shadow);
936 const auto *ND = cast<NamedDecl>(Val: PrevDecl);
937 Diag(Loc, DiagID: DiagId) << ND->getDeclName();
938 NoteTemplateParameterLocation(Decl: *ND);
939}
940
941TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
942 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(Val: D)) {
943 D = Temp->getTemplatedDecl();
944 return Temp;
945 }
946 return nullptr;
947}
948
949ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
950 SourceLocation EllipsisLoc) const {
951 assert(Kind == Template &&
952 "Only template template arguments can be pack expansions here");
953 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
954 "Template template argument pack expansion without packs");
955 ParsedTemplateArgument Result(*this);
956 Result.EllipsisLoc = EllipsisLoc;
957 return Result;
958}
959
960static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
961 const ParsedTemplateArgument &Arg) {
962
963 switch (Arg.getKind()) {
964 case ParsedTemplateArgument::Type: {
965 TypeSourceInfo *TSI;
966 QualType T = SemaRef.GetTypeFromParser(Ty: Arg.getAsType(), TInfo: &TSI);
967 if (!TSI)
968 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc: Arg.getNameLoc());
969 return TemplateArgumentLoc(TemplateArgument(T), TSI);
970 }
971
972 case ParsedTemplateArgument::NonType: {
973 Expr *E = Arg.getAsExpr();
974 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
975 }
976
977 case ParsedTemplateArgument::Template: {
978 TemplateName Template = Arg.getAsTemplate().get();
979 TemplateArgument TArg;
980 if (Arg.getEllipsisLoc().isValid())
981 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
982 else
983 TArg = Template;
984 return TemplateArgumentLoc(
985 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
986 Arg.getScopeSpec().getWithLocInContext(Context&: SemaRef.Context),
987 Arg.getNameLoc(), Arg.getEllipsisLoc());
988 }
989 }
990
991 llvm_unreachable("Unhandled parsed template argument");
992}
993
994void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
995 TemplateArgumentListInfo &TemplateArgs) {
996 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
997 TemplateArgs.addArgument(Loc: translateTemplateArgument(SemaRef&: *this,
998 Arg: TemplateArgsIn[I]));
999}
1000
1001static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
1002 SourceLocation Loc,
1003 const IdentifierInfo *Name) {
1004 NamedDecl *PrevDecl =
1005 SemaRef.LookupSingleName(S, Name, Loc, NameKind: Sema::LookupOrdinaryName,
1006 Redecl: RedeclarationKind::ForVisibleRedeclaration);
1007 if (PrevDecl && PrevDecl->isTemplateParameter())
1008 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
1009}
1010
1011ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
1012 TypeSourceInfo *TInfo;
1013 QualType T = GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TInfo);
1014 if (T.isNull())
1015 return ParsedTemplateArgument();
1016 assert(TInfo && "template argument with no location");
1017
1018 // If we might have formed a deduced template specialization type, convert
1019 // it to a template template argument.
1020 if (getLangOpts().CPlusPlus17) {
1021 TypeLoc TL = TInfo->getTypeLoc();
1022 SourceLocation EllipsisLoc;
1023 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1024 EllipsisLoc = PET.getEllipsisLoc();
1025 TL = PET.getPatternLoc();
1026 }
1027
1028 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1029 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1030 CXXScopeSpec SS;
1031 SS.Adopt(Other: DTST.getQualifierLoc());
1032 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1033 TemplateTy::make(P: Name),
1034 DTST.getTemplateNameLoc());
1035 if (EllipsisLoc.isValid())
1036 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1037 return Result;
1038 }
1039 }
1040
1041 // This is a normal type template argument. Note, if the type template
1042 // argument is an injected-class-name for a template, it has a dual nature
1043 // and can be used as either a type or a template. We handle that in
1044 // convertTypeTemplateArgumentToTemplate.
1045 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1046 ParsedType.get().getAsOpaquePtr(),
1047 TInfo->getTypeLoc().getBeginLoc());
1048}
1049
1050NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1051 SourceLocation EllipsisLoc,
1052 SourceLocation KeyLoc,
1053 IdentifierInfo *ParamName,
1054 SourceLocation ParamNameLoc,
1055 unsigned Depth, unsigned Position,
1056 SourceLocation EqualLoc,
1057 ParsedType DefaultArg,
1058 bool HasTypeConstraint) {
1059 assert(S->isTemplateParamScope() &&
1060 "Template type parameter not in template parameter scope!");
1061
1062 bool IsParameterPack = EllipsisLoc.isValid();
1063 TemplateTypeParmDecl *Param
1064 = TemplateTypeParmDecl::Create(C: Context, DC: Context.getTranslationUnitDecl(),
1065 KeyLoc, NameLoc: ParamNameLoc, D: Depth, P: Position,
1066 Id: ParamName, Typename, ParameterPack: IsParameterPack,
1067 HasTypeConstraint);
1068 Param->setAccess(AS_public);
1069
1070 if (Param->isParameterPack())
1071 if (auto *CSI = getEnclosingLambdaOrBlock())
1072 CSI->LocalPacks.push_back(Elt: Param);
1073
1074 if (ParamName) {
1075 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: ParamNameLoc, Name: ParamName);
1076
1077 // Add the template parameter into the current scope.
1078 S->AddDecl(D: Param);
1079 IdResolver.AddDecl(D: Param);
1080 }
1081
1082 // C++0x [temp.param]p9:
1083 // A default template-argument may be specified for any kind of
1084 // template-parameter that is not a template parameter pack.
1085 if (DefaultArg && IsParameterPack) {
1086 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1087 DefaultArg = nullptr;
1088 }
1089
1090 // Handle the default argument, if provided.
1091 if (DefaultArg) {
1092 TypeSourceInfo *DefaultTInfo;
1093 GetTypeFromParser(Ty: DefaultArg, TInfo: &DefaultTInfo);
1094
1095 assert(DefaultTInfo && "expected source information for type");
1096
1097 // Check for unexpanded parameter packs.
1098 if (DiagnoseUnexpandedParameterPack(Loc: ParamNameLoc, T: DefaultTInfo,
1099 UPPC: UPPC_DefaultArgument))
1100 return Param;
1101
1102 // Check the template argument itself.
1103 if (CheckTemplateArgument(Arg: DefaultTInfo)) {
1104 Param->setInvalidDecl();
1105 return Param;
1106 }
1107
1108 Param->setDefaultArgument(
1109 C: Context, DefArg: TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1110 }
1111
1112 return Param;
1113}
1114
1115/// Convert the parser's template argument list representation into our form.
1116static TemplateArgumentListInfo
1117makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1118 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1119 TemplateId.RAngleLoc);
1120 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1121 TemplateId.NumArgs);
1122 S.translateTemplateArguments(TemplateArgsIn: TemplateArgsPtr, TemplateArgs);
1123 return TemplateArgs;
1124}
1125
1126bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1127
1128 TemplateName TN = TypeConstr->Template.get();
1129 NamedDecl *CD = nullptr;
1130 bool IsTypeConcept = false;
1131 bool RequiresArguments = false;
1132 if (auto *TTP = TN.getAsTemplateTemplateParmDecl()) {
1133 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1134 RequiresArguments =
1135 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1136 CD = TTP;
1137 } else {
1138 CD = TN.getAsTemplateDecl();
1139 IsTypeConcept = cast<ConceptDecl>(Val: CD)->isTypeConcept();
1140 RequiresArguments = cast<ConceptDecl>(Val: CD)
1141 ->getTemplateParameters()
1142 ->getMinRequiredArguments() > 1;
1143 }
1144
1145 // C++2a [temp.param]p4:
1146 // [...] The concept designated by a type-constraint shall be a type
1147 // concept ([temp.concept]).
1148 if (!IsTypeConcept) {
1149 Diag(Loc: TypeConstr->TemplateNameLoc,
1150 DiagID: diag::err_type_constraint_non_type_concept);
1151 return true;
1152 }
1153
1154 if (CheckConceptUseInDefinition(Concept: CD, Loc: TypeConstr->TemplateNameLoc))
1155 return true;
1156
1157 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1158
1159 if (!WereArgsSpecified && RequiresArguments) {
1160 Diag(Loc: TypeConstr->TemplateNameLoc,
1161 DiagID: diag::err_type_constraint_missing_arguments)
1162 << CD;
1163 return true;
1164 }
1165 return false;
1166}
1167
1168bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1169 TemplateIdAnnotation *TypeConstr,
1170 TemplateTypeParmDecl *ConstrainedParameter,
1171 SourceLocation EllipsisLoc) {
1172 return BuildTypeConstraint(SS, TypeConstraint: TypeConstr, ConstrainedParameter, EllipsisLoc,
1173 AllowUnexpandedPack: false);
1174}
1175
1176bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1177 TemplateIdAnnotation *TypeConstr,
1178 TemplateTypeParmDecl *ConstrainedParameter,
1179 SourceLocation EllipsisLoc,
1180 bool AllowUnexpandedPack) {
1181
1182 if (CheckTypeConstraint(TypeConstr))
1183 return true;
1184
1185 TemplateName TN = TypeConstr->Template.get();
1186 UsingShadowDecl *USD = TN.getAsUsingShadowDecl();
1187 TemplateDecl *CD = TN.getAsTemplateDecl();
1188
1189 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1190 TypeConstr->TemplateNameLoc);
1191
1192 TemplateArgumentListInfo TemplateArgs;
1193 if (TypeConstr->LAngleLoc.isValid()) {
1194 TemplateArgs =
1195 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TypeConstr);
1196
1197 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1198 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1199 if (DiagnoseUnexpandedParameterPack(Arg, UPPC: UPPC_TypeConstraint))
1200 return true;
1201 }
1202 }
1203 }
1204 return AttachTypeConstraint(
1205 NS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1206 NameInfo: ConceptName, NamedConcept: TN,
1207 /*FoundDecl=*/USD ? cast<NamedDecl>(Val: USD) : cast_if_present<NamedDecl>(Val: CD),
1208 TemplateArgs: TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1209 ConstrainedParameter, EllipsisLoc);
1210}
1211
1212template <typename ArgumentLocAppender>
1213static ExprResult formImmediatelyDeclaredConstraint(
1214 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1215 TemplateName NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1216 SourceLocation RAngleLoc, QualType ConstrainedType,
1217 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1218 SourceLocation EllipsisLoc) {
1219
1220 TemplateArgumentListInfo ConstraintArgs;
1221 ConstraintArgs.addArgument(
1222 Loc: S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(ConstrainedType),
1223 /*NTTPType=*/QualType(), Loc: ParamNameLoc));
1224
1225 ConstraintArgs.setRAngleLoc(RAngleLoc);
1226 ConstraintArgs.setLAngleLoc(LAngleLoc);
1227 Appender(ConstraintArgs);
1228
1229 // C++2a [temp.param]p4:
1230 // [...] This constraint-expression E is called the immediately-declared
1231 // constraint of T. [...]
1232 CXXScopeSpec SS;
1233 SS.Adopt(Other: NS);
1234 ExprResult ImmediatelyDeclaredConstraint;
1235 if (auto *CD =
1236 dyn_cast_if_present<ConceptDecl>(Val: NamedConcept.getAsTemplateDecl())) {
1237 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1238 SS, /*TemplateKWLoc=*/SourceLocation(), ConceptNameInfo: NameInfo,
1239 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, NamedConcept: CD, TemplateArgs: &ConstraintArgs,
1240 /*DoCheckConstraintSatisfaction=*/
1241 !S.inParameterMappingSubstitution());
1242 }
1243 // We have a template template parameter
1244 else {
1245 assert(SS.isEmpty() && "template parameter with a scope specifier?");
1246 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1247 NameInfo, Template: NamedConcept, TemplateArgs: &ConstraintArgs);
1248 }
1249 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1250 return ImmediatelyDeclaredConstraint;
1251
1252 // C++2a [temp.param]p4:
1253 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1254 //
1255 // We have the following case:
1256 //
1257 // template<typename T> concept C1 = true;
1258 // template<C1... T> struct s1;
1259 //
1260 // The constraint: (C1<T> && ...)
1261 //
1262 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1263 // any unqualified lookups for 'operator&&' here.
1264 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/Callee: nullptr,
1265 /*LParenLoc=*/SourceLocation(),
1266 LHS: ImmediatelyDeclaredConstraint.get(), Operator: BO_LAnd,
1267 EllipsisLoc, /*RHS=*/nullptr,
1268 /*RParenLoc=*/SourceLocation(),
1269 /*NumExpansions=*/std::nullopt);
1270}
1271
1272bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1273 DeclarationNameInfo NameInfo,
1274 TemplateName NamedConcept, NamedDecl *FoundDecl,
1275 const TemplateArgumentListInfo *TemplateArgs,
1276 TemplateTypeParmDecl *ConstrainedParameter,
1277 SourceLocation EllipsisLoc) {
1278 // C++2a [temp.param]p4:
1279 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1280 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1281 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1282 TemplateArgs ? ASTTemplateArgumentListInfo::Create(C: Context,
1283 List: *TemplateArgs) : nullptr;
1284
1285 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1286
1287 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1288 S&: *this, NS, NameInfo, NamedConcept, FoundDecl,
1289 LAngleLoc: TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1290 RAngleLoc: TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1291 ConstrainedType: ParamAsArgument, ParamNameLoc: ConstrainedParameter->getLocation(),
1292 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1293 if (TemplateArgs)
1294 for (const auto &ArgLoc : TemplateArgs->arguments())
1295 ConstraintArgs.addArgument(Loc: ArgLoc);
1296 },
1297 EllipsisLoc);
1298 if (ImmediatelyDeclaredConstraint.isInvalid())
1299 return true;
1300
1301 auto *CL = ConceptReference::Create(C: Context, /*NNS=*/NS,
1302 /*TemplateKWLoc=*/SourceLocation{},
1303 /*ConceptNameInfo=*/NameInfo,
1304 /*FoundDecl=*/FoundDecl,
1305 /*NamedConcept=*/NamedConcept,
1306 /*ArgsWritten=*/ArgsAsWritten);
1307 ConstrainedParameter->setTypeConstraint(
1308 CR: CL, ImmediatelyDeclaredConstraint: ImmediatelyDeclaredConstraint.get(), ArgPackSubstIndex: std::nullopt);
1309 return false;
1310}
1311
1312bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1313 NonTypeTemplateParmDecl *NewConstrainedParm,
1314 NonTypeTemplateParmDecl *OrigConstrainedParm,
1315 SourceLocation EllipsisLoc) {
1316 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1317 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1318 Diag(Loc: NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1319 DiagID: diag::err_unsupported_placeholder_constraint)
1320 << NewConstrainedParm->getTypeSourceInfo()
1321 ->getTypeLoc()
1322 .getSourceRange();
1323 NewConstrainedParm->setType(TL.getType());
1324 return true;
1325 }
1326 // FIXME: Concepts: This should be the type of the placeholder, but this is
1327 // unclear in the wording right now.
1328 DeclRefExpr *Ref =
1329 BuildDeclRefExpr(D: OrigConstrainedParm, Ty: OrigConstrainedParm->getType(),
1330 VK: VK_PRValue, Loc: OrigConstrainedParm->getLocation());
1331 if (!Ref)
1332 return true;
1333 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1334 S&: *this, NS: TL.getNestedNameSpecifierLoc(), NameInfo: TL.getConceptNameInfo(),
1335 NamedConcept: TL.getNamedConcept(),
1336 /*FoundDecl=*/TL.getFoundDecl(), LAngleLoc: TL.getLAngleLoc(), RAngleLoc: TL.getRAngleLoc(),
1337 ConstrainedType: BuildDecltypeType(E: Ref), ParamNameLoc: OrigConstrainedParm->getLocation(),
1338 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1339 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1340 ConstraintArgs.addArgument(Loc: TL.getArgLoc(i: I));
1341 },
1342 EllipsisLoc);
1343 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1344 !ImmediatelyDeclaredConstraint.isUsable())
1345 return true;
1346
1347 NewConstrainedParm->setPlaceholderTypeConstraint(
1348 ImmediatelyDeclaredConstraint.get());
1349 return false;
1350}
1351
1352QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1353 SourceLocation Loc) {
1354 if (TSI->getType()->isUndeducedType()) {
1355 // C++17 [temp.dep.expr]p3:
1356 // An id-expression is type-dependent if it contains
1357 // - an identifier associated by name lookup with a non-type
1358 // template-parameter declared with a type that contains a
1359 // placeholder type (7.1.7.4),
1360 TypeSourceInfo *NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSI);
1361 if (!NewTSI)
1362 return QualType();
1363 TSI = NewTSI;
1364 }
1365
1366 return CheckNonTypeTemplateParameterType(T: TSI->getType(), Loc);
1367}
1368
1369bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1370 if (T->isDependentType())
1371 return false;
1372
1373 if (RequireCompleteType(Loc, T, DiagID: diag::err_template_nontype_parm_incomplete))
1374 return true;
1375
1376 if (T->isStructuralType())
1377 return false;
1378
1379 // Structural types are required to be object types or lvalue references.
1380 if (T->isRValueReferenceType()) {
1381 Diag(Loc, DiagID: diag::err_template_nontype_parm_rvalue_ref) << T;
1382 return true;
1383 }
1384
1385 // Don't mention structural types in our diagnostic prior to C++20. Also,
1386 // there's not much more we can say about non-scalar non-class types --
1387 // because we can't see functions or arrays here, those can only be language
1388 // extensions.
1389 if (!getLangOpts().CPlusPlus20 ||
1390 (!T->isScalarType() && !T->isRecordType())) {
1391 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_type) << T;
1392 return true;
1393 }
1394
1395 // Structural types are required to be literal types.
1396 if (RequireLiteralType(Loc, T, DiagID: diag::err_template_nontype_parm_not_literal))
1397 return true;
1398
1399 Diag(Loc, DiagID: diag::err_template_nontype_parm_not_structural) << T;
1400
1401 // Drill down into the reason why the class is non-structural.
1402 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1403 // All members are required to be public and non-mutable, and can't be of
1404 // rvalue reference type. Check these conditions first to prefer a "local"
1405 // reason over a more distant one.
1406 for (const FieldDecl *FD : RD->fields()) {
1407 if (FD->getAccess() != AS_public) {
1408 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_non_public) << T << 0;
1409 return true;
1410 }
1411 if (FD->isMutable()) {
1412 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_mutable_field) << T;
1413 return true;
1414 }
1415 if (FD->getType()->isRValueReferenceType()) {
1416 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_rvalue_ref_field)
1417 << T;
1418 return true;
1419 }
1420 }
1421
1422 // All bases are required to be public.
1423 for (const auto &BaseSpec : RD->bases()) {
1424 if (BaseSpec.getAccessSpecifier() != AS_public) {
1425 Diag(Loc: BaseSpec.getBaseTypeLoc(), DiagID: diag::note_not_structural_non_public)
1426 << T << 1;
1427 return true;
1428 }
1429 }
1430
1431 // All subobjects are required to be of structural types.
1432 SourceLocation SubLoc;
1433 QualType SubType;
1434 int Kind = -1;
1435
1436 for (const FieldDecl *FD : RD->fields()) {
1437 QualType T = Context.getBaseElementType(QT: FD->getType());
1438 if (!T->isStructuralType()) {
1439 SubLoc = FD->getLocation();
1440 SubType = T;
1441 Kind = 0;
1442 break;
1443 }
1444 }
1445
1446 if (Kind == -1) {
1447 for (const auto &BaseSpec : RD->bases()) {
1448 QualType T = BaseSpec.getType();
1449 if (!T->isStructuralType()) {
1450 SubLoc = BaseSpec.getBaseTypeLoc();
1451 SubType = T;
1452 Kind = 1;
1453 break;
1454 }
1455 }
1456 }
1457
1458 assert(Kind != -1 && "couldn't find reason why type is not structural");
1459 Diag(Loc: SubLoc, DiagID: diag::note_not_structural_subobject)
1460 << T << Kind << SubType;
1461 T = SubType;
1462 RD = T->getAsCXXRecordDecl();
1463 }
1464
1465 return true;
1466}
1467
1468QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1469 SourceLocation Loc) {
1470 // We don't allow variably-modified types as the type of non-type template
1471 // parameters.
1472 if (T->isVariablyModifiedType()) {
1473 Diag(Loc, DiagID: diag::err_variably_modified_nontype_template_param)
1474 << T;
1475 return QualType();
1476 }
1477
1478 if (T->isBlockPointerType()) {
1479 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_type) << T;
1480 return QualType();
1481 }
1482
1483 // C++ [temp.param]p4:
1484 //
1485 // A non-type template-parameter shall have one of the following
1486 // (optionally cv-qualified) types:
1487 //
1488 // -- integral or enumeration type,
1489 if (T->isIntegralOrEnumerationType() ||
1490 // -- pointer to object or pointer to function,
1491 T->isPointerType() ||
1492 // -- lvalue reference to object or lvalue reference to function,
1493 T->isLValueReferenceType() ||
1494 // -- pointer to member,
1495 T->isMemberPointerType() ||
1496 // -- std::nullptr_t, or
1497 T->isNullPtrType() ||
1498 // -- a type that contains a placeholder type.
1499 T->isUndeducedType()) {
1500 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1501 // are ignored when determining its type.
1502 return T.getUnqualifiedType();
1503 }
1504
1505 // C++ [temp.param]p8:
1506 //
1507 // A non-type template-parameter of type "array of T" or
1508 // "function returning T" is adjusted to be of type "pointer to
1509 // T" or "pointer to function returning T", respectively.
1510 if (T->isArrayType() || T->isFunctionType())
1511 return Context.getDecayedType(T);
1512
1513 // If T is a dependent type, we can't do the check now, so we
1514 // assume that it is well-formed. Note that stripping off the
1515 // qualifiers here is not really correct if T turns out to be
1516 // an array type, but we'll recompute the type everywhere it's
1517 // used during instantiation, so that should be OK. (Using the
1518 // qualified type is equally wrong.)
1519 if (T->isDependentType())
1520 return T.getUnqualifiedType();
1521
1522 // C++20 [temp.param]p6:
1523 // -- a structural type
1524 if (RequireStructuralType(T, Loc))
1525 return QualType();
1526
1527 if (!getLangOpts().CPlusPlus20) {
1528 // FIXME: Consider allowing structural types as an extension in C++17. (In
1529 // earlier language modes, the template argument evaluation rules are too
1530 // inflexible.)
1531 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_structural_type) << T;
1532 return QualType();
1533 }
1534
1535 Diag(Loc, DiagID: diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1536 return T.getUnqualifiedType();
1537}
1538
1539NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1540 unsigned Depth,
1541 unsigned Position,
1542 SourceLocation EqualLoc,
1543 Expr *Default) {
1544 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1545
1546 // Check that we have valid decl-specifiers specified.
1547 auto CheckValidDeclSpecifiers = [this, &D] {
1548 // C++ [temp.param]
1549 // p1
1550 // template-parameter:
1551 // ...
1552 // parameter-declaration
1553 // p2
1554 // ... A storage class shall not be specified in a template-parameter
1555 // declaration.
1556 // [dcl.typedef]p1:
1557 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1558 // of a parameter-declaration
1559 const DeclSpec &DS = D.getDeclSpec();
1560 auto EmitDiag = [this](SourceLocation Loc) {
1561 Diag(Loc, DiagID: diag::err_invalid_decl_specifier_in_nontype_parm)
1562 << FixItHint::CreateRemoval(RemoveRange: Loc);
1563 };
1564 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1565 EmitDiag(DS.getStorageClassSpecLoc());
1566
1567 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1568 EmitDiag(DS.getThreadStorageClassSpecLoc());
1569
1570 // [dcl.inline]p1:
1571 // The inline specifier can be applied only to the declaration or
1572 // definition of a variable or function.
1573
1574 if (DS.isInlineSpecified())
1575 EmitDiag(DS.getInlineSpecLoc());
1576
1577 // [dcl.constexpr]p1:
1578 // The constexpr specifier shall be applied only to the definition of a
1579 // variable or variable template or the declaration of a function or
1580 // function template.
1581
1582 if (DS.hasConstexprSpecifier())
1583 EmitDiag(DS.getConstexprSpecLoc());
1584
1585 // [dcl.fct.spec]p1:
1586 // Function-specifiers can be used only in function declarations.
1587
1588 if (DS.isVirtualSpecified())
1589 EmitDiag(DS.getVirtualSpecLoc());
1590
1591 if (DS.hasExplicitSpecifier())
1592 EmitDiag(DS.getExplicitSpecLoc());
1593
1594 if (DS.isNoreturnSpecified())
1595 EmitDiag(DS.getNoreturnSpecLoc());
1596 };
1597
1598 CheckValidDeclSpecifiers();
1599
1600 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1601 if (isa<AutoType>(Val: T))
1602 Diag(Loc: D.getIdentifierLoc(),
1603 DiagID: diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1604 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1605
1606 assert(S->isTemplateParamScope() &&
1607 "Non-type template parameter not in template parameter scope!");
1608 bool Invalid = false;
1609
1610 QualType T = CheckNonTypeTemplateParameterType(TSI&: TInfo, Loc: D.getIdentifierLoc());
1611 if (T.isNull()) {
1612 T = Context.IntTy; // Recover with an 'int' type.
1613 Invalid = true;
1614 }
1615
1616 CheckFunctionOrTemplateParamDeclarator(S, D);
1617
1618 const IdentifierInfo *ParamName = D.getIdentifier();
1619 bool IsParameterPack = D.hasEllipsis();
1620 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1621 C: Context, DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
1622 IdLoc: D.getIdentifierLoc(), D: Depth, P: Position, Id: ParamName, T, ParameterPack: IsParameterPack,
1623 TInfo);
1624 Param->setAccess(AS_public);
1625
1626 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1627 if (TL.isConstrained()) {
1628 if (D.getEllipsisLoc().isInvalid() &&
1629 T->containsUnexpandedParameterPack()) {
1630 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1631 for (auto &Loc :
1632 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1633 Invalid |= DiagnoseUnexpandedParameterPack(
1634 Arg: Loc, UPPC: UnexpandedParameterPackContext::UPPC_TypeConstraint);
1635 }
1636 if (!Invalid &&
1637 AttachTypeConstraint(TL, NewConstrainedParm: Param, OrigConstrainedParm: Param, EllipsisLoc: D.getEllipsisLoc()))
1638 Invalid = true;
1639 }
1640
1641 if (Invalid)
1642 Param->setInvalidDecl();
1643
1644 if (Param->isParameterPack())
1645 if (auto *CSI = getEnclosingLambdaOrBlock())
1646 CSI->LocalPacks.push_back(Elt: Param);
1647
1648 if (ParamName) {
1649 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: D.getIdentifierLoc(),
1650 Name: ParamName);
1651
1652 // Add the template parameter into the current scope.
1653 S->AddDecl(D: Param);
1654 IdResolver.AddDecl(D: Param);
1655 }
1656
1657 // C++0x [temp.param]p9:
1658 // A default template-argument may be specified for any kind of
1659 // template-parameter that is not a template parameter pack.
1660 if (Default && IsParameterPack) {
1661 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1662 Default = nullptr;
1663 }
1664
1665 // Check the well-formedness of the default template argument, if provided.
1666 if (Default) {
1667 // Check for unexpanded parameter packs.
1668 if (DiagnoseUnexpandedParameterPack(E: Default, UPPC: UPPC_DefaultArgument))
1669 return Param;
1670
1671 Param->setDefaultArgument(
1672 C: Context, DefArg: getTrivialTemplateArgumentLoc(
1673 Arg: TemplateArgument(Default, /*IsCanonical=*/false),
1674 NTTPType: QualType(), Loc: SourceLocation()));
1675 }
1676
1677 return Param;
1678}
1679
1680/// ActOnTemplateTemplateParameter - Called when a C++ template template
1681/// parameter (e.g. T in template <template \<typename> class T> class array)
1682/// has been parsed. S is the current scope.
1683NamedDecl *Sema::ActOnTemplateTemplateParameter(
1684 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1685 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1686 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1687 unsigned Position, SourceLocation EqualLoc,
1688 ParsedTemplateArgument Default) {
1689 assert(S->isTemplateParamScope() &&
1690 "Template template parameter not in template parameter scope!");
1691
1692 bool IsParameterPack = EllipsisLoc.isValid();
1693
1694 SourceLocation Loc = NameLoc.isInvalid() ? TmpLoc : NameLoc;
1695 if (Params->size() == 0) {
1696 Diag(Loc, DiagID: diag::err_template_template_parm_no_parms)
1697 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1698
1699 // Recover as if there was a type template parameter pack.
1700 SmallVector<NamedDecl *, 4> ParamDecls;
1701 ParamDecls.push_back(Elt: TemplateTypeParmDecl::Create(
1702 C: Context, DC: Context.getTranslationUnitDecl(), KeyLoc: Loc, NameLoc: SourceLocation(),
1703 D: Depth + 1, P: 0, /*Id=*/nullptr,
1704 /*Typename=*/false, /*ParameterPack=*/true));
1705 Params = TemplateParameterList::Create(
1706 C: Context, TemplateLoc: Params->getTemplateLoc(), LAngleLoc: Params->getLAngleLoc(), Params: ParamDecls,
1707 RAngleLoc: Params->getRAngleLoc(), RequiresClause: Params->getRequiresClause());
1708 }
1709
1710 bool Invalid = false;
1711 if (CheckTemplateParameterList(
1712 NewParams: Params,
1713 /*OldParams=*/nullptr,
1714 TPC: IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1715 Invalid = true;
1716
1717 // Construct the parameter object.
1718 TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(
1719 C: Context, DC: Context.getTranslationUnitDecl(), L: Loc, D: Depth, P: Position,
1720 ParameterPack: IsParameterPack, Id: Name, ParameterKind: Kind, Typename, Params);
1721 Param->setAccess(AS_public);
1722
1723 if (Param->isParameterPack())
1724 if (auto *LSI = getEnclosingLambdaOrBlock())
1725 LSI->LocalPacks.push_back(Elt: Param);
1726
1727 // If the template template parameter has a name, then link the identifier
1728 // into the scope and lookup mechanisms.
1729 if (Name) {
1730 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: NameLoc, Name);
1731
1732 S->AddDecl(D: Param);
1733 IdResolver.AddDecl(D: Param);
1734 }
1735
1736 if (Invalid)
1737 Param->setInvalidDecl();
1738
1739 // C++0x [temp.param]p9:
1740 // A default template-argument may be specified for any kind of
1741 // template-parameter that is not a template parameter pack.
1742 if (IsParameterPack && !Default.isInvalid()) {
1743 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1744 Default = ParsedTemplateArgument();
1745 }
1746
1747 if (!Default.isInvalid()) {
1748 // Check only that we have a template template argument. We don't want to
1749 // try to check well-formedness now, because our template template parameter
1750 // might have dependent types in its template parameters, which we wouldn't
1751 // be able to match now.
1752 //
1753 // If none of the template template parameter's template arguments mention
1754 // other template parameters, we could actually perform more checking here.
1755 // However, it isn't worth doing.
1756 TemplateArgumentLoc DefaultArg = translateTemplateArgument(SemaRef&: *this, Arg: Default);
1757 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1758 Diag(Loc: DefaultArg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
1759 << DefaultArg.getSourceRange();
1760 return Param;
1761 }
1762
1763 TemplateName Name =
1764 DefaultArg.getArgument().getAsTemplateOrTemplatePattern();
1765 TemplateDecl *Template = Name.getAsTemplateDecl();
1766 if (Template &&
1767 !CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg: DefaultArg)) {
1768 return Param;
1769 }
1770
1771 // Check for unexpanded parameter packs.
1772 if (DiagnoseUnexpandedParameterPack(Loc: DefaultArg.getLocation(),
1773 Template: DefaultArg.getArgument().getAsTemplate(),
1774 UPPC: UPPC_DefaultArgument))
1775 return Param;
1776
1777 Param->setDefaultArgument(C: Context, DefArg: DefaultArg);
1778 }
1779
1780 return Param;
1781}
1782
1783namespace {
1784class ConstraintRefersToContainingTemplateChecker
1785 : public ConstDynamicRecursiveASTVisitor {
1786 using inherited = ConstDynamicRecursiveASTVisitor;
1787 bool Result = false;
1788 const FunctionDecl *Friend = nullptr;
1789 unsigned TemplateDepth = 0;
1790
1791 // Check a record-decl that we've seen to see if it is a lexical parent of the
1792 // Friend, likely because it was referred to without its template arguments.
1793 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1794 CheckingRD = CheckingRD->getMostRecentDecl();
1795 if (!CheckingRD->isTemplated())
1796 return true;
1797
1798 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1799 DC && !DC->isFileContext(); DC = DC->getParent())
1800 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
1801 if (CheckingRD == RD->getMostRecentDecl()) {
1802 Result = true;
1803 return false;
1804 }
1805
1806 return true;
1807 }
1808
1809 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1810 if (D->getDepth() < TemplateDepth)
1811 Result = true;
1812
1813 // Necessary because the type of the NTTP might be what refers to the parent
1814 // constriant.
1815 return TraverseType(T: D->getType());
1816 }
1817
1818public:
1819 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1820 unsigned TemplateDepth)
1821 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1822
1823 bool getResult() const { return Result; }
1824
1825 // This should be the only template parm type that we have to deal with.
1826 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1827 // FunctionParmPackExpr are all partially substituted, which cannot happen
1828 // with concepts at this point in translation.
1829 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1830 if (Type->getDecl()->getDepth() < TemplateDepth) {
1831 Result = true;
1832 return false;
1833 }
1834 return true;
1835 }
1836
1837 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1838 return TraverseDecl(D: E->getDecl());
1839 }
1840
1841 bool TraverseTypedefType(const TypedefType *TT,
1842 bool /*TraverseQualifier*/) override {
1843 return TraverseType(T: TT->desugar());
1844 }
1845
1846 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1847 // We don't care about TypeLocs. So traverse Types instead.
1848 return TraverseType(T: TL.getType(), TraverseQualifier);
1849 }
1850
1851 bool VisitTagType(const TagType *T) override {
1852 return TraverseDecl(D: T->getDecl());
1853 }
1854
1855 bool TraverseDecl(const Decl *D) override {
1856 assert(D);
1857 // FIXME : This is possibly an incomplete list, but it is unclear what other
1858 // Decl kinds could be used to refer to the template parameters. This is a
1859 // best guess so far based on examples currently available, but the
1860 // unreachable should catch future instances/cases.
1861 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
1862 return TraverseType(T: TD->getUnderlyingType());
1863 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Val: D))
1864 return CheckNonTypeTemplateParmDecl(D: NTTPD);
1865 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
1866 return TraverseType(T: VD->getType());
1867 if (isa<TemplateDecl>(Val: D))
1868 return true;
1869 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1870 return CheckIfContainingRecord(CheckingRD: RD);
1871
1872 if (isa<NamedDecl, RequiresExprBodyDecl>(Val: D)) {
1873 // No direct types to visit here I believe.
1874 } else
1875 llvm_unreachable("Don't know how to handle this declaration type yet");
1876 return true;
1877 }
1878};
1879} // namespace
1880
1881bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1882 const FunctionDecl *Friend, unsigned TemplateDepth,
1883 const Expr *Constraint) {
1884 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1885 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1886 Checker.TraverseStmt(S: Constraint);
1887 return Checker.getResult();
1888}
1889
1890TemplateParameterList *
1891Sema::ActOnTemplateParameterList(unsigned Depth,
1892 SourceLocation ExportLoc,
1893 SourceLocation TemplateLoc,
1894 SourceLocation LAngleLoc,
1895 ArrayRef<NamedDecl *> Params,
1896 SourceLocation RAngleLoc,
1897 Expr *RequiresClause) {
1898 if (ExportLoc.isValid())
1899 Diag(Loc: ExportLoc, DiagID: diag::warn_template_export_unsupported);
1900
1901 for (NamedDecl *P : Params)
1902 warnOnReservedIdentifier(D: P);
1903
1904 return TemplateParameterList::Create(C: Context, TemplateLoc, LAngleLoc,
1905 Params: llvm::ArrayRef(Params), RAngleLoc,
1906 RequiresClause);
1907}
1908
1909static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1910 const CXXScopeSpec &SS) {
1911 if (SS.isSet())
1912 T->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
1913}
1914
1915// Returns the template parameter list with all default template argument
1916// information.
1917TemplateParameterList *Sema::GetTemplateParameterList(TemplateDecl *TD) {
1918 // Make sure we get the template parameter list from the most
1919 // recent declaration, since that is the only one that is guaranteed to
1920 // have all the default template argument information.
1921 Decl *D = TD->getMostRecentDecl();
1922 // C++11 N3337 [temp.param]p12:
1923 // A default template argument shall not be specified in a friend class
1924 // template declaration.
1925 //
1926 // Skip past friend *declarations* because they are not supposed to contain
1927 // default template arguments. Moreover, these declarations may introduce
1928 // template parameters living in different template depths than the
1929 // corresponding template parameters in TD, causing unmatched constraint
1930 // substitution.
1931 //
1932 // FIXME: Diagnose such cases within a class template:
1933 // template <class T>
1934 // struct S {
1935 // template <class = void> friend struct C;
1936 // };
1937 // template struct S<int>;
1938 while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1939 D->getPreviousDecl())
1940 D = D->getPreviousDecl();
1941 return cast<TemplateDecl>(Val: D)->getTemplateParameters();
1942}
1943
1944DeclResult Sema::CheckClassTemplate(
1945 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1946 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1947 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1948 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1949 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1950 TemplateParameterList **OuterTemplateParamLists,
1951 bool IsMemberSpecialization, SkipBodyInfo *SkipBody) {
1952 assert(TemplateParams && TemplateParams->size() > 0 &&
1953 "No template parameters");
1954 assert(TUK != TagUseKind::Reference &&
1955 "Can only declare or define class templates");
1956 bool Invalid = false;
1957
1958 // Check that we can declare a template here.
1959 if (CheckTemplateDeclScope(S, TemplateParams))
1960 return true;
1961
1962 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
1963 assert(Kind != TagTypeKind::Enum &&
1964 "can't build template of enumerated type");
1965
1966 // There is no such thing as an unnamed class template.
1967 if (!Name) {
1968 Diag(Loc: KWLoc, DiagID: diag::err_template_unnamed_class);
1969 return true;
1970 }
1971
1972 // Find any previous declaration with this name. For a friend with no
1973 // scope explicitly specified, we only look for tag declarations (per
1974 // C++11 [basic.lookup.elab]p2).
1975 DeclContext *SemanticContext;
1976 LookupResult Previous(*this, Name, NameLoc,
1977 (SS.isEmpty() && TUK == TagUseKind::Friend)
1978 ? LookupTagName
1979 : LookupOrdinaryName,
1980 forRedeclarationInCurContext());
1981 if (SS.isNotEmpty() && !SS.isInvalid()) {
1982 SemanticContext = computeDeclContext(SS, EnteringContext: true);
1983 if (!SemanticContext) {
1984 Diag(Loc: NameLoc, DiagID: diag::err_template_qualified_declarator_no_match)
1985 << SS.getScopeRep() << SS.getRange();
1986 return true;
1987 }
1988
1989 if (RequireCompleteDeclContext(SS, DC: SemanticContext))
1990 return true;
1991
1992 // If we're adding a template to a dependent context, we may need to
1993 // rebuilding some of the types used within the template parameter list,
1994 // now that we know what the current instantiation is.
1995 if (SemanticContext->isDependentContext()) {
1996 ContextRAII SavedContext(*this, SemanticContext);
1997 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
1998 Invalid = true;
1999 }
2000
2001 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference &&
2002 diagnoseQualifiedDeclaration(SS, DC: SemanticContext, Name, Loc: NameLoc,
2003 /*TemplateId=*/nullptr,
2004 IsMemberSpecialization))
2005 return true;
2006
2007 LookupQualifiedName(R&: Previous, LookupCtx: SemanticContext);
2008 } else {
2009 SemanticContext = CurContext;
2010
2011 // C++14 [class.mem]p14:
2012 // If T is the name of a class, then each of the following shall have a
2013 // name different from T:
2014 // -- every member template of class T
2015 if (TUK != TagUseKind::Friend &&
2016 DiagnoseClassNameShadow(DC: SemanticContext,
2017 Info: DeclarationNameInfo(Name, NameLoc)))
2018 return true;
2019
2020 LookupName(R&: Previous, S);
2021 }
2022
2023 if (Previous.isAmbiguous())
2024 return true;
2025
2026 // Let the template parameter scope enter the lookup chain of the current
2027 // class template. For example, given
2028 //
2029 // namespace ns {
2030 // template <class> bool Param = false;
2031 // template <class T> struct N;
2032 // }
2033 //
2034 // template <class Param> struct ns::N { void foo(Param); };
2035 //
2036 // When we reference Param inside the function parameter list, our name lookup
2037 // chain for it should be like:
2038 // FunctionScope foo
2039 // -> RecordScope N
2040 // -> TemplateParamScope (where we will find Param)
2041 // -> NamespaceScope ns
2042 //
2043 // See also CppLookupName().
2044 if (S->isTemplateParamScope())
2045 EnterTemplatedContext(S, DC: SemanticContext);
2046
2047 NamedDecl *PrevDecl = nullptr;
2048 if (Previous.begin() != Previous.end())
2049 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2050
2051 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2052 // Maybe we will complain about the shadowed template parameter.
2053 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl);
2054 // Just pretend that we didn't see the previous declaration.
2055 PrevDecl = nullptr;
2056 }
2057
2058 // If there is a previous declaration with the same name, check
2059 // whether this is a valid redeclaration.
2060 ClassTemplateDecl *PrevClassTemplate =
2061 dyn_cast_or_null<ClassTemplateDecl>(Val: PrevDecl);
2062
2063 // We may have found the injected-class-name of a class template,
2064 // class template partial specialization, or class template specialization.
2065 // In these cases, grab the template that is being defined or specialized.
2066 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(Val: PrevDecl) &&
2067 cast<CXXRecordDecl>(Val: PrevDecl)->isInjectedClassName()) {
2068 PrevDecl = cast<CXXRecordDecl>(Val: PrevDecl->getDeclContext());
2069 PrevClassTemplate
2070 = cast<CXXRecordDecl>(Val: PrevDecl)->getDescribedClassTemplate();
2071 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(Val: PrevDecl)) {
2072 PrevClassTemplate
2073 = cast<ClassTemplateSpecializationDecl>(Val: PrevDecl)
2074 ->getSpecializedTemplate();
2075 }
2076 }
2077
2078 if (TUK == TagUseKind::Friend) {
2079 // C++ [namespace.memdef]p3:
2080 // [...] When looking for a prior declaration of a class or a function
2081 // declared as a friend, and when the name of the friend class or
2082 // function is neither a qualified name nor a template-id, scopes outside
2083 // the innermost enclosing namespace scope are not considered.
2084 if (!SS.isSet()) {
2085 DeclContext *OutermostContext = CurContext;
2086 while (!OutermostContext->isFileContext())
2087 OutermostContext = OutermostContext->getLookupParent();
2088
2089 if (PrevDecl &&
2090 (OutermostContext->Equals(DC: PrevDecl->getDeclContext()) ||
2091 OutermostContext->Encloses(DC: PrevDecl->getDeclContext()))) {
2092 SemanticContext = PrevDecl->getDeclContext();
2093 } else {
2094 // Declarations in outer scopes don't matter. However, the outermost
2095 // context we computed is the semantic context for our new
2096 // declaration.
2097 PrevDecl = PrevClassTemplate = nullptr;
2098 SemanticContext = OutermostContext;
2099
2100 // Check that the chosen semantic context doesn't already contain a
2101 // declaration of this name as a non-tag type.
2102 Previous.clear(Kind: LookupOrdinaryName);
2103 DeclContext *LookupContext = SemanticContext;
2104 while (LookupContext->isTransparentContext())
2105 LookupContext = LookupContext->getLookupParent();
2106 LookupQualifiedName(R&: Previous, LookupCtx: LookupContext);
2107
2108 if (Previous.isAmbiguous())
2109 return true;
2110
2111 if (Previous.begin() != Previous.end())
2112 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2113 }
2114 }
2115 } else if (PrevDecl &&
2116 !isTagRedeclarationInScope(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, NewDefinitionLoc: NameLoc, 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, bool TraverseQualifier) 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 TraverseQualifier);
2787 }
2788
2789 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2790 if (NonTypeTemplateParmDecl *PD =
2791 dyn_cast<NonTypeTemplateParmDecl>(Val: E->getDecl()))
2792 if (Matches(ParmDepth: PD->getDepth(), Loc: E->getExprLoc()))
2793 return false;
2794 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(S: E);
2795 }
2796
2797 bool VisitDependentTemplateIdExpr(DependentTemplateIdExpr *E) override {
2798 if (Matches(ParmDepth: E->getParameter()->getDepth(), Loc: E->getExprLoc()))
2799 return false;
2800 return DynamicRecursiveASTVisitor::VisitDependentTemplateIdExpr(S: E);
2801 }
2802
2803 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2804 return TraverseType(T: T->getReplacementType());
2805 }
2806
2807 bool VisitSubstTemplateTypeParmPackType(
2808 SubstTemplateTypeParmPackType *T) override {
2809 return TraverseTemplateArgument(Arg: T->getArgumentPack());
2810 }
2811
2812 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2813 bool TraverseQualifier) override {
2814 // An InjectedClassNameType will never have a dependent template name,
2815 // so no need to traverse it.
2816 return TraverseTemplateArguments(
2817 Args: T->getTemplateArgs(Ctx: T->getDecl()->getASTContext()));
2818 }
2819};
2820} // end anonymous namespace
2821
2822/// Determines whether a given type depends on the given parameter
2823/// list.
2824static bool
2825DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2826 if (!Params->size())
2827 return false;
2828
2829 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2830 Checker.TraverseType(T);
2831 return Checker.Match;
2832}
2833
2834// Find the source range corresponding to the named type in the given
2835// nested-name-specifier, if any.
2836static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2837 QualType T,
2838 const CXXScopeSpec &SS) {
2839 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2840 for (;;) {
2841 NestedNameSpecifier NNS = NNSLoc.getNestedNameSpecifier();
2842 if (NNS.getKind() != NestedNameSpecifier::Kind::Type)
2843 break;
2844 if (Context.hasSameUnqualifiedType(T1: T, T2: QualType(NNS.getAsType(), 0)))
2845 return NNSLoc.castAsTypeLoc().getSourceRange();
2846 // FIXME: This will always be empty.
2847 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2848 }
2849
2850 return SourceRange();
2851}
2852
2853TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2854 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2855 TemplateIdAnnotation *TemplateId,
2856 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2857 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2858 IsMemberSpecialization = false;
2859 Invalid = false;
2860
2861 // The sequence of nested types to which we will match up the template
2862 // parameter lists. We first build this list by starting with the type named
2863 // by the nested-name-specifier and walking out until we run out of types.
2864 SmallVector<QualType, 4> NestedTypes;
2865 QualType T;
2866 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2867 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2868 if (CXXRecordDecl *Record =
2869 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: true)))
2870 T = Context.getCanonicalTagType(TD: Record);
2871 else
2872 T = QualType(Qualifier.getAsType(), 0);
2873 }
2874
2875 // If we found an explicit specialization that prevents us from needing
2876 // 'template<>' headers, this will be set to the location of that
2877 // explicit specialization.
2878 SourceLocation ExplicitSpecLoc;
2879
2880 while (!T.isNull()) {
2881 NestedTypes.push_back(Elt: T);
2882
2883 // Retrieve the parent of a record type.
2884 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2885 // If this type is an explicit specialization, we're done.
2886 if (ClassTemplateSpecializationDecl *Spec
2887 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
2888 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Spec) &&
2889 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2890 ExplicitSpecLoc = Spec->getLocation();
2891 break;
2892 }
2893 } else if (Record->getTemplateSpecializationKind()
2894 == TSK_ExplicitSpecialization) {
2895 ExplicitSpecLoc = Record->getLocation();
2896 break;
2897 }
2898
2899 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Record->getParent()))
2900 T = Context.getTypeDeclType(Decl: Parent);
2901 else
2902 T = QualType();
2903 continue;
2904 }
2905
2906 if (const TemplateSpecializationType *TST
2907 = T->getAs<TemplateSpecializationType>()) {
2908 TemplateName Name = TST->getTemplateName();
2909 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2910 // Look one step prior in a dependent template specialization type.
2911 if (NestedNameSpecifier NNS = DTS->getQualifier();
2912 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2913 T = QualType(NNS.getAsType(), 0);
2914 else
2915 T = QualType();
2916 continue;
2917 }
2918 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2919 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Template->getDeclContext()))
2920 T = Context.getTypeDeclType(Decl: Parent);
2921 else
2922 T = QualType();
2923 continue;
2924 }
2925 }
2926
2927 // Look one step prior in a dependent name type.
2928 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2929 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2930 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2931 T = QualType(NNS.getAsType(), 0);
2932 else
2933 T = QualType();
2934 continue;
2935 }
2936
2937 // Retrieve the parent of an enumeration type.
2938 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2939 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2940 // check here.
2941 EnumDecl *Enum = EnumT->getDecl();
2942
2943 // Get to the parent type.
2944 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Enum->getParent()))
2945 T = Context.getCanonicalTypeDeclType(TD: Parent);
2946 else
2947 T = QualType();
2948 continue;
2949 }
2950
2951 T = QualType();
2952 }
2953 // Reverse the nested types list, since we want to traverse from the outermost
2954 // to the innermost while checking template-parameter-lists.
2955 std::reverse(first: NestedTypes.begin(), last: NestedTypes.end());
2956
2957 // C++0x [temp.expl.spec]p17:
2958 // A member or a member template may be nested within many
2959 // enclosing class templates. In an explicit specialization for
2960 // such a member, the member declaration shall be preceded by a
2961 // template<> for each enclosing class template that is
2962 // explicitly specialized.
2963 bool SawNonEmptyTemplateParameterList = false;
2964
2965 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2966 if (SawNonEmptyTemplateParameterList) {
2967 if (!SuppressDiagnostic)
2968 Diag(Loc: DeclLoc, DiagID: diag::err_specialize_member_of_template)
2969 << !Recovery << Range;
2970 Invalid = true;
2971 IsMemberSpecialization = false;
2972 return true;
2973 }
2974
2975 return false;
2976 };
2977
2978 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2979 // Check that we can have an explicit specialization here.
2980 if (CheckExplicitSpecialization(Range, true))
2981 return true;
2982
2983 // We don't have a template header, but we should.
2984 SourceLocation ExpectedTemplateLoc;
2985 if (!ParamLists.empty())
2986 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2987 else
2988 ExpectedTemplateLoc = DeclStartLoc;
2989
2990 if (!SuppressDiagnostic)
2991 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_header)
2992 << Range
2993 << FixItHint::CreateInsertion(InsertionLoc: ExpectedTemplateLoc, Code: "template<> ");
2994 return false;
2995 };
2996
2997 unsigned ParamIdx = 0;
2998 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2999 ++TypeIdx) {
3000 T = NestedTypes[TypeIdx];
3001
3002 // Whether we expect a 'template<>' header.
3003 bool NeedEmptyTemplateHeader = false;
3004
3005 // Whether we expect a template header with parameters.
3006 bool NeedNonemptyTemplateHeader = false;
3007
3008 // For a dependent type, the set of template parameters that we
3009 // expect to see.
3010 TemplateParameterList *ExpectedTemplateParams = nullptr;
3011
3012 // C++0x [temp.expl.spec]p15:
3013 // A member or a member template may be nested within many enclosing
3014 // class templates. In an explicit specialization for such a member, the
3015 // member declaration shall be preceded by a template<> for each
3016 // enclosing class template that is explicitly specialized.
3017 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3018 if (ClassTemplatePartialSpecializationDecl *Partial
3019 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Record)) {
3020 ExpectedTemplateParams = Partial->getTemplateParameters();
3021 NeedNonemptyTemplateHeader = true;
3022 } else if (Record->isDependentType()) {
3023 if (Record->getDescribedClassTemplate()) {
3024 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3025 ->getTemplateParameters();
3026 NeedNonemptyTemplateHeader = true;
3027 }
3028 } else if (ClassTemplateSpecializationDecl *Spec
3029 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
3030 // C++0x [temp.expl.spec]p4:
3031 // Members of an explicitly specialized class template are defined
3032 // in the same manner as members of normal classes, and not using
3033 // the template<> syntax.
3034 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3035 NeedEmptyTemplateHeader = true;
3036 else
3037 continue;
3038 } else if (Record->getTemplateSpecializationKind()) {
3039 if (Record->getTemplateSpecializationKind()
3040 != TSK_ExplicitSpecialization &&
3041 TypeIdx == NumTypes - 1)
3042 IsMemberSpecialization = true;
3043
3044 continue;
3045 }
3046 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3047 TemplateName Name = TST->getTemplateName();
3048 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3049 ExpectedTemplateParams = Template->getTemplateParameters();
3050 NeedNonemptyTemplateHeader = true;
3051 } else if (Name.getAsDependentTemplateName()) {
3052 NeedNonemptyTemplateHeader = true;
3053 } else if (Name.getAsDeducedTemplateName()) {
3054 // FIXME: We actually could/should check the template arguments here
3055 // against the corresponding template parameter list.
3056 NeedNonemptyTemplateHeader = false;
3057 }
3058 }
3059
3060 // C++ [temp.expl.spec]p16:
3061 // In an explicit specialization declaration for a member of a class
3062 // template or a member template that appears in namespace scope, the
3063 // member template and some of its enclosing class templates may remain
3064 // unspecialized, except that the declaration shall not explicitly
3065 // specialize a class member template if its enclosing class templates
3066 // are not explicitly specialized as well.
3067 if (ParamIdx < ParamLists.size()) {
3068 if (ParamLists[ParamIdx]->size() == 0) {
3069 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3070 false))
3071 return nullptr;
3072 } else
3073 SawNonEmptyTemplateParameterList = true;
3074 }
3075
3076 if (NeedEmptyTemplateHeader) {
3077 // If we're on the last of the types, and we need a 'template<>' header
3078 // here, then it's a member specialization.
3079 if (TypeIdx == NumTypes - 1)
3080 IsMemberSpecialization = true;
3081
3082 if (ParamIdx < ParamLists.size()) {
3083 if (ParamLists[ParamIdx]->size() > 0) {
3084 // The header has template parameters when it shouldn't. Complain.
3085 if (!SuppressDiagnostic)
3086 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3087 DiagID: diag::err_template_param_list_matches_nontemplate)
3088 << T
3089 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3090 ParamLists[ParamIdx]->getRAngleLoc())
3091 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3092 Invalid = true;
3093 return nullptr;
3094 }
3095
3096 // Consume this template header.
3097 ++ParamIdx;
3098 continue;
3099 }
3100
3101 if (!IsFriend)
3102 if (DiagnoseMissingExplicitSpecialization(
3103 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3104 return nullptr;
3105
3106 continue;
3107 }
3108
3109 if (NeedNonemptyTemplateHeader) {
3110 // In friend declarations we can have template-ids which don't
3111 // depend on the corresponding template parameter lists. But
3112 // assume that empty parameter lists are supposed to match this
3113 // template-id.
3114 if (IsFriend && T->isDependentType()) {
3115 if (ParamIdx < ParamLists.size() &&
3116 DependsOnTemplateParameters(T, Params: ParamLists[ParamIdx]))
3117 ExpectedTemplateParams = nullptr;
3118 else
3119 continue;
3120 }
3121
3122 if (ParamIdx < ParamLists.size()) {
3123 // Check the template parameter list, if we can.
3124 if (ExpectedTemplateParams &&
3125 !TemplateParameterListsAreEqual(New: ParamLists[ParamIdx],
3126 Old: ExpectedTemplateParams,
3127 Complain: !SuppressDiagnostic, Kind: TPL_TemplateMatch))
3128 Invalid = true;
3129
3130 if (!Invalid &&
3131 CheckTemplateParameterList(NewParams: ParamLists[ParamIdx], OldParams: nullptr,
3132 TPC: TPC_ClassTemplateMember))
3133 Invalid = true;
3134
3135 ++ParamIdx;
3136 continue;
3137 }
3138
3139 if (!SuppressDiagnostic)
3140 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_template_parameters)
3141 << T
3142 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3143 Invalid = true;
3144 continue;
3145 }
3146 }
3147
3148 // If there were at least as many template-ids as there were template
3149 // parameter lists, then there are no template parameter lists remaining for
3150 // the declaration itself.
3151 if (ParamIdx >= ParamLists.size()) {
3152 if (TemplateId && !IsFriend) {
3153 // We don't have a template header for the declaration itself, but we
3154 // should.
3155 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3156 TemplateId->RAngleLoc));
3157
3158 // Fabricate an empty template parameter list for the invented header.
3159 return TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(),
3160 LAngleLoc: SourceLocation(), Params: {},
3161 RAngleLoc: SourceLocation(), RequiresClause: nullptr);
3162 }
3163
3164 return nullptr;
3165 }
3166
3167 // If there were too many template parameter lists, complain about that now.
3168 if (ParamIdx < ParamLists.size() - 1) {
3169 bool HasAnyExplicitSpecHeader = false;
3170 bool AllExplicitSpecHeaders = true;
3171 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3172 if (ParamLists[I]->size() == 0)
3173 HasAnyExplicitSpecHeader = true;
3174 else
3175 AllExplicitSpecHeaders = false;
3176 }
3177
3178 if (!SuppressDiagnostic)
3179 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3180 DiagID: AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3181 : diag::err_template_spec_extra_headers)
3182 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3183 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3184
3185 // If there was a specialization somewhere, such that 'template<>' is
3186 // not required, and there were any 'template<>' headers, note where the
3187 // specialization occurred.
3188 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3189 !SuppressDiagnostic)
3190 Diag(Loc: ExplicitSpecLoc,
3191 DiagID: diag::note_explicit_template_spec_does_not_need_header)
3192 << NestedTypes.back();
3193
3194 // We have a template parameter list with no corresponding scope, which
3195 // means that the resulting template declaration can't be instantiated
3196 // properly (we'll end up with dependent nodes when we shouldn't).
3197 if (!AllExplicitSpecHeaders)
3198 Invalid = true;
3199 }
3200
3201 // C++ [temp.expl.spec]p16:
3202 // In an explicit specialization declaration for a member of a class
3203 // template or a member template that ap- pears in namespace scope, the
3204 // member template and some of its enclosing class templates may remain
3205 // unspecialized, except that the declaration shall not explicitly
3206 // specialize a class member template if its en- closing class templates
3207 // are not explicitly specialized as well.
3208 if (ParamLists.back()->size() == 0 &&
3209 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3210 false))
3211 return nullptr;
3212
3213 // Return the last template parameter list, which corresponds to the
3214 // entity being declared.
3215 return ParamLists.back();
3216}
3217
3218void Sema::NoteAllFoundTemplates(TemplateName Name) {
3219 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3220 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_declared_here)
3221 << (isa<FunctionTemplateDecl>(Val: Template)
3222 ? 0
3223 : isa<ClassTemplateDecl>(Val: Template)
3224 ? 1
3225 : isa<VarTemplateDecl>(Val: Template)
3226 ? 2
3227 : isa<TypeAliasTemplateDecl>(Val: Template) ? 3 : 4)
3228 << Template->getDeclName();
3229 return;
3230 }
3231
3232 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3233 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3234 IEnd = OST->end();
3235 I != IEnd; ++I)
3236 Diag(Loc: (*I)->getLocation(), DiagID: diag::note_template_declared_here)
3237 << 0 << (*I)->getDeclName();
3238
3239 return;
3240 }
3241}
3242
3243static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword,
3244 TemplateName BaseTemplate,
3245 SourceLocation TemplateLoc,
3246 ArrayRef<TemplateArgument> Ts) {
3247 auto lookUpCommonType = [&](TemplateArgument T1,
3248 TemplateArgument T2) -> QualType {
3249 // Don't bother looking for other specializations if both types are
3250 // builtins - users aren't allowed to specialize for them
3251 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3252 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3253 Ts: {T1, T2});
3254
3255 TemplateArgumentListInfo Args;
3256 Args.addArgument(Loc: TemplateArgumentLoc(
3257 T1, S.Context.getTrivialTypeSourceInfo(T: T1.getAsType())));
3258 Args.addArgument(Loc: TemplateArgumentLoc(
3259 T2, S.Context.getTrivialTypeSourceInfo(T: T2.getAsType())));
3260
3261 EnterExpressionEvaluationContext UnevaluatedContext(
3262 S, Sema::ExpressionEvaluationContext::Unevaluated);
3263 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3264 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3265
3266 QualType BaseTemplateInst = S.CheckTemplateIdType(
3267 Keyword, Template: BaseTemplate, TemplateLoc, TemplateArgs&: Args,
3268 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3269
3270 if (SFINAE.hasErrorOccurred())
3271 return QualType();
3272
3273 return BaseTemplateInst;
3274 };
3275
3276 // Note A: For the common_type trait applied to a template parameter pack T of
3277 // types, the member type shall be either defined or not present as follows:
3278 switch (Ts.size()) {
3279
3280 // If sizeof...(T) is zero, there shall be no member type.
3281 case 0:
3282 return QualType();
3283
3284 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3285 // pack T. The member typedef-name type shall denote the same type, if any, as
3286 // common_type_t<T0, T0>; otherwise there shall be no member type.
3287 case 1:
3288 return lookUpCommonType(Ts[0], Ts[0]);
3289
3290 // If sizeof...(T) is two, let the first and second types constituting T be
3291 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3292 // as decay_t<T1> and decay_t<T2>, respectively.
3293 case 2: {
3294 QualType T1 = Ts[0].getAsType();
3295 QualType T2 = Ts[1].getAsType();
3296 QualType D1 = S.BuiltinDecay(BaseType: T1, Loc: {});
3297 QualType D2 = S.BuiltinDecay(BaseType: T2, Loc: {});
3298
3299 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3300 // the same type, if any, as common_type_t<D1, D2>.
3301 if (!S.Context.hasSameType(T1, T2: D1) || !S.Context.hasSameType(T1: T2, T2: D2))
3302 return lookUpCommonType(D1, D2);
3303
3304 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3305 // denotes a valid type, let C denote that type.
3306 {
3307 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3308 EnterExpressionEvaluationContext UnevaluatedContext(
3309 S, Sema::ExpressionEvaluationContext::Unevaluated);
3310 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3311 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3312
3313 // false
3314 OpaqueValueExpr CondExpr(SourceLocation(), S.Context.BoolTy,
3315 VK_PRValue);
3316 ExprResult Cond = &CondExpr;
3317
3318 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3319 if (ConstRefQual) {
3320 D1.addConst();
3321 D2.addConst();
3322 }
3323
3324 // declval<D1>()
3325 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3326 ExprResult LHS = &LHSExpr;
3327
3328 // declval<D2>()
3329 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3330 ExprResult RHS = &RHSExpr;
3331
3332 ExprValueKind VK = VK_PRValue;
3333 ExprObjectKind OK = OK_Ordinary;
3334
3335 // decltype(false ? declval<D1>() : declval<D2>())
3336 QualType Result =
3337 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc: TemplateLoc);
3338
3339 if (Result.isNull() || SFINAE.hasErrorOccurred())
3340 return QualType();
3341
3342 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3343 return S.BuiltinDecay(BaseType: Result, Loc: TemplateLoc);
3344 };
3345
3346 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3347 return Res;
3348
3349 // Let:
3350 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3351 // COND-RES(X, Y) be
3352 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3353
3354 // C++20 only
3355 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3356 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3357 if (!S.Context.getLangOpts().CPlusPlus20)
3358 return QualType();
3359 return CheckConditionalOperands(true);
3360 }
3361 }
3362
3363 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3364 // denote the first, second, and (pack of) remaining types constituting T. Let
3365 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3366 // a type C, the member typedef-name type shall denote the same type, if any,
3367 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3368 default: {
3369 QualType Result = Ts.front().getAsType();
3370 for (auto T : llvm::drop_begin(RangeOrContainer&: Ts)) {
3371 Result = lookUpCommonType(Result, T.getAsType());
3372 if (Result.isNull())
3373 return QualType();
3374 }
3375 return Result;
3376 }
3377 }
3378}
3379
3380static bool isInVkNamespace(const RecordType *RT) {
3381 DeclContext *DC = RT->getDecl()->getDeclContext();
3382 if (!DC)
3383 return false;
3384
3385 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: DC);
3386 if (!ND)
3387 return false;
3388
3389 return ND->getQualifiedNameAsString() == "hlsl::vk";
3390}
3391
3392static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3393 QualType OperandArg,
3394 SourceLocation Loc) {
3395 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3396 bool Literal = false;
3397 SourceLocation LiteralLoc;
3398 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3399 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3400 assert(SpecDecl);
3401
3402 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3403 QualType ConstantType = LiteralArgs[0].getAsType();
3404 RT = ConstantType->getAsCanonical<RecordType>();
3405 Literal = true;
3406 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3407 }
3408
3409 if (RT && isInVkNamespace(RT) &&
3410 RT->getDecl()->getName() == "integral_constant") {
3411 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3412 assert(SpecDecl);
3413
3414 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3415
3416 QualType ConstantType = ConstantArgs[0].getAsType();
3417 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3418
3419 if (Literal)
3420 return SpirvOperand::createLiteral(Val: Value);
3421 return SpirvOperand::createConstant(ResultType: ConstantType, Val: Value);
3422 } else if (Literal) {
3423 SemaRef.Diag(Loc: LiteralLoc, DiagID: diag::err_hlsl_vk_literal_must_contain_constant);
3424 return SpirvOperand();
3425 }
3426 }
3427 if (SemaRef.RequireCompleteType(Loc, T: OperandArg,
3428 DiagID: diag::err_call_incomplete_argument))
3429 return SpirvOperand();
3430 return SpirvOperand::createType(T: OperandArg);
3431}
3432
3433static QualType sortBuiltinTemplatePack(ASTContext &Context,
3434 ArrayRef<TemplateArgument> InputArgs) {
3435 // FIXME: cache mangling globally?
3436 std::unique_ptr<MangleContext> MC(Context.createMangleContext());
3437 SmallVector<std::pair<std::string, TemplateArgument>> SortedArgs(
3438 InputArgs.size());
3439 llvm::transform(Range&: InputArgs, d_first: SortedArgs.begin(),
3440 F: [&](const TemplateArgument &Arg) {
3441 assert(Arg.getKind() == TemplateArgument::Type);
3442 std::string MangledName;
3443 llvm::raw_string_ostream OS(MangledName);
3444 MC->mangleCanonicalTypeName(T: Arg.getAsType(), OS);
3445 return std::pair<std::string, TemplateArgument>(
3446 std::move(MangledName), Arg);
3447 });
3448 llvm::stable_sort(Range&: SortedArgs, C: llvm::less_first());
3449
3450 auto OutArgs = llvm::to_vector(Range: llvm::make_second_range(c&: SortedArgs));
3451 return Context.getSubstBuiltinTemplatePack(
3452 ArgPack: TemplateArgument::CreatePackCopy(Context, Args: OutArgs));
3453}
3454
3455static QualType checkBuiltinTemplateIdType(
3456 Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD,
3457 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3458 TemplateArgumentListInfo &TemplateArgs) {
3459 ASTContext &Context = SemaRef.getASTContext();
3460
3461 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3462 "Builtin template arguments do not match its parameters");
3463
3464 switch (BTD->getBuiltinTemplateKind()) {
3465 case BTK__make_integer_seq: {
3466 // Specializations of __make_integer_seq<S, T, N> are treated like
3467 // S<T, 0, ..., N-1>.
3468
3469 QualType OrigType = Converted[1].getAsType();
3470 // C++14 [inteseq.intseq]p1:
3471 // T shall be an integer type.
3472 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Ctx: Context)) {
3473 SemaRef.Diag(Loc: TemplateArgs[1].getLocation(),
3474 DiagID: diag::err_integer_sequence_integral_element_type);
3475 return QualType();
3476 }
3477
3478 TemplateArgument NumArgsArg = Converted[2];
3479 if (NumArgsArg.isDependent())
3480 return QualType();
3481
3482 TemplateArgumentListInfo SyntheticTemplateArgs;
3483 // The type argument, wrapped in substitution sugar, gets reused as the
3484 // first template argument in the synthetic template argument list.
3485 SyntheticTemplateArgs.addArgument(
3486 Loc: TemplateArgumentLoc(TemplateArgument(OrigType),
3487 SemaRef.Context.getTrivialTypeSourceInfo(
3488 T: OrigType, Loc: TemplateArgs[1].getLocation())));
3489
3490 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3491 // Expand N into 0 ... N-1.
3492 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3493 I < NumArgs; ++I) {
3494 TemplateArgument TA(Context, I, OrigType);
3495 SyntheticTemplateArgs.addArgument(Loc: SemaRef.getTrivialTemplateArgumentLoc(
3496 Arg: TA, NTTPType: OrigType, Loc: TemplateArgs[2].getLocation()));
3497 }
3498 } else {
3499 // C++14 [inteseq.make]p1:
3500 // If N is negative the program is ill-formed.
3501 SemaRef.Diag(Loc: TemplateArgs[2].getLocation(),
3502 DiagID: diag::err_integer_sequence_negative_length);
3503 return QualType();
3504 }
3505
3506 // The first template argument will be reused as the template decl that
3507 // our synthetic template arguments will be applied to.
3508 return SemaRef.CheckTemplateIdType(Keyword, Template: Converted[0].getAsTemplate(),
3509 TemplateLoc, TemplateArgs&: SyntheticTemplateArgs,
3510 /*Scope=*/nullptr,
3511 /*ForNestedNameSpecifier=*/false);
3512 }
3513
3514 case BTK__type_pack_element: {
3515 // Specializations of
3516 // __type_pack_element<Index, T_1, ..., T_N>
3517 // are treated like T_Index.
3518 assert(Converted.size() == 2 &&
3519 "__type_pack_element should be given an index and a parameter pack");
3520
3521 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3522 if (IndexArg.isDependent() || Ts.isDependent())
3523 return QualType();
3524
3525 llvm::APSInt Index = IndexArg.getAsIntegral();
3526 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3527 "type std::size_t, and hence be non-negative");
3528 // If the Index is out of bounds, the program is ill-formed.
3529 if (Index >= Ts.pack_size()) {
3530 SemaRef.Diag(Loc: TemplateArgs[0].getLocation(),
3531 DiagID: diag::err_type_pack_element_out_of_bounds);
3532 return QualType();
3533 }
3534
3535 // We simply return the type at index `Index`.
3536 int64_t N = Index.getExtValue();
3537 return Ts.getPackAsArray()[N].getAsType();
3538 }
3539
3540 case BTK__builtin_common_type: {
3541 assert(Converted.size() == 4);
3542 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3543 return QualType();
3544
3545 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3546 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3547 if (auto CT = builtinCommonTypeImpl(S&: SemaRef, Keyword, BaseTemplate,
3548 TemplateLoc, Ts);
3549 !CT.isNull()) {
3550 TemplateArgumentListInfo TAs;
3551 TAs.addArgument(Loc: TemplateArgumentLoc(
3552 TemplateArgument(CT), SemaRef.Context.getTrivialTypeSourceInfo(
3553 T: CT, Loc: TemplateArgs[1].getLocation())));
3554 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3555 return SemaRef.CheckTemplateIdType(Keyword, Template: HasTypeMember, TemplateLoc,
3556 TemplateArgs&: TAs, /*Scope=*/nullptr,
3557 /*ForNestedNameSpecifier=*/false);
3558 }
3559 QualType HasNoTypeMember = Converted[2].getAsType();
3560 return HasNoTypeMember;
3561 }
3562
3563 case BTK__hlsl_spirv_type: {
3564 assert(Converted.size() == 4);
3565
3566 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3567 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_hlsl_spirv_only) << BTD;
3568 }
3569
3570 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3571 return QualType();
3572
3573 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3574 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3575 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3576
3577 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3578
3579 llvm::SmallVector<SpirvOperand> Operands;
3580
3581 for (auto &OperandTA : OperandArgs) {
3582 QualType OperandArg = OperandTA.getAsType();
3583 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3584 Loc: TemplateArgs[3].getLocation());
3585 if (!Operand.isValid())
3586 return QualType();
3587 Operands.push_back(Elt: Operand);
3588 }
3589
3590 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3591 }
3592 case BTK__builtin_dedup_pack: {
3593 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3594 "a parameter pack");
3595 TemplateArgument Ts = Converted[0];
3596 // Delay the computation until we can compute the final result. We choose
3597 // not to remove the duplicates upfront before substitution to keep the code
3598 // simple.
3599 if (Ts.isDependent())
3600 return QualType();
3601 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3602 llvm::SmallVector<TemplateArgument> OutArgs;
3603 llvm::SmallDenseSet<QualType> Seen;
3604 // Synthesize a new template argument list, removing duplicates.
3605 for (auto T : Ts.getPackAsArray()) {
3606 assert(T.getKind() == clang::TemplateArgument::Type);
3607 if (!Seen.insert(V: T.getAsType().getCanonicalType()).second)
3608 continue;
3609 OutArgs.push_back(Elt: T);
3610 }
3611 return Context.getSubstBuiltinTemplatePack(
3612 ArgPack: TemplateArgument::CreatePackCopy(Context, Args: OutArgs));
3613 }
3614 case BTK__builtin_sort_pack: {
3615 assert(Converted.size() == 1 &&
3616 "__builtin_sort_pack should be given a parameter pack");
3617 TemplateArgument Ts = Converted[0];
3618 if (Ts.isDependent())
3619 return QualType();
3620 assert(Ts.getKind() == TemplateArgument::Pack);
3621 return sortBuiltinTemplatePack(Context, InputArgs: Ts.getPackAsArray());
3622 }
3623 }
3624 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3625}
3626
3627/// Determine whether this alias template is "enable_if_t".
3628/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3629static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3630 return AliasTemplate->getName() == "enable_if_t" ||
3631 AliasTemplate->getName() == "__enable_if_t";
3632}
3633
3634/// Collect all of the separable terms in the given condition, which
3635/// might be a conjunction.
3636///
3637/// FIXME: The right answer is to convert the logical expression into
3638/// disjunctive normal form, so we can find the first failed term
3639/// within each possible clause.
3640static void collectConjunctionTerms(Expr *Clause,
3641 SmallVectorImpl<Expr *> &Terms) {
3642 if (auto BinOp = dyn_cast<BinaryOperator>(Val: Clause->IgnoreParenImpCasts())) {
3643 if (BinOp->getOpcode() == BO_LAnd) {
3644 collectConjunctionTerms(Clause: BinOp->getLHS(), Terms);
3645 collectConjunctionTerms(Clause: BinOp->getRHS(), Terms);
3646 return;
3647 }
3648 }
3649
3650 Terms.push_back(Elt: Clause);
3651}
3652
3653// The ranges-v3 library uses an odd pattern of a top-level "||" with
3654// a left-hand side that is value-dependent but never true. Identify
3655// the idiom and ignore that term.
3656static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3657 // Top-level '||'.
3658 auto *BinOp = dyn_cast<BinaryOperator>(Val: Cond->IgnoreParenImpCasts());
3659 if (!BinOp) return Cond;
3660
3661 if (BinOp->getOpcode() != BO_LOr) return Cond;
3662
3663 // With an inner '==' that has a literal on the right-hand side.
3664 Expr *LHS = BinOp->getLHS();
3665 auto *InnerBinOp = dyn_cast<BinaryOperator>(Val: LHS->IgnoreParenImpCasts());
3666 if (!InnerBinOp) return Cond;
3667
3668 if (InnerBinOp->getOpcode() != BO_EQ ||
3669 !isa<IntegerLiteral>(Val: InnerBinOp->getRHS()))
3670 return Cond;
3671
3672 // If the inner binary operation came from a macro expansion named
3673 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3674 // of the '||', which is the real, user-provided condition.
3675 SourceLocation Loc = InnerBinOp->getExprLoc();
3676 if (!Loc.isMacroID()) return Cond;
3677
3678 StringRef MacroName = PP.getImmediateMacroName(Loc);
3679 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3680 return BinOp->getRHS();
3681
3682 return Cond;
3683}
3684
3685namespace {
3686
3687// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3688// within failing boolean expression, such as substituting template parameters
3689// for actual types.
3690class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3691public:
3692 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3693 : Policy(P) {}
3694
3695 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3696 const auto *DR = dyn_cast<DeclRefExpr>(Val: E);
3697 if (DR && DR->getQualifier()) {
3698 // If this is a qualified name, expand the template arguments in nested
3699 // qualifiers.
3700 DR->getQualifier().print(OS, Policy, ResolveTemplateArguments: true);
3701 // Then print the decl itself.
3702 const ValueDecl *VD = DR->getDecl();
3703 OS << *VD;
3704 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) {
3705 // This is a template variable, print the expanded template arguments.
3706 printTemplateArgumentList(
3707 OS, Args: IV->getTemplateArgs().asArray(), Policy,
3708 TPL: IV->getSpecializedTemplate()->getTemplateParameters());
3709 }
3710 return true;
3711 }
3712 return false;
3713 }
3714
3715private:
3716 const PrintingPolicy Policy;
3717};
3718
3719} // end anonymous namespace
3720
3721std::pair<Expr *, std::string>
3722Sema::findFailedBooleanCondition(Expr *Cond) {
3723 Cond = lookThroughRangesV3Condition(PP, Cond);
3724
3725 // Separate out all of the terms in a conjunction.
3726 SmallVector<Expr *, 4> Terms;
3727 collectConjunctionTerms(Clause: Cond, Terms);
3728
3729 // Determine which term failed.
3730 Expr *FailedCond = nullptr;
3731 for (Expr *Term : Terms) {
3732 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3733
3734 // Literals are uninteresting.
3735 if (isa<CXXBoolLiteralExpr>(Val: TermAsWritten) ||
3736 isa<IntegerLiteral>(Val: TermAsWritten))
3737 continue;
3738
3739 // The initialization of the parameter from the argument is
3740 // a constant-evaluated context.
3741 EnterExpressionEvaluationContext ConstantEvaluated(
3742 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3743
3744 bool Succeeded;
3745 if (Term->EvaluateAsBooleanCondition(Result&: Succeeded, Ctx: Context) &&
3746 !Succeeded) {
3747 FailedCond = TermAsWritten;
3748 break;
3749 }
3750 }
3751 if (!FailedCond)
3752 FailedCond = Cond->IgnoreParenImpCasts();
3753
3754 std::string Description;
3755 {
3756 llvm::raw_string_ostream Out(Description);
3757 PrintingPolicy Policy = getPrintingPolicy();
3758 Policy.PrintAsCanonical = true;
3759 FailedBooleanConditionPrinterHelper Helper(Policy);
3760 FailedCond->printPretty(OS&: Out, Helper: &Helper, Policy, Indentation: 0, NewlineSymbol: "\n", Context: nullptr);
3761 }
3762 return { FailedCond, Description };
3763}
3764
3765static TemplateName
3766resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope,
3767 const AssumedTemplateStorage *ATN,
3768 SourceLocation NameLoc) {
3769 // We assumed this undeclared identifier to be an (ADL-only) function
3770 // template name, but it was used in a context where a type was required.
3771 // Try to typo-correct it now.
3772 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3773 struct CandidateCallback : CorrectionCandidateCallback {
3774 bool ValidateCandidate(const TypoCorrection &TC) override {
3775 return TC.getCorrectionDecl() &&
3776 getAsTypeTemplateDecl(D: TC.getCorrectionDecl());
3777 }
3778 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3779 return std::make_unique<CandidateCallback>(args&: *this);
3780 }
3781 } FilterCCC;
3782
3783 TypoCorrection Corrected =
3784 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Scope,
3785 /*SS=*/nullptr, CCC&: FilterCCC, Mode: CorrectTypoKind::ErrorRecovery);
3786 if (Corrected && Corrected.getFoundDecl()) {
3787 S.diagnoseTypo(Correction: Corrected, TypoDiag: S.PDiag(DiagID: diag::err_no_template_suggest)
3788 << ATN->getDeclName());
3789 return S.Context.getQualifiedTemplateName(
3790 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3791 Template: TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()));
3792 }
3793
3794 return TemplateName();
3795}
3796
3797QualType Sema::CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
3798 TemplateName Name,
3799 SourceLocation TemplateLoc,
3800 TemplateArgumentListInfo &TemplateArgs,
3801 Scope *Scope, bool ForNestedNameSpecifier) {
3802 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3803
3804 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3805 if (!Template) {
3806 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3807 Template = S->getParameterPack();
3808 } else if (const auto *PI = UnderlyingName.getAsPackIndexingTemplate()) {
3809 Template = PI->getParameterPack();
3810 if (!Template)
3811 Template = PI->getPattern().getAsTemplateDecl();
3812 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3813 if (DTN->getName().getIdentifier())
3814 // When building a template-id where the template-name is dependent,
3815 // assume the template is a type template. Either our assumption is
3816 // correct, or the code is ill-formed and will be diagnosed when the
3817 // dependent name is substituted.
3818 return Context.getTemplateSpecializationType(Keyword, T: Name,
3819 SpecifiedArgs: TemplateArgs.arguments(),
3820 /*CanonicalArgs=*/{});
3821 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3822 if (TemplateName CorrectedName = ::resolveAssumedTemplateNameAsType(
3823 S&: *this, Scope, ATN, NameLoc: TemplateLoc);
3824 CorrectedName.isNull()) {
3825 Diag(Loc: TemplateLoc, DiagID: diag::err_no_template) << ATN->getDeclName();
3826 return QualType();
3827 } else {
3828 Name = CorrectedName;
3829 Template = Name.getAsTemplateDecl();
3830 }
3831 }
3832 }
3833 if (!Template ||
3834 isa<FunctionTemplateDecl, VarTemplateDecl, ConceptDecl>(Val: Template)) {
3835 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3836 if (ForNestedNameSpecifier)
3837 Diag(Loc: TemplateLoc, DiagID: diag::err_non_type_template_in_nested_name_specifier)
3838 << isa_and_nonnull<VarTemplateDecl>(Val: Template) << Name << R;
3839 else
3840 Diag(Loc: TemplateLoc, DiagID: diag::err_template_id_not_a_type) << Name << R;
3841 NoteAllFoundTemplates(Name);
3842 return QualType();
3843 }
3844
3845 // Check that the template argument list is well-formed for this
3846 // template.
3847 CheckTemplateArgumentInfo CTAI;
3848 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3849 DefaultArgs, /*PartialTemplateArgs=*/false,
3850 CTAI,
3851 /*UpdateArgsWithConversions=*/true))
3852 return QualType();
3853
3854 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3855 // and there are no diagnsotics currently implemented for TemplateDecls,
3856 // so avoid doing it for now.
3857 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Template, /*OdrUse=*/MightBeOdrUse: false);
3858
3859 QualType CanonType;
3860
3861 if (isa<TemplateTemplateParmDecl>(Val: Template)) {
3862 // We might have a substituted template template parameter pack. If so,
3863 // build a template specialization type for it.
3864 } else if (TypeAliasTemplateDecl *AliasTemplate =
3865 dyn_cast<TypeAliasTemplateDecl>(Val: Template)) {
3866
3867 // C++0x [dcl.type.elab]p2:
3868 // If the identifier resolves to a typedef-name or the simple-template-id
3869 // resolves to an alias template specialization, the
3870 // elaborated-type-specifier is ill-formed.
3871 if (Keyword != ElaboratedTypeKeyword::None &&
3872 Keyword != ElaboratedTypeKeyword::Typename) {
3873 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_tag_reference_non_tag)
3874 << AliasTemplate << NonTagKind::TypeAliasTemplate
3875 << KeywordHelpers::getTagTypeKindForKeyword(Keyword);
3876 SemaRef.Diag(Loc: AliasTemplate->getLocation(), DiagID: diag::note_declared_at);
3877 }
3878
3879 // Find the canonical type for this type alias template specialization.
3880 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3881
3882 // Diagnose uses of the pattern of this template.
3883 (void)DiagnoseUseOfDecl(D: Pattern, Locs: TemplateLoc);
3884 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Pattern, /*OdrUse=*/MightBeOdrUse: false);
3885
3886 if (Pattern->isInvalidDecl())
3887 return QualType();
3888
3889 // Only substitute for the innermost template argument list.
3890 MultiLevelTemplateArgumentList TemplateArgLists;
3891 TemplateArgLists.addOuterTemplateArguments(AssociatedDecl: Template, Args: CTAI.SugaredConverted,
3892 /*Final=*/true);
3893 TemplateArgLists.addOuterRetainedLevels(
3894 Num: AliasTemplate->getTemplateParameters()->getDepth());
3895
3896 LocalInstantiationScope Scope(*this);
3897
3898 // FIXME: The TemplateArgs passed here are not used for the context note,
3899 // nor they should, because this note will be pointing to the specialization
3900 // anyway. These arguments are needed for a hack for instantiating lambdas
3901 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3902 // arguments will be used for collating the template arguments needed to
3903 // instantiate the lambda.
3904 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3905 /*Entity=*/AliasTemplate,
3906 /*TemplateArgs=*/CTAI.SugaredConverted);
3907 if (Inst.isInvalid())
3908 return QualType();
3909
3910 std::optional<ContextRAII> SavedContext;
3911 if (!AliasTemplate->getDeclContext()->isFileContext())
3912 SavedContext.emplace(args&: *this, args: AliasTemplate->getDeclContext());
3913
3914 CanonType =
3915 SubstType(T: Pattern->getUnderlyingType(), TemplateArgs: TemplateArgLists,
3916 Loc: AliasTemplate->getLocation(), Entity: AliasTemplate->getDeclName());
3917 if (CanonType.isNull()) {
3918 // If this was enable_if and we failed to find the nested type
3919 // within enable_if in a SFINAE context, dig out the specific
3920 // enable_if condition that failed and present that instead.
3921 if (isEnableIfAliasTemplate(AliasTemplate)) {
3922 if (SFINAETrap *Trap = getSFINAEContext();
3923 TemplateDeductionInfo *DeductionInfo =
3924 Trap ? Trap->getDeductionInfo() : nullptr) {
3925 if (DeductionInfo->hasSFINAEDiagnostic() &&
3926 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3927 diag::err_typename_nested_not_found_enable_if &&
3928 TemplateArgs[0].getArgument().getKind() ==
3929 TemplateArgument::Expression) {
3930 Expr *FailedCond;
3931 std::string FailedDescription;
3932 std::tie(args&: FailedCond, args&: FailedDescription) =
3933 findFailedBooleanCondition(Cond: TemplateArgs[0].getSourceExpression());
3934
3935 // Remove the old SFINAE diagnostic.
3936 PartialDiagnosticAt OldDiag =
3937 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3938 DeductionInfo->takeSFINAEDiagnostic(PD&: OldDiag);
3939
3940 // Add a new SFINAE diagnostic specifying which condition
3941 // failed.
3942 DeductionInfo->addSFINAEDiagnostic(
3943 Loc: OldDiag.first,
3944 PD: PDiag(DiagID: diag::err_typename_nested_not_found_requirement)
3945 << FailedDescription << FailedCond->getSourceRange());
3946 }
3947 }
3948 }
3949
3950 return QualType();
3951 }
3952 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Val: Template)) {
3953 CanonType = checkBuiltinTemplateIdType(
3954 SemaRef&: *this, Keyword, BTD, Converted: CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3955 } else if (Name.isDependent() ||
3956 TemplateSpecializationType::anyDependentTemplateArguments(
3957 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
3958 // This class template specialization is a dependent
3959 // type. Therefore, its canonical type is another class template
3960 // specialization type that contains all of the converted
3961 // arguments in canonical form. This ensures that, e.g., A<T> and
3962 // A<T, T> have identical types when A is declared as:
3963 //
3964 // template<typename T, typename U = T> struct A;
3965 CanonType = Context.getCanonicalTemplateSpecializationType(
3966 Keyword: ElaboratedTypeKeyword::None,
3967 T: Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3968 CanonicalArgs: CTAI.CanonicalConverted);
3969 assert(CanonType->isCanonicalUnqualified());
3970
3971 // This might work out to be a current instantiation, in which
3972 // case the canonical type needs to be the InjectedClassNameType.
3973 //
3974 // TODO: in theory this could be a simple hashtable lookup; most
3975 // changes to CurContext don't change the set of current
3976 // instantiations.
3977 if (isa<ClassTemplateDecl>(Val: Template)) {
3978 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3979 // If we get out to a namespace, we're done.
3980 if (Ctx->isFileContext()) break;
3981
3982 // If this isn't a record, keep looking.
3983 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Ctx);
3984 if (!Record) continue;
3985
3986 // Look for one of the two cases with InjectedClassNameTypes
3987 // and check whether it's the same template.
3988 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Record) &&
3989 !Record->getDescribedClassTemplate())
3990 continue;
3991
3992 // Fetch the injected class name type and check whether its
3993 // injected type is equal to the type we just built.
3994 CanQualType ICNT = Context.getCanonicalTagType(TD: Record);
3995 CanQualType Injected =
3996 Record->getCanonicalTemplateSpecializationType(Ctx: Context);
3997
3998 if (CanonType != Injected)
3999 continue;
4000
4001 (void)DiagnoseUseOfDecl(D: Record, Locs: TemplateLoc);
4002 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Record, /*OdrUse=*/MightBeOdrUse: false);
4003
4004 // If so, the canonical type of this TST is the injected
4005 // class name type of the record we just found.
4006 CanonType = ICNT;
4007 break;
4008 }
4009 }
4010 } else if (ClassTemplateDecl *ClassTemplate =
4011 dyn_cast<ClassTemplateDecl>(Val: Template)) {
4012 // Find the class template specialization declaration that
4013 // corresponds to these arguments.
4014 llvm::FoldingSetInsertToken InsertToken;
4015 ClassTemplateSpecializationDecl *Decl =
4016 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertToken);
4017 if (!Decl) {
4018 // This is the first time we have referenced this class template
4019 // specialization. Create the canonical declaration and add it to
4020 // the set of specializations.
4021 Decl = ClassTemplateSpecializationDecl::Create(
4022 Context, TK: ClassTemplate->getTemplatedDecl()->getTagKind(),
4023 DC: ClassTemplate->getDeclContext(),
4024 StartLoc: ClassTemplate->getTemplatedDecl()->getBeginLoc(),
4025 IdLoc: ClassTemplate->getLocation(), SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted,
4026 StrictPackMatch: CTAI.StrictPackMatch, PrevDecl: nullptr);
4027 ClassTemplate->AddSpecialization(D: Decl, InsertToken);
4028 if (ClassTemplate->isOutOfLine())
4029 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
4030 }
4031
4032 if (Decl->getSpecializationKind() == TSK_Undeclared &&
4033 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4034 NonSFINAEContext _(*this);
4035 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4036 if (!Inst.isInvalid()) {
4037 MultiLevelTemplateArgumentList TemplateArgLists(Template,
4038 CTAI.CanonicalConverted,
4039 /*Final=*/false);
4040 InstantiateAttrsForDecl(TemplateArgs: TemplateArgLists,
4041 Pattern: ClassTemplate->getTemplatedDecl(), Inst: Decl);
4042 }
4043 }
4044
4045 // Diagnose uses of this specialization.
4046 (void)DiagnoseUseOfDecl(D: Decl, Locs: TemplateLoc);
4047 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Decl, /*OdrUse=*/MightBeOdrUse: false);
4048
4049 CanonType = Context.getCanonicalTagType(TD: Decl);
4050 assert(isa<RecordType>(CanonType) &&
4051 "type of non-dependent specialization is not a RecordType");
4052 } else {
4053 llvm_unreachable("Unhandled template kind");
4054 }
4055
4056 // Build the fully-sugared type for this class template
4057 // specialization, which refers back to the class template
4058 // specialization we created or found.
4059 return Context.getTemplateSpecializationType(
4060 Keyword, T: Name, SpecifiedArgs: TemplateArgs.arguments(), CanonicalArgs: CTAI.CanonicalConverted,
4061 Canon: CanonType);
4062}
4063
4064void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
4065 TemplateNameKind &TNK,
4066 SourceLocation NameLoc,
4067 IdentifierInfo *&II) {
4068 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4069
4070 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4071 assert(ATN && "not an assumed template name");
4072 II = ATN->getDeclName().getAsIdentifierInfo();
4073
4074 if (TemplateName Name =
4075 ::resolveAssumedTemplateNameAsType(S&: *this, Scope: S, ATN, NameLoc);
4076 !Name.isNull()) {
4077 // Resolved to a type template name.
4078 ParsedName = TemplateTy::make(P: Name);
4079 TNK = TNK_Type_template;
4080 }
4081}
4082
4083TypeResult Sema::ActOnTemplateIdType(
4084 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4085 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4086 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4087 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4088 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4089 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4090 ImplicitTypenameContext AllowImplicitTypename) {
4091 if (SS.isInvalid())
4092 return true;
4093
4094 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4095 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4096
4097 // C++ [temp.res]p3:
4098 // A qualified-id that refers to a type and in which the
4099 // nested-name-specifier depends on a template-parameter (14.6.2)
4100 // shall be prefixed by the keyword typename to indicate that the
4101 // qualified-id denotes a type, forming an
4102 // elaborated-type-specifier (7.1.5.3).
4103 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4104 // C++2a relaxes some of those restrictions in [temp.res]p5.
4105 QualType DNT = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
4106 NNS: SS.getScopeRep(), Name: TemplateII);
4107 NestedNameSpecifier NNS(DNT.getTypePtr());
4108 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4109 auto DB = DiagCompat(Loc: SS.getBeginLoc(), CompatDiagId: diag_compat::implicit_typename)
4110 << NNS;
4111 if (!getLangOpts().CPlusPlus20)
4112 DB << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "typename ");
4113 } else
4114 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_typename_missing_template) << NNS;
4115
4116 // FIXME: This is not quite correct recovery as we don't transform SS
4117 // into the corresponding dependent form (and we don't diagnose missing
4118 // 'template' keywords within SS as a result).
4119 return ActOnTypenameType(S: nullptr, TypenameLoc: SourceLocation(), SS, TemplateLoc: TemplateKWLoc,
4120 TemplateName: TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4121 TemplateArgs: TemplateArgsIn, RAngleLoc);
4122 }
4123
4124 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4125 // it's not actually allowed to be used as a type in most cases. Because
4126 // we annotate it before we know whether it's valid, we have to check for
4127 // this case here.
4128 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
4129 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4130 Diag(Loc: TemplateIILoc,
4131 DiagID: TemplateKWLoc.isInvalid()
4132 ? diag::err_out_of_line_qualified_id_type_names_constructor
4133 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4134 << TemplateII << 0 /*injected-class-name used as template name*/
4135 << 1 /*if any keyword was present, it was 'template'*/;
4136 }
4137 }
4138
4139 // Translate the parser's template argument list in our AST format.
4140 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4141 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4142
4143 QualType SpecTy = CheckTemplateIdType(
4144 Keyword: ElaboratedKeyword, Name: TemplateD.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
4145 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4146 if (SpecTy.isNull())
4147 return true;
4148
4149 // Build type-source information.
4150 TypeLocBuilder TLB;
4151 TLB.push<TemplateSpecializationTypeLoc>(T: SpecTy).set(
4152 ElaboratedKeywordLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
4153 NameLoc: TemplateIILoc, TAL: TemplateArgs);
4154 return CreateParsedType(T: SpecTy, TInfo: TLB.getTypeSourceInfo(Context, T: SpecTy));
4155}
4156
4157TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4158 TypeSpecifierType TagSpec,
4159 SourceLocation TagLoc,
4160 CXXScopeSpec &SS,
4161 SourceLocation TemplateKWLoc,
4162 TemplateTy TemplateD,
4163 SourceLocation TemplateLoc,
4164 SourceLocation LAngleLoc,
4165 ASTTemplateArgsPtr TemplateArgsIn,
4166 SourceLocation RAngleLoc) {
4167 if (SS.isInvalid())
4168 return TypeResult(true);
4169
4170 // Translate the parser's template argument list in our AST format.
4171 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4172 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4173
4174 // Determine the tag kind
4175 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
4176 ElaboratedTypeKeyword Keyword
4177 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
4178
4179 QualType Result =
4180 CheckTemplateIdType(Keyword, Name: TemplateD.get(), TemplateLoc, TemplateArgs,
4181 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4182 if (Result.isNull())
4183 return TypeResult(true);
4184
4185 // Check the tag kind
4186 if (const RecordType *RT = Result->getAs<RecordType>()) {
4187 RecordDecl *D = RT->getDecl();
4188
4189 IdentifierInfo *Id = D->getIdentifier();
4190 assert(Id && "templated class must have an identifier");
4191
4192 if (!isAcceptableTagRedeclaration(Previous: D, NewTag: TagKind, isDefinition: TUK == TagUseKind::Definition,
4193 NewTagLoc: TagLoc, Name: Id)) {
4194 Diag(Loc: TagLoc, DiagID: diag::err_use_with_wrong_tag)
4195 << Result
4196 << FixItHint::CreateReplacement(RemoveRange: SourceRange(TagLoc), Code: D->getKindName());
4197 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_use);
4198 }
4199 }
4200
4201 // Provide source-location information for the template specialization.
4202 TypeLocBuilder TLB;
4203 TLB.push<TemplateSpecializationTypeLoc>(T: Result).set(
4204 ElaboratedKeywordLoc: TagLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc, NameLoc: TemplateLoc,
4205 TAL: TemplateArgs);
4206 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
4207}
4208
4209static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4210 NamedDecl *PrevDecl,
4211 SourceLocation Loc,
4212 bool IsPartialSpecialization);
4213
4214static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4215
4216static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg,
4217 unsigned Depth,
4218 unsigned Index) {
4219 switch (Arg.getKind()) {
4220 case TemplateArgument::Null:
4221 case TemplateArgument::NullPtr:
4222 case TemplateArgument::Integral:
4223 case TemplateArgument::Declaration:
4224 case TemplateArgument::StructuralValue:
4225 case TemplateArgument::Pack:
4226 case TemplateArgument::TemplateExpansion:
4227 return false;
4228
4229 case TemplateArgument::Type: {
4230 QualType Type = Arg.getAsType();
4231 const TemplateTypeParmType *TPT =
4232 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4233 return TPT && !Type.hasQualifiers() &&
4234 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4235 }
4236
4237 case TemplateArgument::Expression: {
4238 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg.getAsExpr());
4239 if (!DRE || !DRE->getDecl())
4240 return false;
4241 const NonTypeTemplateParmDecl *NTTP =
4242 dyn_cast<NonTypeTemplateParmDecl>(Val: DRE->getDecl());
4243 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4244 }
4245
4246 case TemplateArgument::Template:
4247 const TemplateTemplateParmDecl *TTP =
4248 dyn_cast_or_null<TemplateTemplateParmDecl>(
4249 Val: Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4250 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4251 }
4252 llvm_unreachable("unexpected kind of template argument");
4253}
4254
4255static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4256 TemplateParameterList *SpecParams,
4257 ArrayRef<TemplateArgument> Args) {
4258 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4259 return false;
4260
4261 unsigned Depth = Params->getDepth();
4262
4263 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4264 TemplateArgument Arg = Args[I];
4265
4266 // If the parameter is a pack expansion, the argument must be a pack
4267 // whose only element is a pack expansion.
4268 if (Params->getParam(Idx: I)->isParameterPack()) {
4269 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4270 !Arg.pack_begin()->isPackExpansion())
4271 return false;
4272 Arg = Arg.pack_begin()->getPackExpansionPattern();
4273 }
4274
4275 if (!isTemplateArgumentTemplateParameter(Arg, Depth, Index: I))
4276 return false;
4277
4278 // For NTTPs further specialization is allowed via deduced types, so
4279 // we need to make sure to only reject here if primary template and
4280 // specialization use the same type for the NTTP.
4281 if (auto *SpecNTTP =
4282 dyn_cast<NonTypeTemplateParmDecl>(Val: SpecParams->getParam(Idx: I))) {
4283 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: I));
4284 if (!NTTP || NTTP->getType().getCanonicalType() !=
4285 SpecNTTP->getType().getCanonicalType())
4286 return false;
4287 }
4288 }
4289
4290 return true;
4291}
4292
4293template<typename PartialSpecDecl>
4294static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4295 if (Partial->getDeclContext()->isDependentContext())
4296 return;
4297
4298 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4299 // for non-substitution-failure issues?
4300 TemplateDeductionInfo Info(Partial->getLocation());
4301 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4302 return;
4303
4304 auto *Template = Partial->getSpecializedTemplate();
4305 S.Diag(Partial->getLocation(),
4306 diag::ext_partial_spec_not_more_specialized_than_primary)
4307 << isa<VarTemplateDecl>(Template);
4308
4309 if (Info.hasSFINAEDiagnostic()) {
4310 PartialDiagnosticAt Diag = {SourceLocation(),
4311 PartialDiagnostic::NullDiagnostic()};
4312 Info.takeSFINAEDiagnostic(PD&: Diag);
4313 SmallString<128> SFINAEArgString;
4314 Diag.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
4315 S.Diag(Loc: Diag.first,
4316 DiagID: diag::note_partial_spec_not_more_specialized_than_primary)
4317 << SFINAEArgString;
4318 }
4319
4320 S.NoteTemplateLocation(Decl: *Template);
4321 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4322 Template->getAssociatedConstraints(TemplateAC);
4323 Partial->getAssociatedConstraints(PartialAC);
4324 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Partial, AC1: PartialAC, D2: Template,
4325 AC2: TemplateAC);
4326}
4327
4328static void
4329noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4330 const llvm::SmallBitVector &DeducibleParams) {
4331 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4332 if (!DeducibleParams[I]) {
4333 NamedDecl *Param = TemplateParams->getParam(Idx: I);
4334 if (Param->getDeclName())
4335 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4336 << Param->getDeclName();
4337 else
4338 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4339 << "(anonymous)";
4340 }
4341 }
4342}
4343
4344
4345template<typename PartialSpecDecl>
4346static void checkTemplatePartialSpecialization(Sema &S,
4347 PartialSpecDecl *Partial) {
4348 // C++1z [temp.class.spec]p8: (DR1495)
4349 // - The specialization shall be more specialized than the primary
4350 // template (14.5.5.2).
4351 checkMoreSpecializedThanPrimary(S, Partial);
4352
4353 // C++ [temp.class.spec]p8: (DR1315)
4354 // - Each template-parameter shall appear at least once in the
4355 // template-id outside a non-deduced context.
4356 // C++1z [temp.class.spec.match]p3 (P0127R2)
4357 // If the template arguments of a partial specialization cannot be
4358 // deduced because of the structure of its template-parameter-list
4359 // and the template-id, the program is ill-formed.
4360 auto *TemplateParams = Partial->getTemplateParameters();
4361 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4362 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4363 TemplateParams->getDepth(), DeducibleParams);
4364
4365 if (!DeducibleParams.all()) {
4366 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4367 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4368 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4369 << (NumNonDeducible > 1)
4370 << SourceRange(Partial->getLocation(),
4371 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4372 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4373 }
4374}
4375
4376void Sema::CheckTemplatePartialSpecialization(
4377 ClassTemplatePartialSpecializationDecl *Partial) {
4378 checkTemplatePartialSpecialization(S&: *this, Partial);
4379}
4380
4381void Sema::CheckTemplatePartialSpecialization(
4382 VarTemplatePartialSpecializationDecl *Partial) {
4383 checkTemplatePartialSpecialization(S&: *this, Partial);
4384}
4385
4386void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4387 // C++1z [temp.param]p11:
4388 // A template parameter of a deduction guide template that does not have a
4389 // default-argument shall be deducible from the parameter-type-list of the
4390 // deduction guide template.
4391 auto *TemplateParams = TD->getTemplateParameters();
4392 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4393 MarkDeducedTemplateParameters(FunctionTemplate: TD, Deduced&: DeducibleParams);
4394 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4395 // A parameter pack is deducible (to an empty pack).
4396 auto *Param = TemplateParams->getParam(Idx: I);
4397 if (Param->isParameterPack() || hasVisibleDefaultArgument(D: Param))
4398 DeducibleParams[I] = true;
4399 }
4400
4401 if (!DeducibleParams.all()) {
4402 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4403 Diag(Loc: TD->getLocation(), DiagID: diag::err_deduction_guide_template_not_deducible)
4404 << (NumNonDeducible > 1);
4405 noteNonDeducibleParameters(S&: *this, TemplateParams, DeducibleParams);
4406 }
4407}
4408
4409DeclResult Sema::ActOnVarTemplateSpecialization(
4410 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
4411 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4412 StorageClass SC, bool IsPartialSpecialization) {
4413 // D must be variable template id.
4414 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4415 "Variable template specialization is declared with a template id.");
4416
4417 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4418 TemplateArgumentListInfo TemplateArgs =
4419 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TemplateId);
4420 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4421 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4422 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4423
4424 TemplateName Name = TemplateId->Template.get();
4425
4426 // The template-id must name a variable template.
4427 VarTemplateDecl *VarTemplate =
4428 dyn_cast_or_null<VarTemplateDecl>(Val: Name.getAsTemplateDecl());
4429 if (!VarTemplate) {
4430 NamedDecl *FnTemplate;
4431 if (auto *OTS = Name.getAsOverloadedTemplate())
4432 FnTemplate = *OTS->begin();
4433 else
4434 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Val: Name.getAsTemplateDecl());
4435 if (FnTemplate)
4436 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template_but_method)
4437 << FnTemplate->getDeclName();
4438 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template)
4439 << IsPartialSpecialization;
4440 }
4441
4442 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4443 auto Message = DSA->getMessage();
4444 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
4445 << VarTemplate << !Message.empty() << Message;
4446 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
4447 }
4448
4449 // Check for unexpanded parameter packs in any of the template arguments.
4450 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4451 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
4452 UPPC: IsPartialSpecialization
4453 ? UPPC_PartialSpecialization
4454 : UPPC_ExplicitSpecialization))
4455 return true;
4456
4457 // Check that the template argument list is well-formed for this
4458 // template.
4459 CheckTemplateArgumentInfo CTAI;
4460 if (CheckTemplateArgumentList(Template: VarTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
4461 /*DefaultArgs=*/{},
4462 /*PartialTemplateArgs=*/false, CTAI,
4463 /*UpdateArgsWithConversions=*/true))
4464 return true;
4465
4466 // Find the variable template (partial) specialization declaration that
4467 // corresponds to these arguments.
4468 if (IsPartialSpecialization) {
4469 if (CheckTemplatePartialSpecializationArgs(Loc: TemplateNameLoc, PrimaryTemplate: VarTemplate,
4470 NumExplicitArgs: TemplateArgs.size(),
4471 Args: CTAI.CanonicalConverted))
4472 return true;
4473
4474 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4475 // we also do them during instantiation.
4476 if (!Name.isDependent() &&
4477 !TemplateSpecializationType::anyDependentTemplateArguments(
4478 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4479 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
4480 << VarTemplate->getDeclName();
4481 IsPartialSpecialization = false;
4482 }
4483
4484 if (isSameAsPrimaryTemplate(Params: VarTemplate->getTemplateParameters(),
4485 SpecParams: TemplateParams, Args: CTAI.CanonicalConverted) &&
4486 (!Context.getLangOpts().CPlusPlus20 ||
4487 !TemplateParams->hasAssociatedConstraints())) {
4488 // C++ [temp.class.spec]p9b3:
4489 //
4490 // -- The argument list of the specialization shall not be identical
4491 // to the implicit argument list of the primary template.
4492 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
4493 << /*variable template*/ 1
4494 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4495 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
4496 // FIXME: Recover from this by treating the declaration as a
4497 // redeclaration of the primary template.
4498 return true;
4499 }
4500 }
4501
4502 llvm::FoldingSetInsertToken InsertToken;
4503 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4504
4505 if (IsPartialSpecialization)
4506 PrevDecl = VarTemplate->findPartialSpecialization(
4507 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertToken);
4508 else
4509 PrevDecl =
4510 VarTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertToken);
4511
4512 VarTemplateSpecializationDecl *Specialization = nullptr;
4513
4514 // Check whether we can declare a variable template specialization in
4515 // the current scope.
4516 if (CheckTemplateSpecializationScope(S&: *this, Specialized: VarTemplate, PrevDecl,
4517 Loc: TemplateNameLoc,
4518 IsPartialSpecialization))
4519 return true;
4520
4521 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4522 // Since the only prior variable template specialization with these
4523 // arguments was referenced but not declared, reuse that
4524 // declaration node as our own, updating its source location and
4525 // the list of outer template parameters to reflect our new declaration.
4526 Specialization = PrevDecl;
4527 Specialization->setLocation(TemplateNameLoc);
4528 PrevDecl = nullptr;
4529 } else if (IsPartialSpecialization) {
4530 // Create a new class template partial specialization declaration node.
4531 VarTemplatePartialSpecializationDecl *PrevPartial =
4532 cast_or_null<VarTemplatePartialSpecializationDecl>(Val: PrevDecl);
4533 VarTemplatePartialSpecializationDecl *Partial =
4534 VarTemplatePartialSpecializationDecl::Create(
4535 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc,
4536 IdLoc: TemplateNameLoc, Params: TemplateParams, SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI,
4537 S: SC, Args: CTAI.CanonicalConverted);
4538 Partial->setTemplateArgsAsWritten(TemplateArgs);
4539
4540 if (!PrevPartial)
4541 VarTemplate->AddPartialSpecialization(D: Partial, InsertToken);
4542 Specialization = Partial;
4543
4544 CheckTemplatePartialSpecialization(Partial);
4545 } else {
4546 // Create a new class template specialization declaration node for
4547 // this explicit specialization or friend declaration.
4548 Specialization = VarTemplateSpecializationDecl::Create(
4549 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc, IdLoc: TemplateNameLoc,
4550 SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI, S: SC, Args: CTAI.CanonicalConverted);
4551 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4552
4553 if (!PrevDecl)
4554 VarTemplate->AddSpecialization(D: Specialization, InsertToken);
4555 }
4556
4557 // C++ [temp.expl.spec]p6:
4558 // If a template, a member template or the member of a class template is
4559 // explicitly specialized then that specialization shall be declared
4560 // before the first use of that specialization that would cause an implicit
4561 // instantiation to take place, in every translation unit in which such a
4562 // use occurs; no diagnostic is required.
4563 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4564 bool Okay = false;
4565 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4566 // Is there any previous explicit specialization declaration?
4567 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
4568 Okay = true;
4569 break;
4570 }
4571 }
4572
4573 if (!Okay) {
4574 SourceRange Range(TemplateNameLoc, RAngleLoc);
4575 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
4576 << Name << Range;
4577
4578 Diag(Loc: PrevDecl->getPointOfInstantiation(),
4579 DiagID: diag::note_instantiation_required_here)
4580 << (PrevDecl->getTemplateSpecializationKind() !=
4581 TSK_ImplicitInstantiation);
4582 return true;
4583 }
4584 }
4585
4586 Specialization->setLexicalDeclContext(CurContext);
4587
4588 // Add the specialization into its lexical context, so that it can
4589 // be seen when iterating through the list of declarations in that
4590 // context. However, specializations are not found by name lookup.
4591 CurContext->addDecl(D: Specialization);
4592
4593 // Note that this is an explicit specialization.
4594 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4595
4596 Previous.clear();
4597 if (PrevDecl)
4598 Previous.addDecl(D: PrevDecl);
4599 else if (Specialization->isStaticDataMember() &&
4600 Specialization->isOutOfLine())
4601 Specialization->setAccess(VarTemplate->getAccess());
4602
4603 return Specialization;
4604}
4605
4606namespace {
4607/// A partial specialization whose template arguments have matched
4608/// a given template-id.
4609struct PartialSpecMatchResult {
4610 VarTemplatePartialSpecializationDecl *Partial;
4611 TemplateArgumentList *Args;
4612};
4613
4614// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4615// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4616static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4617 if (Var->getName() != "format_kind" ||
4618 !Var->getDeclContext()->isStdNamespace())
4619 return false;
4620
4621 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4622 // release in which users can access std::format_kind.
4623 // We can use 20250520 as the final date, see the following commits.
4624 // GCC releases/gcc-15 branch:
4625 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4626 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4627 // GCC master branch:
4628 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4629 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4630 return PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2025'05'20);
4631}
4632} // end anonymous namespace
4633
4634DeclResult
4635Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4636 SourceLocation TemplateNameLoc,
4637 const TemplateArgumentListInfo &TemplateArgs,
4638 bool SetWrittenArgs) {
4639 assert(Template && "A variable template id without template?");
4640
4641 // Check that the template argument list is well-formed for this template.
4642 CheckTemplateArgumentInfo CTAI;
4643 if (CheckTemplateArgumentList(
4644 Template, TemplateLoc: TemplateNameLoc,
4645 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4646 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4647 /*UpdateArgsWithConversions=*/true))
4648 return true;
4649
4650 // Produce a placeholder value if the specialization is dependent.
4651 if (Template->getDeclContext()->isDependentContext() ||
4652 TemplateSpecializationType::anyDependentTemplateArguments(
4653 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4654 if (ParsingInitForAutoVars.empty())
4655 return DeclResult();
4656
4657 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4658 const TemplateArgument &Arg2) {
4659 return Context.isSameTemplateArgument(Arg1, Arg2);
4660 };
4661
4662 if (VarDecl *Var = Template->getTemplatedDecl();
4663 ParsingInitForAutoVars.count(Ptr: Var) &&
4664 // See comments on this function definition
4665 !IsLibstdcxxStdFormatKind(PP, Var) &&
4666 llvm::equal(
4667 LRange&: CTAI.CanonicalConverted,
4668 RRange: Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4669 P: IsSameTemplateArg)) {
4670 Diag(Loc: TemplateNameLoc,
4671 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4672 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4673 return true;
4674 }
4675
4676 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4677 Template->getPartialSpecializations(PS&: PartialSpecs);
4678 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4679 if (ParsingInitForAutoVars.count(Ptr: Partial) &&
4680 llvm::equal(LRange&: CTAI.CanonicalConverted,
4681 RRange: Partial->getTemplateArgs().asArray(),
4682 P: IsSameTemplateArg)) {
4683 Diag(Loc: TemplateNameLoc,
4684 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4685 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4686 << Partial->getType();
4687 return true;
4688 }
4689
4690 return DeclResult();
4691 }
4692
4693 // Find the variable template specialization declaration that
4694 // corresponds to these arguments.
4695 llvm::FoldingSetInsertToken InsertToken;
4696 if (VarTemplateSpecializationDecl *Spec =
4697 Template->findSpecialization(Args: CTAI.CanonicalConverted, InsertToken)) {
4698 checkSpecializationReachability(Loc: TemplateNameLoc, Spec);
4699 if (Spec->getType()->isUndeducedType()) {
4700 if (ParsingInitForAutoVars.count(Ptr: Spec))
4701 Diag(Loc: TemplateNameLoc,
4702 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4703 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4704 << Spec->getType();
4705 else
4706 // We are substituting the initializer of this variable template
4707 // specialization.
4708 Diag(Loc: TemplateNameLoc, DiagID: diag::err_var_template_spec_type_depends_on_self)
4709 << Spec << Spec->getType();
4710
4711 return true;
4712 }
4713 // If we already have a variable template specialization, return it.
4714 return Spec;
4715 }
4716
4717 // This is the first time we have referenced this variable template
4718 // specialization. Create the canonical declaration and add it to
4719 // the set of specializations, based on the closest partial specialization
4720 // that it represents. That is,
4721 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4722 const TemplateArgumentList *PartialSpecArgs = nullptr;
4723 bool AmbiguousPartialSpec = false;
4724 typedef PartialSpecMatchResult MatchResult;
4725 SmallVector<MatchResult, 4> Matched;
4726 SourceLocation PointOfInstantiation = TemplateNameLoc;
4727 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4728 /*ForTakingAddress=*/false);
4729
4730 // 1. Attempt to find the closest partial specialization that this
4731 // specializes, if any.
4732 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4733 // Perhaps better after unification of DeduceTemplateArguments() and
4734 // getMoreSpecializedPartialSpecialization().
4735 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4736 Template->getPartialSpecializations(PS&: PartialSpecs);
4737
4738 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4739 // C++ [temp.spec.partial.member]p2:
4740 // If the primary member template is explicitly specialized for a given
4741 // (implicit) specialization of the enclosing class template, the partial
4742 // specializations of the member template are ignored for this
4743 // specialization of the enclosing class template. If a partial
4744 // specialization of the member template is explicitly specialized for a
4745 // given (implicit) specialization of the enclosing class template, the
4746 // primary member template and its other partial specializations are still
4747 // considered for this specialization of the enclosing class template.
4748 if (Template->isMemberSpecialization() &&
4749 !Partial->isMemberSpecialization())
4750 continue;
4751
4752 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4753
4754 if (TemplateDeductionResult Result =
4755 DeduceTemplateArguments(Partial, TemplateArgs: CTAI.SugaredConverted, Info);
4756 Result != TemplateDeductionResult::Success) {
4757 // Store the failed-deduction information for use in diagnostics, later.
4758 // TODO: Actually use the failed-deduction info?
4759 FailedCandidates.addCandidate().set(
4760 Found: DeclAccessPair::make(D: Template, AS: AS_public), Spec: Partial,
4761 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
4762 (void)Result;
4763 } else {
4764 Matched.push_back(Elt: PartialSpecMatchResult());
4765 Matched.back().Partial = Partial;
4766 Matched.back().Args = Info.takeSugared();
4767 }
4768 }
4769
4770 if (Matched.size() >= 1) {
4771 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4772 if (Matched.size() == 1) {
4773 // -- If exactly one matching specialization is found, the
4774 // instantiation is generated from that specialization.
4775 // We don't need to do anything for this.
4776 } else {
4777 // -- If more than one matching specialization is found, the
4778 // partial order rules (14.5.4.2) are used to determine
4779 // whether one of the specializations is more specialized
4780 // than the others. If none of the specializations is more
4781 // specialized than all of the other matching
4782 // specializations, then the use of the variable template is
4783 // ambiguous and the program is ill-formed.
4784 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4785 PEnd = Matched.end();
4786 P != PEnd; ++P) {
4787 if (getMoreSpecializedPartialSpecialization(PS1: P->Partial, PS2: Best->Partial,
4788 Loc: PointOfInstantiation) ==
4789 P->Partial)
4790 Best = P;
4791 }
4792
4793 // Determine if the best partial specialization is more specialized than
4794 // the others.
4795 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4796 PEnd = Matched.end();
4797 P != PEnd; ++P) {
4798 if (P != Best && getMoreSpecializedPartialSpecialization(
4799 PS1: P->Partial, PS2: Best->Partial,
4800 Loc: PointOfInstantiation) != Best->Partial) {
4801 AmbiguousPartialSpec = true;
4802 break;
4803 }
4804 }
4805 }
4806
4807 // Instantiate using the best variable template partial specialization.
4808 InstantiationPattern = Best->Partial;
4809 PartialSpecArgs = Best->Args;
4810 } else {
4811 // -- If no match is found, the instantiation is generated
4812 // from the primary template.
4813 // InstantiationPattern = Template->getTemplatedDecl();
4814 }
4815
4816 // 2. Create the canonical declaration.
4817 // Note that we do not instantiate a definition until we see an odr-use
4818 // in DoMarkVarDeclReferenced().
4819 // FIXME: LateAttrs et al.?
4820 if (AmbiguousPartialSpec) {
4821 // Partial ordering did not produce a clear winner. Complain.
4822 Diag(Loc: PointOfInstantiation, DiagID: diag::err_partial_spec_ordering_ambiguous)
4823 << Template;
4824 // Print the matching partial specializations.
4825 for (MatchResult P : Matched)
4826 Diag(Loc: P.Partial->getLocation(), DiagID: diag::note_partial_spec_match)
4827 << getTemplateArgumentBindingsText(Params: P.Partial->getTemplateParameters(),
4828 Args: *P.Args);
4829 return true;
4830 }
4831
4832 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4833 VarTemplate: Template, FromVar: InstantiationPattern, PartialSpecArgs, Converted&: CTAI.CanonicalConverted,
4834 PointOfInstantiation: TemplateNameLoc /*, LateAttrs, StartingScope*/);
4835 if (!Decl)
4836 return true;
4837 if (SetWrittenArgs)
4838 Decl->setTemplateArgsAsWritten(TemplateArgs);
4839
4840 if (VarTemplatePartialSpecializationDecl *D =
4841 dyn_cast<VarTemplatePartialSpecializationDecl>(Val: InstantiationPattern))
4842 Decl->setInstantiationOf(PartialSpec: D, TemplateArgs: PartialSpecArgs);
4843
4844 checkSpecializationReachability(Loc: TemplateNameLoc, Spec: Decl);
4845
4846 assert(Decl && "No variable template specialization?");
4847 return Decl;
4848}
4849
4850ExprResult Sema::CheckVarTemplateId(
4851 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4852 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4853 const TemplateArgumentListInfo *TemplateArgs) {
4854
4855 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, TemplateNameLoc: NameInfo.getLoc(),
4856 TemplateArgs: *TemplateArgs, /*SetWrittenArgs=*/false);
4857 if (Decl.isInvalid())
4858 return ExprError();
4859
4860 if (!Decl.get())
4861 return ExprResult();
4862
4863 VarDecl *Var = cast<VarDecl>(Val: Decl.get());
4864 if (!Var->getTemplateSpecializationKind())
4865 Var->setTemplateSpecializationKind(TSK: TSK_ImplicitInstantiation,
4866 PointOfInstantiation: NameInfo.getLoc());
4867
4868 // Build an ordinary singleton decl ref.
4869 return BuildDeclarationNameExpr(SS, NameInfo, D: Var, FoundD, TemplateArgs);
4870}
4871
4872ExprResult Sema::CheckVarOrConceptTemplateTemplateId(
4873 const DeclarationNameInfo &NameInfo, TemplateName Template,
4874 const TemplateArgumentListInfo *TemplateArgs) {
4875 TemplateTemplateParmDecl *Parameter =
4876 Template.getAsTemplateTemplateParmDecl();
4877 assert(Parameter && "A variable template id without template?");
4878
4879 if (Parameter->templateParameterKind() !=
4880 TemplateNameKind::TNK_Var_template &&
4881 Parameter->templateParameterKind() !=
4882 TemplateNameKind::TNK_Concept_template)
4883 return ExprResult();
4884
4885 // Check that the template argument list is well-formed for this template.
4886 CheckTemplateArgumentInfo CTAI;
4887 if (CheckTemplateArgumentList(
4888 Template: Parameter, /*Template kw loc=*/TemplateLoc: {},
4889 // FIXME: TemplateArgs will not be modified because
4890 // UpdateArgsWithConversions is false, however, we should
4891 // CheckTemplateArgumentList to be const-correct.
4892 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4893 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4894 /*UpdateArgsWithConversions=*/false))
4895 return true;
4896
4897 return DependentTemplateIdExpr::Create(Context: getASTContext(), NameInfo, Name: Template,
4898 TemplateArgs: *TemplateArgs);
4899}
4900
4901void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4902 SourceLocation Loc) {
4903 Diag(Loc, DiagID: diag::err_template_missing_args)
4904 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4905 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4906 NoteTemplateLocation(Decl: *TD, ParamRange: TD->getTemplateParameters()->getSourceRange());
4907 }
4908}
4909
4910void Sema::diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
4911 bool TemplateKeyword,
4912 TemplateDecl *TD,
4913 SourceLocation Loc) {
4914 TemplateName Name = Context.getQualifiedTemplateName(
4915 Qualifier: SS.getScopeRep(), TemplateKeyword, Template: TemplateName(TD));
4916 diagnoseMissingTemplateArguments(Name, Loc);
4917}
4918
4919ExprResult Sema::CheckConceptTemplateId(
4920 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4921 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4922 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4923 bool DoCheckConstraintSatisfaction) {
4924 assert(NamedConcept && "A concept template id without a template?");
4925
4926 if (NamedConcept->isInvalidDecl())
4927 return ExprError();
4928
4929 CheckTemplateArgumentInfo CTAI;
4930 if (CheckTemplateArgumentList(
4931 Template: NamedConcept, TemplateLoc: ConceptNameInfo.getLoc(),
4932 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4933 /*DefaultArgs=*/{},
4934 /*PartialTemplateArgs=*/false, CTAI,
4935 /*UpdateArgsWithConversions=*/false))
4936 return ExprError();
4937
4938 DiagnoseUseOfDecl(D: NamedConcept, Locs: ConceptNameInfo.getLoc());
4939
4940 // There's a bug with CTAI.CanonicalConverted.
4941 // If the template argument contains a DependentDecltypeType that includes a
4942 // TypeAliasType, and the same written type had occurred previously in the
4943 // source, then the DependentDecltypeType would be canonicalized to that
4944 // previous type which would mess up the substitution.
4945 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4946 auto *CSD = ImplicitConceptSpecializationDecl::Create(
4947 C: Context, DC: NamedConcept->getDeclContext(), SL: NamedConcept->getLocation(),
4948 ConvertedArgs: CTAI.SugaredConverted);
4949 ConstraintSatisfaction Satisfaction;
4950 bool AreArgsDependent =
4951 TemplateSpecializationType::anyDependentTemplateArguments(
4952 *TemplateArgs, Converted: CTAI.SugaredConverted);
4953 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4954 /*Final=*/false);
4955 auto *CL = ConceptReference::Create(
4956 C: Context,
4957 NNS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4958 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept: TemplateName(NamedConcept),
4959 ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: *TemplateArgs));
4960
4961 bool Error = false;
4962 if (const auto *Concept = dyn_cast<ConceptDecl>(Val: NamedConcept);
4963 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4964 DoCheckConstraintSatisfaction) {
4965
4966 LocalInstantiationScope Scope(*this);
4967
4968 EnterExpressionEvaluationContext EECtx{
4969 *this, ExpressionEvaluationContext::Unevaluated};
4970
4971 Error = CheckConstraintSatisfaction(
4972 Entity: NamedConcept, AssociatedConstraints: AssociatedConstraint(Concept->getConstraintExpr()), TemplateArgLists: MLTAL,
4973 TemplateIDRange: SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4974 TemplateArgs->getRAngleLoc()),
4975 Satisfaction, TopLevelConceptId: CL);
4976 Satisfaction.ContainsErrors = Error;
4977 }
4978
4979 if (Error)
4980 return ExprError();
4981
4982 return ConceptSpecializationExpr::Create(
4983 C: Context, ConceptRef: CL, SpecDecl: CSD, Satisfaction: AreArgsDependent ? nullptr : &Satisfaction);
4984}
4985
4986ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4987 SourceLocation TemplateKWLoc,
4988 LookupResult &R,
4989 bool RequiresADL,
4990 const TemplateArgumentListInfo *TemplateArgs) {
4991 // FIXME: Can we do any checking at this point? I guess we could check the
4992 // template arguments that we have against the template name, if the template
4993 // name refers to a single template. That's not a terribly common case,
4994 // though.
4995 // foo<int> could identify a single function unambiguously
4996 // This approach does NOT work, since f<int>(1);
4997 // gets resolved prior to resorting to overload resolution
4998 // i.e., template<class T> void f(double);
4999 // vs template<class T, class U> void f(U);
5000
5001 // These should be filtered out by our callers.
5002 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
5003
5004 // Non-function templates require a template argument list.
5005 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
5006 if (!TemplateArgs && !isa<FunctionTemplateDecl>(Val: TD)) {
5007 diagnoseMissingTemplateArguments(
5008 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, Loc: R.getNameLoc());
5009 return ExprError();
5010 }
5011 }
5012 bool KnownDependent = false;
5013 // In C++1y, check variable template ids.
5014 if (R.getAsSingle<VarTemplateDecl>()) {
5015 ExprResult Res = CheckVarTemplateId(
5016 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<VarTemplateDecl>(),
5017 FoundD: R.getRepresentativeDecl(), TemplateLoc: TemplateKWLoc, TemplateArgs);
5018 if (Res.isInvalid() || Res.isUsable())
5019 return Res;
5020 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
5021 KnownDependent = true;
5022 }
5023
5024 // We don't want lookup warnings at this point.
5025 R.suppressDiagnostics();
5026
5027 if (R.getAsSingle<ConceptDecl>()) {
5028 return CheckConceptTemplateId(SS, TemplateKWLoc, ConceptNameInfo: R.getLookupNameInfo(),
5029 FoundDecl: R.getRepresentativeDecl(),
5030 NamedConcept: R.getAsSingle<ConceptDecl>(), TemplateArgs);
5031 }
5032
5033 // Check variable template ids (C++17) and concept template parameters
5034 // (C++26).
5035 UnresolvedLookupExpr *ULE;
5036 if (R.getAsSingle<TemplateTemplateParmDecl>()) {
5037 assert(SS.isEmpty() && "template parameter with a scope specifier?");
5038 assert(TemplateKWLoc.isInvalid() &&
5039 "template keyword in front of a template parameter?");
5040 return CheckVarOrConceptTemplateTemplateId(
5041 NameInfo: R.getLookupNameInfo(),
5042 Template: TemplateName(R.getAsSingle<TemplateTemplateParmDecl>()), TemplateArgs);
5043 }
5044
5045 // Function templates
5046 ULE = UnresolvedLookupExpr::Create(
5047 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
5048 TemplateKWLoc, NameInfo: R.getLookupNameInfo(), RequiresADL, Args: TemplateArgs,
5049 Begin: R.begin(), End: R.end(), KnownDependent,
5050 /*KnownInstantiationDependent=*/false);
5051 // Model the templates with UnresolvedTemplateTy. The expression should then
5052 // either be transformed in an instantiation or be diagnosed in
5053 // CheckPlaceholderExpr.
5054 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5055 !R.getFoundDecl()->getAsFunction())
5056 ULE->setType(Context.UnresolvedTemplateTy);
5057
5058 return ULE;
5059}
5060
5061ExprResult Sema::BuildQualifiedTemplateIdExpr(
5062 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5063 const DeclarationNameInfo &NameInfo,
5064 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5065 assert(TemplateArgs || TemplateKWLoc.isValid());
5066
5067 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5068 if (LookupTemplateName(Found&: R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5069 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc))
5070 return ExprError();
5071
5072 if (R.isAmbiguous())
5073 return ExprError();
5074
5075 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5076 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5077
5078 if (R.empty()) {
5079 DeclContext *DC = computeDeclContext(SS);
5080 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
5081 << NameInfo.getName() << DC << SS.getRange();
5082 return ExprError();
5083 }
5084
5085 // If necessary, build an implicit class member access.
5086 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5087 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5088 /*S=*/nullptr);
5089
5090 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/RequiresADL: false, TemplateArgs);
5091}
5092
5093TemplateNameKind Sema::ActOnTemplateName(Scope *S,
5094 CXXScopeSpec &SS,
5095 SourceLocation TemplateKWLoc,
5096 const UnqualifiedId &Name,
5097 ParsedType ObjectType,
5098 bool EnteringContext,
5099 TemplateTy &Result,
5100 bool AllowInjectedClassName) {
5101 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5102 DiagCompat(Loc: TemplateKWLoc, CompatDiagId: diag_compat::template_outside_of_template)
5103 << FixItHint::CreateRemoval(RemoveRange: TemplateKWLoc);
5104
5105 if (SS.isInvalid())
5106 return TNK_Non_template;
5107
5108 // Figure out where isTemplateName is going to look.
5109 DeclContext *LookupCtx = nullptr;
5110 if (SS.isNotEmpty())
5111 LookupCtx = computeDeclContext(SS, EnteringContext);
5112 else if (ObjectType)
5113 LookupCtx = computeDeclContext(T: GetTypeFromParser(Ty: ObjectType));
5114
5115 // C++0x [temp.names]p5:
5116 // If a name prefixed by the keyword template is not the name of
5117 // a template, the program is ill-formed. [Note: the keyword
5118 // template may not be applied to non-template members of class
5119 // templates. -end note ] [ Note: as is the case with the
5120 // typename prefix, the template prefix is allowed in cases
5121 // where it is not strictly necessary; i.e., when the
5122 // nested-name-specifier or the expression on the left of the ->
5123 // or . is not dependent on a template-parameter, or the use
5124 // does not appear in the scope of a template. -end note]
5125 //
5126 // Note: C++03 was more strict here, because it banned the use of
5127 // the "template" keyword prior to a template-name that was not a
5128 // dependent name. C++ DR468 relaxed this requirement (the
5129 // "template" keyword is now permitted). We follow the C++0x
5130 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5131 bool MemberOfUnknownSpecialization;
5132 TemplateNameKind TNK = isTemplateName(S, SS, hasTemplateKeyword: TemplateKWLoc.isValid(), Name,
5133 ObjectTypePtr: ObjectType, EnteringContext, TemplateResult&: Result,
5134 MemberOfUnknownSpecialization);
5135 if (TNK != TNK_Non_template) {
5136 // We resolved this to a (non-dependent) template name. Return it.
5137 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
5138 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5139 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5140 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5141 // C++14 [class.qual]p2:
5142 // In a lookup in which function names are not ignored and the
5143 // nested-name-specifier nominates a class C, if the name specified
5144 // [...] is the injected-class-name of C, [...] the name is instead
5145 // considered to name the constructor
5146 //
5147 // We don't get here if naming the constructor would be valid, so we
5148 // just reject immediately and recover by treating the
5149 // injected-class-name as naming the template.
5150 Diag(Loc: Name.getBeginLoc(),
5151 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
5152 << Name.Identifier
5153 << 0 /*injected-class-name used as template name*/
5154 << TemplateKWLoc.isValid();
5155 }
5156 return TNK;
5157 }
5158
5159 if (!MemberOfUnknownSpecialization) {
5160 // Didn't find a template name, and the lookup wasn't dependent.
5161 // Do the lookup again to determine if this is a "nothing found" case or
5162 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5163 // need to do this.
5164 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
5165 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5166 LookupOrdinaryName);
5167 // Tell LookupTemplateName that we require a template so that it diagnoses
5168 // cases where it finds a non-template.
5169 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5170 ? RequiredTemplateKind(TemplateKWLoc)
5171 : TemplateNameIsRequired;
5172 if (!LookupTemplateName(Found&: R, S, SS, ObjectType: ObjectType.get(), EnteringContext, RequiredTemplate: RTK,
5173 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5174 !R.isAmbiguous()) {
5175 if (LookupCtx)
5176 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_no_member)
5177 << DNI.getName() << LookupCtx << SS.getRange();
5178 else
5179 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_undeclared_use)
5180 << DNI.getName() << SS.getRange();
5181 }
5182 return TNK_Non_template;
5183 }
5184
5185 NestedNameSpecifier Qualifier = SS.getScopeRep();
5186
5187 switch (Name.getKind()) {
5188 case UnqualifiedIdKind::IK_Identifier:
5189 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5190 Name: {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5191 return TNK_Dependent_template_name;
5192
5193 case UnqualifiedIdKind::IK_OperatorFunctionId:
5194 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5195 Name: {Qualifier, Name.OperatorFunctionId.Operator,
5196 TemplateKWLoc.isValid()}));
5197 return TNK_Function_template;
5198
5199 case UnqualifiedIdKind::IK_LiteralOperatorId:
5200 // This is a kind of template name, but can never occur in a dependent
5201 // scope (literal operators can only be declared at namespace scope).
5202 break;
5203
5204 default:
5205 break;
5206 }
5207
5208 // This name cannot possibly name a dependent template. Diagnose this now
5209 // rather than building a dependent template name that can never be valid.
5210 Diag(Loc: Name.getBeginLoc(),
5211 DiagID: diag::err_template_kw_refers_to_dependent_non_template)
5212 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5213 << TemplateKWLoc.isValid() << TemplateKWLoc;
5214 return TNK_Non_template;
5215}
5216
5217bool Sema::CheckTemplateTypeArgument(
5218 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
5219 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5220 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5221 const TemplateArgument &Arg = AL.getArgument();
5222 QualType ArgType;
5223 TypeSourceInfo *TSI = nullptr;
5224
5225 // Check template type parameter.
5226 switch(Arg.getKind()) {
5227 case TemplateArgument::Type:
5228 // C++ [temp.arg.type]p1:
5229 // A template-argument for a template-parameter which is a
5230 // type shall be a type-id.
5231 ArgType = Arg.getAsType();
5232 TSI = AL.getTypeSourceInfo();
5233 break;
5234 case TemplateArgument::Template:
5235 case TemplateArgument::TemplateExpansion: {
5236 // We have a template type parameter but the template argument
5237 // is a template without any arguments.
5238 SourceRange SR = AL.getSourceRange();
5239 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5240 diagnoseMissingTemplateArguments(Name, Loc: SR.getEnd());
5241 return true;
5242 }
5243 case TemplateArgument::Expression: {
5244 // We have a template type parameter but the template argument is an
5245 // expression; see if maybe it is missing the "typename" keyword.
5246 CXXScopeSpec SS;
5247 DeclarationNameInfo NameInfo;
5248 TemplateArgument Pattern = Arg;
5249 if (Pattern.isPackExpansion())
5250 Pattern = Pattern.getPackExpansionPattern();
5251 Expr *E = Pattern.getAsExpr();
5252
5253 if (DependentScopeDeclRefExpr *ArgExpr =
5254 dyn_cast<DependentScopeDeclRefExpr>(Val: E)) {
5255 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5256 NameInfo = ArgExpr->getNameInfo();
5257 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5258 dyn_cast<CXXDependentScopeMemberExpr>(Val: E)) {
5259 if (ArgExpr->isImplicitAccess()) {
5260 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5261 NameInfo = ArgExpr->getMemberNameInfo();
5262 }
5263 }
5264
5265 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5266 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5267 LookupParsedName(R&: Result, S: CurScope, SS: &SS, /*ObjectType=*/QualType());
5268
5269 if (Result.getAsSingle<TypeDecl>() ||
5270 Result.wasNotFoundInCurrentInstantiation()) {
5271 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5272 // Suggest that the user add 'typename' before the NNS.
5273 SourceLocation Loc = AL.getSourceRange().getBegin();
5274 Diag(Loc, DiagID: getLangOpts().MSVCCompat
5275 ? diag::ext_ms_template_type_arg_missing_typename
5276 : diag::err_template_arg_must_be_type_suggest)
5277 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
5278 NoteTemplateParameterLocation(Decl: *Param);
5279
5280 // Recover by synthesizing a type using the location information that we
5281 // already have.
5282 ArgType = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
5283 NNS: SS.getScopeRep(), Name: II);
5284 TypeLocBuilder TLB;
5285 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: ArgType);
5286 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5287 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5288 TL.setNameLoc(NameInfo.getLoc());
5289 if (Arg.isPackExpansion()) {
5290 ArgType = Context.getPackExpansionType(Pattern: ArgType, NumExpansions: std::nullopt);
5291 PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(T: ArgType);
5292 TL.setEllipsisLoc(
5293 cast<PackExpansionExpr>(Val: Arg.getAsExpr())->getEllipsisLoc());
5294 }
5295 TSI = TLB.getTypeSourceInfo(Context, T: ArgType);
5296
5297 // Overwrite our input TemplateArgumentLoc so that we can recover
5298 // properly.
5299 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5300 TemplateArgumentLocInfo(TSI));
5301
5302 break;
5303 }
5304 }
5305 // fallthrough
5306 [[fallthrough]];
5307 }
5308 default: {
5309 // We allow instantiating a template with template argument packs when
5310 // building deduction guides or mapping constraint template parameters.
5311 if (Arg.getKind() == TemplateArgument::Pack &&
5312 (CodeSynthesisContexts.back().Kind ==
5313 Sema::CodeSynthesisContext::BuildingDeductionGuides ||
5314 inParameterMappingSubstitution())) {
5315 SugaredConverted.push_back(Elt: Arg);
5316 CanonicalConverted.push_back(Elt: Arg);
5317 return false;
5318 }
5319 // We have a template type parameter but the template argument
5320 // is not a type.
5321 SourceRange SR = AL.getSourceRange();
5322 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_type) << SR;
5323 NoteTemplateParameterLocation(Decl: *Param);
5324
5325 return true;
5326 }
5327 }
5328
5329 if (CheckTemplateArgument(Arg: TSI))
5330 return true;
5331
5332 // Objective-C ARC:
5333 // If an explicitly-specified template argument type is a lifetime type
5334 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5335 if (getLangOpts().ObjCAutoRefCount &&
5336 ArgType->isObjCLifetimeType() &&
5337 !ArgType.getObjCLifetime()) {
5338 Qualifiers Qs;
5339 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5340 ArgType = Context.getQualifiedType(T: ArgType, Qs);
5341 }
5342
5343 SugaredConverted.push_back(Elt: TemplateArgument(ArgType));
5344 CanonicalConverted.push_back(
5345 Elt: TemplateArgument(Context.getCanonicalType(T: ArgType)));
5346 return false;
5347}
5348
5349/// Substitute template arguments into the default template argument for
5350/// the given template type parameter.
5351///
5352/// \param SemaRef the semantic analysis object for which we are performing
5353/// the substitution.
5354///
5355/// \param Template the template that we are synthesizing template arguments
5356/// for.
5357///
5358/// \param TemplateLoc the location of the template name that started the
5359/// template-id we are checking.
5360///
5361/// \param RAngleLoc the location of the right angle bracket ('>') that
5362/// terminates the template-id.
5363///
5364/// \param Param the template template parameter whose default we are
5365/// substituting into.
5366///
5367/// \param Converted the list of template arguments provided for template
5368/// parameters that precede \p Param in the template parameter list.
5369///
5370/// \param Output the resulting substituted template argument.
5371///
5372/// \returns true if an error occurred.
5373static bool SubstDefaultTemplateArgument(
5374 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5375 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5376 ArrayRef<TemplateArgument> SugaredConverted,
5377 ArrayRef<TemplateArgument> CanonicalConverted,
5378 TemplateArgumentLoc &Output) {
5379 Output = Param->getDefaultArgument();
5380
5381 // If the argument type is dependent, instantiate it now based
5382 // on the previously-computed template arguments.
5383 if (Output.getArgument().isInstantiationDependent()) {
5384 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5385 SugaredConverted,
5386 SourceRange(TemplateLoc, RAngleLoc));
5387 if (Inst.isInvalid())
5388 return true;
5389
5390 // Only substitute for the innermost template argument list.
5391 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5392 /*Final=*/true);
5393 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5394 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5395
5396 bool ForLambdaCallOperator = false;
5397 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Val: Template->getDeclContext()))
5398 ForLambdaCallOperator = Rec->isLambda();
5399 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5400 !ForLambdaCallOperator);
5401
5402 if (SemaRef.SubstTemplateArgument(Input: Output, TemplateArgs: TemplateArgLists, Output,
5403 Loc: Param->getDefaultArgumentLoc(),
5404 Entity: Param->getDeclName()))
5405 return true;
5406 }
5407
5408 return false;
5409}
5410
5411/// Substitute template arguments into the default template argument for
5412/// the given non-type template parameter.
5413///
5414/// \param SemaRef the semantic analysis object for which we are performing
5415/// the substitution.
5416///
5417/// \param Template the template that we are synthesizing template arguments
5418/// for.
5419///
5420/// \param TemplateLoc the location of the template name that started the
5421/// template-id we are checking.
5422///
5423/// \param RAngleLoc the location of the right angle bracket ('>') that
5424/// terminates the template-id.
5425///
5426/// \param Param the non-type template parameter whose default we are
5427/// substituting into.
5428///
5429/// \param Converted the list of template arguments provided for template
5430/// parameters that precede \p Param in the template parameter list.
5431///
5432/// \returns the substituted template argument, or NULL if an error occurred.
5433static bool SubstDefaultTemplateArgument(
5434 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5435 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5436 ArrayRef<TemplateArgument> SugaredConverted,
5437 ArrayRef<TemplateArgument> CanonicalConverted,
5438 TemplateArgumentLoc &Output) {
5439 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5440 SugaredConverted,
5441 SourceRange(TemplateLoc, RAngleLoc));
5442 if (Inst.isInvalid())
5443 return true;
5444
5445 // Only substitute for the innermost template argument list.
5446 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5447 /*Final=*/true);
5448 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5449 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5450
5451 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5452 EnterExpressionEvaluationContext ConstantEvaluated(
5453 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5454 return SemaRef.SubstTemplateArgument(Input: Param->getDefaultArgument(),
5455 TemplateArgs: TemplateArgLists, Output);
5456}
5457
5458/// Substitute template arguments into the default template argument for
5459/// the given template template parameter.
5460///
5461/// \param SemaRef the semantic analysis object for which we are performing
5462/// the substitution.
5463///
5464/// \param Template the template that we are synthesizing template arguments
5465/// for.
5466///
5467/// \param TemplateLoc the location of the template name that started the
5468/// template-id we are checking.
5469///
5470/// \param RAngleLoc the location of the right angle bracket ('>') that
5471/// terminates the template-id.
5472///
5473/// \param Param the template template parameter whose default we are
5474/// substituting into.
5475///
5476/// \param Converted the list of template arguments provided for template
5477/// parameters that precede \p Param in the template parameter list.
5478///
5479/// \param QualifierLoc Will be set to the nested-name-specifier (with
5480/// source-location information) that precedes the template name.
5481///
5482/// \returns the substituted template argument, or NULL if an error occurred.
5483static TemplateName SubstDefaultTemplateArgument(
5484 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5485 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5486 TemplateTemplateParmDecl *Param,
5487 ArrayRef<TemplateArgument> SugaredConverted,
5488 ArrayRef<TemplateArgument> CanonicalConverted,
5489 NestedNameSpecifierLoc &QualifierLoc) {
5490 Sema::InstantiatingTemplate Inst(
5491 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5492 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5493 if (Inst.isInvalid())
5494 return TemplateName();
5495
5496 // Only substitute for the innermost template argument list.
5497 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5498 /*Final=*/true);
5499 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5500 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5501
5502 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5503
5504 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5505 QualifierLoc = A.getTemplateQualifierLoc();
5506 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5507 Name: A.getArgument().getAsTemplate(),
5508 NameLoc: A.getTemplateNameLoc(), TemplateArgs: TemplateArgLists);
5509}
5510
5511TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5512 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5513 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5514 ArrayRef<TemplateArgument> SugaredConverted,
5515 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5516 HasDefaultArg = false;
5517
5518 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
5519 if (!hasReachableDefaultArgument(D: TypeParm))
5520 return TemplateArgumentLoc();
5521
5522 HasDefaultArg = true;
5523 TemplateArgumentLoc Output;
5524 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5525 RAngleLoc, Param: TypeParm, SugaredConverted,
5526 CanonicalConverted, Output))
5527 return TemplateArgumentLoc();
5528 return Output;
5529 }
5530
5531 if (NonTypeTemplateParmDecl *NonTypeParm
5532 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5533 if (!hasReachableDefaultArgument(D: NonTypeParm))
5534 return TemplateArgumentLoc();
5535
5536 HasDefaultArg = true;
5537 TemplateArgumentLoc Output;
5538 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5539 RAngleLoc, Param: NonTypeParm, SugaredConverted,
5540 CanonicalConverted, Output))
5541 return TemplateArgumentLoc();
5542 return Output;
5543 }
5544
5545 TemplateTemplateParmDecl *TempTempParm
5546 = cast<TemplateTemplateParmDecl>(Val: Param);
5547 if (!hasReachableDefaultArgument(D: TempTempParm))
5548 return TemplateArgumentLoc();
5549
5550 HasDefaultArg = true;
5551 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5552 NestedNameSpecifierLoc QualifierLoc;
5553 TemplateName TName = SubstDefaultTemplateArgument(
5554 SemaRef&: *this, Template, TemplateKWLoc, TemplateLoc: TemplateNameLoc, RAngleLoc, Param: TempTempParm,
5555 SugaredConverted, CanonicalConverted, QualifierLoc);
5556 if (TName.isNull())
5557 return TemplateArgumentLoc();
5558
5559 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5560 QualifierLoc, A.getTemplateNameLoc());
5561}
5562
5563/// Convert a template-argument that we parsed as a type into a template, if
5564/// possible. C++ permits injected-class-names to perform dual service as
5565/// template template arguments and as template type arguments.
5566static TemplateArgumentLoc
5567convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5568 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5569 if (!TagLoc)
5570 return TemplateArgumentLoc();
5571
5572 // If this type was written as an injected-class-name, it can be used as a
5573 // template template argument.
5574 // If this type was written as an injected-class-name, it may have been
5575 // converted to a RecordType during instantiation. If the RecordType is
5576 // *not* wrapped in a TemplateSpecializationType and denotes a class
5577 // template specialization, it must have come from an injected-class-name.
5578
5579 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Ctx: Context);
5580 if (Name.isNull())
5581 return TemplateArgumentLoc();
5582
5583 return TemplateArgumentLoc(Context, Name,
5584 /*TemplateKWLoc=*/SourceLocation(),
5585 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5586}
5587
5588bool Sema::CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &ArgLoc,
5589 NamedDecl *Template,
5590 SourceLocation TemplateLoc,
5591 SourceLocation RAngleLoc,
5592 unsigned ArgumentPackIndex,
5593 CheckTemplateArgumentInfo &CTAI,
5594 CheckTemplateArgumentKind CTAK) {
5595 // Check template type parameters.
5596 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param))
5597 return CheckTemplateTypeArgument(Param: TTP, AL&: ArgLoc, SugaredConverted&: CTAI.SugaredConverted,
5598 CanonicalConverted&: CTAI.CanonicalConverted);
5599
5600 const TemplateArgument &Arg = ArgLoc.getArgument();
5601 // Check non-type template parameters.
5602 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5603 // Do substitution on the type of the non-type template parameter
5604 // with the template arguments we've seen thus far. But if the
5605 // template has a dependent context then we cannot substitute yet.
5606 QualType NTTPType = NTTP->getType();
5607 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5608 NTTPType = NTTP->getExpansionType(I: ArgumentPackIndex);
5609
5610 // C++26 [dcl.type.auto.deduct]p3:
5611 // If the placeholder-type-specifier is of the form type-constraint_opt
5612 // auto, [...] If E is a value synthesized for a constant template
5613 // parameter of type decltype(auto) ([temp.func.order]), the declaration
5614 // is ill-formed.
5615 auto isUndeducedAuto = [](QualType T, bool DecltypeAuto) {
5616 if (T.isNull())
5617 return false;
5618 const AutoType *AT = T->getContainedAutoType();
5619 return AT && AT->isDecltypeAuto() == DecltypeAuto &&
5620 AT->getDeducedType().isNull();
5621 };
5622 if (CTAI.PartialOrdering &&
5623 isUndeducedAuto(NTTPType, /*DecltypeAuto=*/false) &&
5624 isUndeducedAuto(getTypeOfConstantTemplateParameter(Arg),
5625 /*DecltypeAuto=*/true))
5626 return true;
5627
5628 if (NTTPType->isInstantiationDependentType()) {
5629 // Do substitution on the type of the non-type template parameter.
5630 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5631 CTAI.SugaredConverted,
5632 SourceRange(TemplateLoc, RAngleLoc));
5633 if (Inst.isInvalid())
5634 return true;
5635
5636 MultiLevelTemplateArgumentList MLTAL(Template, CTAI.SugaredConverted,
5637 /*Final=*/true);
5638 MLTAL.addOuterRetainedLevels(Num: NTTP->getDepth());
5639 // If the parameter is a pack expansion, expand this slice of the pack.
5640 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5641 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5642 NTTPType = SubstType(T: PET->getPattern(), TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5643 Entity: NTTP->getDeclName());
5644 } else {
5645 NTTPType = SubstType(T: NTTPType, TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5646 Entity: NTTP->getDeclName());
5647 }
5648
5649 // If that worked, check the non-type template parameter type
5650 // for validity.
5651 if (!NTTPType.isNull())
5652 NTTPType = CheckNonTypeTemplateParameterType(T: NTTPType,
5653 Loc: NTTP->getLocation());
5654 if (NTTPType.isNull())
5655 return true;
5656 }
5657
5658 auto checkExpr = [&](Expr *E) -> Expr * {
5659 TemplateArgument SugaredResult, CanonicalResult;
5660 ExprResult Res = CheckTemplateArgument(
5661 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E, SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5662 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5663 // If the current template argument causes an error, give up now.
5664 if (Res.isInvalid())
5665 return nullptr;
5666 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5667 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5668 return Res.get();
5669 };
5670
5671 switch (Arg.getKind()) {
5672 case TemplateArgument::Null:
5673 llvm_unreachable("Should never see a NULL template argument here");
5674
5675 case TemplateArgument::Expression: {
5676 Expr *E = Arg.getAsExpr();
5677 Expr *R = checkExpr(E);
5678 if (!R)
5679 return true;
5680 // If the resulting expression is new, then use it in place of the
5681 // old expression in the template argument.
5682 if (R != E) {
5683 TemplateArgument TA(R, /*IsCanonical=*/false);
5684 ArgLoc = TemplateArgumentLoc(TA, R);
5685 }
5686 break;
5687 }
5688
5689 // As for the converted NTTP kinds, they still might need another
5690 // conversion, as the new corresponding parameter might be different.
5691 // Ideally, we would always perform substitution starting with sugared types
5692 // and never need these, as we would still have expressions. Since these are
5693 // needed so rarely, it's probably a better tradeoff to just convert them
5694 // back to expressions.
5695 case TemplateArgument::Integral:
5696 case TemplateArgument::Declaration:
5697 case TemplateArgument::NullPtr:
5698 case TemplateArgument::StructuralValue: {
5699 // FIXME: StructuralValue is untested here.
5700 ExprResult R =
5701 BuildExpressionFromNonTypeTemplateArgument(Arg, Loc: SourceLocation());
5702 assert(R.isUsable());
5703 if (!checkExpr(R.get()))
5704 return true;
5705 break;
5706 }
5707
5708 case TemplateArgument::Template:
5709 case TemplateArgument::TemplateExpansion:
5710 // We were given a template template argument. It may not be ill-formed;
5711 // see below.
5712 if (DependentTemplateName *DTN = Arg.getAsTemplateOrTemplatePattern()
5713 .getAsDependentTemplateName()) {
5714 // We have a template argument such as \c T::template X, which we
5715 // parsed as a template template argument. However, since we now
5716 // know that we need a non-type template argument, convert this
5717 // template name into an expression.
5718
5719 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5720 ArgLoc.getTemplateNameLoc());
5721
5722 CXXScopeSpec SS;
5723 SS.Adopt(Other: ArgLoc.getTemplateQualifierLoc());
5724 // FIXME: the template-template arg was a DependentTemplateName,
5725 // so it was provided with a template keyword. However, its source
5726 // location is not stored in the template argument structure.
5727 SourceLocation TemplateKWLoc;
5728 ExprResult E = DependentScopeDeclRefExpr::Create(
5729 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5730 TemplateArgs: nullptr);
5731
5732 // If we parsed the template argument as a pack expansion, create a
5733 // pack expansion expression.
5734 if (Arg.getKind() == TemplateArgument::TemplateExpansion) {
5735 E = ActOnPackExpansion(Pattern: E.get(), EllipsisLoc: ArgLoc.getTemplateEllipsisLoc());
5736 if (E.isInvalid())
5737 return true;
5738 }
5739
5740 TemplateArgument SugaredResult, CanonicalResult;
5741 E = CheckTemplateArgument(
5742 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E.get(), SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5743 /*StrictCheck=*/CTAI.PartialOrdering, CTAK: CTAK_Specified);
5744 if (E.isInvalid())
5745 return true;
5746
5747 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5748 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5749 break;
5750 }
5751
5752 // We have a template argument that actually does refer to a class
5753 // template, alias template, or template template parameter, and
5754 // therefore cannot be a non-type template argument.
5755 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_expr)
5756 << ArgLoc.getSourceRange();
5757 NoteTemplateParameterLocation(Decl: *Param);
5758
5759 return true;
5760
5761 case TemplateArgument::Type: {
5762 // We have a non-type template parameter but the template
5763 // argument is a type.
5764
5765 // C++ [temp.arg]p2:
5766 // In a template-argument, an ambiguity between a type-id and
5767 // an expression is resolved to a type-id, regardless of the
5768 // form of the corresponding template-parameter.
5769 //
5770 // We warn specifically about this case, since it can be rather
5771 // confusing for users.
5772 QualType T = Arg.getAsType();
5773 SourceRange SR = ArgLoc.getSourceRange();
5774 if (T->isFunctionType())
5775 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_nontype_ambig) << SR << T;
5776 else
5777 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_expr) << SR;
5778 NoteTemplateParameterLocation(Decl: *Param);
5779 return true;
5780 }
5781
5782 case TemplateArgument::Pack:
5783 llvm_unreachable("Caller must expand template argument packs");
5784 }
5785
5786 return false;
5787 }
5788
5789
5790 // Check template template parameters.
5791 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Val: Param);
5792
5793 TemplateParameterList *Params = TempParm->getTemplateParameters();
5794 if (TempParm->isExpandedParameterPack())
5795 Params = TempParm->getExpansionTemplateParameters(I: ArgumentPackIndex);
5796
5797 // Substitute into the template parameter list of the template
5798 // template parameter, since previously-supplied template arguments
5799 // may appear within the template template parameter.
5800 //
5801 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5802 {
5803 // Set up a template instantiation context.
5804 LocalInstantiationScope Scope(*this);
5805 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5806 CTAI.SugaredConverted,
5807 SourceRange(TemplateLoc, RAngleLoc));
5808 if (Inst.isInvalid())
5809 return true;
5810
5811 Params = SubstTemplateParams(
5812 Params, Owner: CurContext,
5813 TemplateArgs: MultiLevelTemplateArgumentList(Template, CTAI.SugaredConverted,
5814 /*Final=*/true),
5815 /*EvaluateConstraints=*/false);
5816 if (!Params)
5817 return true;
5818 }
5819
5820 // C++1z [temp.local]p1: (DR1004)
5821 // When [the injected-class-name] is used [...] as a template-argument for
5822 // a template template-parameter [...] it refers to the class template
5823 // itself.
5824 if (Arg.getKind() == TemplateArgument::Type) {
5825 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5826 Context, TLoc: ArgLoc.getTypeSourceInfo()->getTypeLoc());
5827 if (!ConvertedArg.getArgument().isNull())
5828 ArgLoc = ConvertedArg;
5829 }
5830
5831 switch (Arg.getKind()) {
5832 case TemplateArgument::Null:
5833 llvm_unreachable("Should never see a NULL template argument here");
5834
5835 case TemplateArgument::Template:
5836 case TemplateArgument::TemplateExpansion:
5837 if (CheckTemplateTemplateArgument(Param: TempParm, Params, Arg&: ArgLoc,
5838 PartialOrdering: CTAI.PartialOrdering,
5839 StrictPackMatch: &CTAI.StrictPackMatch))
5840 return true;
5841
5842 CTAI.SugaredConverted.push_back(Elt: Arg);
5843 CTAI.CanonicalConverted.push_back(
5844 Elt: Context.getCanonicalTemplateArgument(Arg));
5845 break;
5846
5847 case TemplateArgument::Expression:
5848 case TemplateArgument::Type: {
5849 auto Kind = 0;
5850 switch (TempParm->templateParameterKind()) {
5851 case TemplateNameKind::TNK_Var_template:
5852 Kind = 1;
5853 break;
5854 case TemplateNameKind::TNK_Concept_template:
5855 Kind = 2;
5856 break;
5857 default:
5858 break;
5859 }
5860
5861 // We have a template template parameter but the template
5862 // argument does not refer to a template.
5863 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_template)
5864 << Kind << getLangOpts().CPlusPlus11;
5865 return true;
5866 }
5867
5868 case TemplateArgument::Declaration:
5869 case TemplateArgument::Integral:
5870 case TemplateArgument::StructuralValue:
5871 case TemplateArgument::NullPtr:
5872 llvm_unreachable("non-type argument with template template parameter");
5873
5874 case TemplateArgument::Pack:
5875 llvm_unreachable("Caller must expand template argument packs");
5876 }
5877
5878 return false;
5879}
5880
5881/// Diagnose a missing template argument.
5882template <typename TemplateParmDecl>
5883static void diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5884 TemplateDecl *TD,
5885 const TemplateParmDecl *D) {
5886 // Dig out the most recent declaration of the template parameter; there may be
5887 // declarations of the template that are more recent than TD.
5888 D = cast<TemplateParmDecl>(cast<TemplateDecl>(Val: TD->getMostRecentDecl())
5889 ->getTemplateParameters()
5890 ->getParam(D->getIndex()));
5891
5892 // If there's a default argument that's not reachable, diagnose that we're
5893 // missing a module import.
5894 llvm::SmallVector<Module*, 8> Modules;
5895 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, Modules: &Modules)) {
5896 S.diagnoseMissingImport(Loc, cast<NamedDecl>(Val: TD),
5897 D->getDefaultArgumentLoc(), Modules,
5898 Sema::MissingImportKind::DefaultArgument,
5899 /*Recover*/true);
5900 return;
5901 }
5902
5903 // FIXME: If there's a more recent default argument that *is* visible,
5904 // diagnose that it was declared too late.
5905
5906 TemplateParameterList *Params = TD->getTemplateParameters();
5907
5908 S.Diag(Loc, DiagID: diag::err_template_arg_list_different_arity)
5909 << /*not enough args*/0
5910 << (int)S.getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
5911 << TD;
5912 S.NoteTemplateLocation(Decl: *TD, ParamRange: Params->getSourceRange());
5913}
5914
5915/// Check that the given template argument list is well-formed
5916/// for specializing the given template.
5917bool Sema::CheckTemplateArgumentList(
5918 TemplateDecl *Template, SourceLocation TemplateLoc,
5919 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5920 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5921 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5922 return CheckTemplateArgumentList(
5923 Template, Params: GetTemplateParameterList(TD: Template), TemplateLoc, TemplateArgs,
5924 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5925 ConstraintsNotSatisfied);
5926}
5927
5928/// Check that the given template argument list is well-formed
5929/// for specializing the given template.
5930bool Sema::CheckTemplateArgumentList(
5931 TemplateDecl *Template, TemplateParameterList *Params,
5932 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5933 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5934 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5935 bool *ConstraintsNotSatisfied) {
5936
5937 if (ConstraintsNotSatisfied)
5938 *ConstraintsNotSatisfied = false;
5939
5940 // Make a copy of the template arguments for processing. Only make the
5941 // changes at the end when successful in matching the arguments to the
5942 // template.
5943 TemplateArgumentListInfo NewArgs = TemplateArgs;
5944
5945 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5946
5947 // C++23 [temp.arg.general]p1:
5948 // [...] The type and form of each template-argument specified in
5949 // a template-id shall match the type and form specified for the
5950 // corresponding parameter declared by the template in its
5951 // template-parameter-list.
5952 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Val: Template);
5953 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5954 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5955 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5956 LocalInstantiationScope InstScope(*this, true);
5957 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5958 ParamEnd = Params->end(),
5959 Param = ParamBegin;
5960 Param != ParamEnd;
5961 /* increment in loop */) {
5962 if (size_t ParamIdx = Param - ParamBegin;
5963 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5964 // All written arguments should have been consumed by this point.
5965 assert(ArgIdx == NumArgs && "bad default argument deduction");
5966 if (ParamIdx == DefaultArgs.StartPos) {
5967 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5968 // Default arguments from a DeducedTemplateName are already converted.
5969 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5970 CTAI.SugaredConverted.push_back(Elt: DefArg);
5971 CTAI.CanonicalConverted.push_back(
5972 Elt: Context.getCanonicalTemplateArgument(Arg: DefArg));
5973 ++Param;
5974 }
5975 continue;
5976 }
5977 }
5978
5979 // If we have an expanded parameter pack, make sure we don't have too
5980 // many arguments.
5981 if (UnsignedOrNone Expansions = getExpandedPackSize(Param: *Param)) {
5982 if (*Expansions == SugaredArgumentPack.size()) {
5983 // We're done with this parameter pack. Pack up its arguments and add
5984 // them to the list.
5985 CTAI.SugaredConverted.push_back(
5986 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
5987 SugaredArgumentPack.clear();
5988
5989 CTAI.CanonicalConverted.push_back(
5990 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
5991 CanonicalArgumentPack.clear();
5992
5993 // This argument is assigned to the next parameter.
5994 ++Param;
5995 continue;
5996 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5997 // Not enough arguments for this parameter pack.
5998 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
5999 << /*not enough args*/0
6000 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
6001 << Template;
6002 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
6003 return true;
6004 }
6005 }
6006
6007 // Check for builtins producing template packs in this context, we do not
6008 // support them yet.
6009 if (const NonTypeTemplateParmDecl *NTTP =
6010 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param);
6011 NTTP && NTTP->isPackExpansion()) {
6012 auto TL = NTTP->getTypeSourceInfo()
6013 ->getTypeLoc()
6014 .castAs<PackExpansionTypeLoc>();
6015 llvm::SmallVector<UnexpandedParameterPack> Unexpanded;
6016 collectUnexpandedParameterPacks(TL: TL.getPatternLoc(), Unexpanded);
6017 for (const auto &UPP : Unexpanded) {
6018 auto *TST = dyn_cast<const TemplateSpecializationType *>(Val: UPP.first);
6019 if (!TST)
6020 continue;
6021 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
6022 // Expanding a built-in pack in this context is not yet supported.
6023 Diag(Loc: TL.getEllipsisLoc(),
6024 DiagID: diag::err_unsupported_builtin_template_pack_expansion)
6025 << TST->getTemplateName();
6026 return true;
6027 }
6028 }
6029
6030 if (ArgIdx < NumArgs) {
6031 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
6032 bool NonPackParameter =
6033 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(Param: *Param);
6034 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
6035
6036 if (ArgIsExpansion && CTAI.MatchingTTP) {
6037 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
6038 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
6039 ++Param) {
6040 TemplateArgument &Arg = Args[Param - First];
6041 Arg = ArgLoc.getArgument();
6042 if (!(*Param)->isTemplateParameterPack() ||
6043 getExpandedPackSize(Param: *Param))
6044 Arg = Arg.getPackExpansionPattern();
6045 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
6046 SaveAndRestore _1(CTAI.PartialOrdering, false);
6047 SaveAndRestore _2(CTAI.MatchingTTP, true);
6048 if (CheckTemplateArgument(Param: *Param, ArgLoc&: NewArgLoc, Template, TemplateLoc,
6049 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
6050 CTAK: CTAK_Specified))
6051 return true;
6052 Arg = NewArgLoc.getArgument();
6053 CTAI.CanonicalConverted.back().setIsDefaulted(
6054 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg, Param: *Param,
6055 Args: CTAI.CanonicalConverted,
6056 Depth: Params->getDepth()));
6057 }
6058 ArgLoc = TemplateArgumentLoc(
6059 TemplateArgument::CreatePackCopy(Context, Args),
6060 TemplateArgumentLocInfo(Context, ArgLoc.getLocation()));
6061 } else {
6062 SaveAndRestore _1(CTAI.PartialOrdering, false);
6063 if (CheckTemplateArgument(Param: *Param, ArgLoc, Template, TemplateLoc,
6064 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
6065 CTAK: CTAK_Specified))
6066 return true;
6067 CTAI.CanonicalConverted.back().setIsDefaulted(
6068 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg: ArgLoc.getArgument(),
6069 Param: *Param, Args: CTAI.CanonicalConverted,
6070 Depth: Params->getDepth()));
6071 if (ArgIsExpansion && NonPackParameter) {
6072 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6073 // alias template, builtin template, or concept, and it's not part of
6074 // a parameter pack. This can't be canonicalized, so reject it now.
6075 if (isa<TypeAliasTemplateDecl, ConceptDecl, BuiltinTemplateDecl>(
6076 Val: Template)) {
6077 unsigned DiagSelect = isa<ConceptDecl>(Val: Template) ? 1
6078 : isa<BuiltinTemplateDecl>(Val: Template) ? 2
6079 : 0;
6080 Diag(Loc: ArgLoc.getLocation(),
6081 DiagID: diag::err_template_expansion_into_fixed_list)
6082 << DiagSelect << ArgLoc.getSourceRange();
6083 NoteTemplateParameterLocation(Decl: **Param);
6084 return true;
6085 }
6086 }
6087 }
6088
6089 // We're now done with this argument.
6090 ++ArgIdx;
6091
6092 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6093 // Directly convert the remaining arguments, because we don't know what
6094 // parameters they'll match up with.
6095
6096 if (!SugaredArgumentPack.empty()) {
6097 // If we were part way through filling in an expanded parameter pack,
6098 // fall back to just producing individual arguments.
6099 CTAI.SugaredConverted.insert(I: CTAI.SugaredConverted.end(),
6100 From: SugaredArgumentPack.begin(),
6101 To: SugaredArgumentPack.end());
6102 SugaredArgumentPack.clear();
6103
6104 CTAI.CanonicalConverted.insert(I: CTAI.CanonicalConverted.end(),
6105 From: CanonicalArgumentPack.begin(),
6106 To: CanonicalArgumentPack.end());
6107 CanonicalArgumentPack.clear();
6108 }
6109
6110 while (ArgIdx < NumArgs) {
6111 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6112 CTAI.SugaredConverted.push_back(Elt: Arg);
6113 CTAI.CanonicalConverted.push_back(
6114 Elt: Context.getCanonicalTemplateArgument(Arg));
6115 ++ArgIdx;
6116 }
6117
6118 return false;
6119 }
6120
6121 if ((*Param)->isTemplateParameterPack()) {
6122 // The template parameter was a template parameter pack, so take the
6123 // deduced argument and place it on the argument pack. Note that we
6124 // stay on the same template parameter so that we can deduce more
6125 // arguments.
6126 SugaredArgumentPack.push_back(Elt: CTAI.SugaredConverted.pop_back_val());
6127 CanonicalArgumentPack.push_back(Elt: CTAI.CanonicalConverted.pop_back_val());
6128 } else {
6129 // Move to the next template parameter.
6130 ++Param;
6131 }
6132 continue;
6133 }
6134
6135 // If we're checking a partial template argument list, we're done.
6136 if (PartialTemplateArgs) {
6137 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6138 CTAI.SugaredConverted.push_back(
6139 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6140 CTAI.CanonicalConverted.push_back(
6141 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6142 }
6143 return false;
6144 }
6145
6146 // If we have a template parameter pack with no more corresponding
6147 // arguments, just break out now and we'll fill in the argument pack below.
6148 if ((*Param)->isTemplateParameterPack()) {
6149 assert(!getExpandedPackSize(*Param) &&
6150 "Should have dealt with this already");
6151
6152 // A non-expanded parameter pack before the end of the parameter list
6153 // only occurs for an ill-formed template parameter list, unless we've
6154 // got a partial argument list for a function template, so just bail out.
6155 if (Param + 1 != ParamEnd) {
6156 assert(
6157 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6158 "Concept templates must have parameter packs at the end.");
6159 return true;
6160 }
6161
6162 CTAI.SugaredConverted.push_back(
6163 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6164 SugaredArgumentPack.clear();
6165
6166 CTAI.CanonicalConverted.push_back(
6167 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6168 CanonicalArgumentPack.clear();
6169
6170 ++Param;
6171 continue;
6172 }
6173
6174 // Check whether we have a default argument.
6175 bool HasDefaultArg;
6176
6177 // Retrieve the default template argument from the template
6178 // parameter. For each kind of template parameter, we substitute the
6179 // template arguments provided thus far and any "outer" template arguments
6180 // (when the template parameter was part of a nested template) into
6181 // the default argument.
6182 TemplateArgumentLoc Arg = SubstDefaultTemplateArgumentIfAvailable(
6183 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateNameLoc: TemplateLoc, RAngleLoc,
6184 Param: *Param, SugaredConverted: CTAI.SugaredConverted, CanonicalConverted: CTAI.CanonicalConverted, HasDefaultArg);
6185
6186 if (Arg.getArgument().isNull()) {
6187 if (!HasDefaultArg) {
6188 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *Param))
6189 diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: TTP);
6190 else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: *Param))
6191 diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: NTTP);
6192 else
6193 diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template,
6194 D: cast<TemplateTemplateParmDecl>(Val: *Param));
6195 }
6196 return true;
6197 }
6198
6199 // Introduce an instantiation record that describes where we are using
6200 // the default template argument. We're not actually instantiating a
6201 // template here, we just create this object to put a note into the
6202 // context stack.
6203 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6204 CTAI.SugaredConverted,
6205 SourceRange(TemplateLoc, RAngleLoc));
6206 if (Inst.isInvalid())
6207 return true;
6208
6209 SaveAndRestore _1(CTAI.PartialOrdering, false);
6210 SaveAndRestore _2(CTAI.MatchingTTP, false);
6211 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6212 // Check the default template argument.
6213 if (CheckTemplateArgument(Param: *Param, ArgLoc&: Arg, Template, TemplateLoc, RAngleLoc, ArgumentPackIndex: 0,
6214 CTAI, CTAK: CTAK_Specified))
6215 return true;
6216
6217 CTAI.SugaredConverted.back().setIsDefaulted(true);
6218 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6219
6220 // Core issue 150 (assumed resolution): if this is a template template
6221 // parameter, keep track of the default template arguments from the
6222 // template definition.
6223 if (isTemplateTemplateParameter)
6224 NewArgs.addArgument(Loc: Arg);
6225
6226 // Move to the next template parameter and argument.
6227 ++Param;
6228 ++ArgIdx;
6229 }
6230
6231 // If we're performing a partial argument substitution, allow any trailing
6232 // pack expansions; they might be empty. This can happen even if
6233 // PartialTemplateArgs is false (the list of arguments is complete but
6234 // still dependent).
6235 if (CTAI.MatchingTTP ||
6236 (CurrentInstantiationScope &&
6237 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6238 while (ArgIdx < NumArgs &&
6239 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6240 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6241 CTAI.SugaredConverted.push_back(Elt: Arg);
6242 CTAI.CanonicalConverted.push_back(
6243 Elt: Context.getCanonicalTemplateArgument(Arg));
6244 }
6245 }
6246
6247 // If we have any leftover arguments, then there were too many arguments.
6248 // Complain and fail.
6249 if (ArgIdx < NumArgs) {
6250 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
6251 << /*too many args*/1
6252 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
6253 << Template
6254 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6255 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
6256 return true;
6257 }
6258
6259 // No problems found with the new argument list, propagate changes back
6260 // to caller.
6261 if (UpdateArgsWithConversions)
6262 TemplateArgs = std::move(NewArgs);
6263
6264 if (!PartialTemplateArgs) {
6265 // Setup the context/ThisScope for the case where we are needing to
6266 // re-instantiate constraints outside of normal instantiation.
6267 DeclContext *NewContext = Template->getDeclContext();
6268
6269 // If this template is in a template, make sure we extract the templated
6270 // decl.
6271 if (auto *TD = dyn_cast<TemplateDecl>(Val: NewContext))
6272 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6273 auto *RD = dyn_cast<CXXRecordDecl>(Val: NewContext);
6274
6275 Qualifiers ThisQuals;
6276 if (const auto *Method =
6277 dyn_cast_or_null<CXXMethodDecl>(Val: Template->getTemplatedDecl()))
6278 ThisQuals = Method->getMethodQualifiers();
6279
6280 ContextRAII Context(*this, NewContext);
6281 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6282
6283 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6284 D: Template, DC: NewContext, /*Final=*/true, Innermost: CTAI.SugaredConverted,
6285 /*RelativeToPrimary=*/true,
6286 /*Pattern=*/nullptr,
6287 /*ForConceptInstantiation=*/ForConstraintInstantiation: true);
6288 if (!isa<ConceptDecl>(Val: Template) &&
6289 EnsureTemplateArgumentListConstraints(
6290 Template, TemplateArgs: MLTAL,
6291 TemplateIDRange: SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6292 if (ConstraintsNotSatisfied)
6293 *ConstraintsNotSatisfied = true;
6294 return true;
6295 }
6296 }
6297
6298 return false;
6299}
6300
6301namespace {
6302 class UnnamedLocalNoLinkageFinder
6303 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6304 {
6305 Sema &S;
6306 SourceRange SR;
6307
6308 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6309
6310 public:
6311 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6312
6313 bool Visit(QualType T) {
6314 return T.isNull() ? false : inherited::Visit(T: T.getTypePtr());
6315 }
6316
6317#define TYPE(Class, Parent) \
6318 bool Visit##Class##Type(const Class##Type *);
6319#define ABSTRACT_TYPE(Class, Parent) \
6320 bool Visit##Class##Type(const Class##Type *) { return false; }
6321#define NON_CANONICAL_TYPE(Class, Parent) \
6322 bool Visit##Class##Type(const Class##Type *) { return false; }
6323#include "clang/AST/TypeNodes.inc"
6324
6325 bool VisitTagDecl(const TagDecl *Tag);
6326 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6327 };
6328} // end anonymous namespace
6329
6330bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6331 return false;
6332}
6333
6334bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6335 return Visit(T: T->getElementType());
6336}
6337
6338bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6339 return Visit(T: T->getPointeeType());
6340}
6341
6342bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6343 const BlockPointerType* T) {
6344 return Visit(T: T->getPointeeType());
6345}
6346
6347bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6348 const LValueReferenceType* T) {
6349 return Visit(T: T->getPointeeType());
6350}
6351
6352bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6353 const RValueReferenceType* T) {
6354 return Visit(T: T->getPointeeType());
6355}
6356
6357bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6358 const MemberPointerType *T) {
6359 if (Visit(T: T->getPointeeType()))
6360 return true;
6361 if (auto *RD = T->getMostRecentCXXRecordDecl())
6362 return VisitTagDecl(Tag: RD);
6363 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6364}
6365
6366bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6367 const ConstantArrayType* T) {
6368 return Visit(T: T->getElementType());
6369}
6370
6371bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6372 const IncompleteArrayType* T) {
6373 return Visit(T: T->getElementType());
6374}
6375
6376bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6377 const VariableArrayType* T) {
6378 return Visit(T: T->getElementType());
6379}
6380
6381bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6382 const DependentSizedArrayType* T) {
6383 return Visit(T: T->getElementType());
6384}
6385
6386bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6387 const DependentSizedExtVectorType* T) {
6388 return Visit(T: T->getElementType());
6389}
6390
6391bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6392 const DependentSizedMatrixType *T) {
6393 return Visit(T: T->getElementType());
6394}
6395
6396bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6397 const DependentAddressSpaceType *T) {
6398 return Visit(T: T->getPointeeType());
6399}
6400
6401bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6402 return Visit(T: T->getElementType());
6403}
6404
6405bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6406 const DependentVectorType *T) {
6407 return Visit(T: T->getElementType());
6408}
6409
6410bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6411 return Visit(T: T->getElementType());
6412}
6413
6414bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6415 const ConstantMatrixType *T) {
6416 return Visit(T: T->getElementType());
6417}
6418
6419bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6420 const FunctionProtoType* T) {
6421 for (const auto &A : T->param_types()) {
6422 if (Visit(T: A))
6423 return true;
6424 }
6425
6426 return Visit(T: T->getReturnType());
6427}
6428
6429bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6430 const FunctionNoProtoType* T) {
6431 return Visit(T: T->getReturnType());
6432}
6433
6434bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6435 const UnresolvedUsingType*) {
6436 return false;
6437}
6438
6439bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6440 return false;
6441}
6442
6443bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6444 return Visit(T: T->getUnmodifiedType());
6445}
6446
6447bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6448 return false;
6449}
6450
6451bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6452 const PackIndexingType *) {
6453 return false;
6454}
6455
6456bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6457 const UnaryTransformType*) {
6458 return false;
6459}
6460
6461bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6462 return Visit(T: T->getDeducedType());
6463}
6464
6465bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6466 const DeducedTemplateSpecializationType *T) {
6467 return Visit(T: T->getDeducedType());
6468}
6469
6470bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6471 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6472}
6473
6474bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6475 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6476}
6477
6478bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6479 const TemplateTypeParmType*) {
6480 return false;
6481}
6482
6483bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6484 const SubstTemplateTypeParmPackType *) {
6485 return false;
6486}
6487
6488bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6489 const SubstBuiltinTemplatePackType *) {
6490 return false;
6491}
6492
6493bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6494 const TemplateSpecializationType*) {
6495 return false;
6496}
6497
6498bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6499 const InjectedClassNameType* T) {
6500 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6501}
6502
6503bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6504 const DependentNameType* T) {
6505 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6506}
6507
6508bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6509 const PackExpansionType* T) {
6510 return Visit(T: T->getPattern());
6511}
6512
6513bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6514 return false;
6515}
6516
6517bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6518 const ObjCInterfaceType *) {
6519 return false;
6520}
6521
6522bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6523 const ObjCObjectPointerType *) {
6524 return false;
6525}
6526
6527bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6528 return Visit(T: T->getValueType());
6529}
6530
6531bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6532 const OverflowBehaviorType *T) {
6533 return Visit(T: T->getUnderlyingType());
6534}
6535
6536bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6537 return false;
6538}
6539
6540bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6541 return false;
6542}
6543
6544bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6545 const ArrayParameterType *T) {
6546 return VisitConstantArrayType(T);
6547}
6548
6549bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6550 const DependentBitIntType *T) {
6551 return false;
6552}
6553
6554bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6555 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6556 S.Diag(Loc: SR.getBegin(), DiagID: S.getLangOpts().CPlusPlus11
6557 ? diag::warn_cxx98_compat_template_arg_local_type
6558 : diag::ext_template_arg_local_type)
6559 << S.Context.getCanonicalTagType(TD: Tag) << SR;
6560 return true;
6561 }
6562
6563 if (!Tag->hasNameForLinkage()) {
6564 S.Diag(Loc: SR.getBegin(),
6565 DiagID: S.getLangOpts().CPlusPlus11 ?
6566 diag::warn_cxx98_compat_template_arg_unnamed_type :
6567 diag::ext_template_arg_unnamed_type) << SR;
6568 S.Diag(Loc: Tag->getLocation(), DiagID: diag::note_template_unnamed_type_here);
6569 return true;
6570 }
6571
6572 return false;
6573}
6574
6575bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6576 NestedNameSpecifier NNS) {
6577 switch (NNS.getKind()) {
6578 case NestedNameSpecifier::Kind::Null:
6579 case NestedNameSpecifier::Kind::Namespace:
6580 case NestedNameSpecifier::Kind::Global:
6581 case NestedNameSpecifier::Kind::MicrosoftSuper:
6582 return false;
6583 case NestedNameSpecifier::Kind::Type:
6584 return Visit(T: QualType(NNS.getAsType(), 0));
6585 }
6586 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6587}
6588
6589bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6590 const HLSLAttributedResourceType *T) {
6591 if (T->hasContainedType() && Visit(T: T->getContainedType()))
6592 return true;
6593 return Visit(T: T->getWrappedType());
6594}
6595
6596bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6597 const HLSLInlineSpirvType *T) {
6598 for (auto &Operand : T->getOperands())
6599 if (Operand.isConstant() && Operand.isLiteral())
6600 if (Visit(T: Operand.getResultType()))
6601 return true;
6602 return false;
6603}
6604
6605bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6606 assert(ArgInfo && "invalid TypeSourceInfo");
6607 QualType Arg = ArgInfo->getType();
6608 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6609 QualType CanonArg = Context.getCanonicalType(T: Arg);
6610
6611 if (CanonArg->isVariablyModifiedType()) {
6612 return Diag(Loc: SR.getBegin(), DiagID: diag::err_variably_modified_template_arg) << Arg;
6613 } else if (Context.hasSameUnqualifiedType(T1: Arg, T2: Context.OverloadTy)) {
6614 return Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_overload_type) << SR;
6615 }
6616
6617 // C++03 [temp.arg.type]p2:
6618 // A local type, a type with no linkage, an unnamed type or a type
6619 // compounded from any of these types shall not be used as a
6620 // template-argument for a template type-parameter.
6621 //
6622 // C++11 allows these, and even in C++03 we allow them as an extension with
6623 // a warning.
6624 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6625 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6626 (void)Finder.Visit(T: CanonArg);
6627 }
6628
6629 return false;
6630}
6631
6632enum NullPointerValueKind {
6633 NPV_NotNullPointer,
6634 NPV_NullPointer,
6635 NPV_Error
6636};
6637
6638/// Determine whether the given template argument is a null pointer
6639/// value of the appropriate type.
6640static NullPointerValueKind
6641isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param,
6642 QualType ParamType, Expr *Arg,
6643 Decl *Entity = nullptr) {
6644 if (Arg->isValueDependent() || Arg->isTypeDependent())
6645 return NPV_NotNullPointer;
6646
6647 // dllimport'd entities aren't constant but are available inside of template
6648 // arguments.
6649 if (Entity && Entity->hasAttr<DLLImportAttr>())
6650 return NPV_NotNullPointer;
6651
6652 if (!S.isCompleteType(Loc: Arg->getExprLoc(), T: ParamType))
6653 llvm_unreachable(
6654 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6655
6656 if (!S.getLangOpts().CPlusPlus11)
6657 return NPV_NotNullPointer;
6658
6659 // Determine whether we have a constant expression.
6660 ExprResult ArgRV = S.DefaultFunctionArrayConversion(E: Arg);
6661 if (ArgRV.isInvalid())
6662 return NPV_Error;
6663 Arg = ArgRV.get();
6664
6665 Expr::EvalResult EvalResult;
6666 SmallVector<PartialDiagnosticAt, 8> Notes;
6667 EvalResult.Diag = &Notes;
6668 if (!Arg->EvaluateAsRValue(Result&: EvalResult, Ctx: S.Context) ||
6669 EvalResult.HasSideEffects) {
6670 SourceLocation DiagLoc = Arg->getExprLoc();
6671
6672 // If our only note is the usual "invalid subexpression" note, just point
6673 // the caret at its location rather than producing an essentially
6674 // redundant note.
6675 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6676 diag::note_invalid_subexpr_in_const_expr) {
6677 DiagLoc = Notes[0].first;
6678 Notes.clear();
6679 }
6680
6681 S.Diag(Loc: DiagLoc, DiagID: diag::err_template_arg_not_address_constant)
6682 << Arg->getType() << Arg->getSourceRange();
6683 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6684 S.Diag(Loc: Notes[I].first, PD: Notes[I].second);
6685
6686 S.NoteTemplateParameterLocation(Decl: *Param);
6687 return NPV_Error;
6688 }
6689
6690 // C++11 [temp.arg.nontype]p1:
6691 // - an address constant expression of type std::nullptr_t
6692 if (Arg->getType()->isNullPtrType())
6693 return NPV_NullPointer;
6694
6695 // - a constant expression that evaluates to a null pointer value (4.10); or
6696 // - a constant expression that evaluates to a null member pointer value
6697 // (4.11); or
6698 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6699 (EvalResult.Val.isMemberPointer() &&
6700 !EvalResult.Val.getMemberPointerDecl())) {
6701 // If our expression has an appropriate type, we've succeeded.
6702 bool ObjCLifetimeConversion;
6703 if (S.Context.hasSameUnqualifiedType(T1: Arg->getType(), T2: ParamType) ||
6704 S.IsQualificationConversion(FromType: Arg->getType(), ToType: ParamType, CStyle: false,
6705 ObjCLifetimeConversion))
6706 return NPV_NullPointer;
6707
6708 // The types didn't match, but we know we got a null pointer; complain,
6709 // then recover as if the types were correct.
6710 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_wrongtype_null_constant)
6711 << Arg->getType() << ParamType << Arg->getSourceRange();
6712 S.NoteTemplateParameterLocation(Decl: *Param);
6713 return NPV_NullPointer;
6714 }
6715
6716 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6717 // We found a pointer that isn't null, but doesn't refer to an object.
6718 // We could just return NPV_NotNullPointer, but we can print a better
6719 // message with the information we have here.
6720 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_invalid)
6721 << EvalResult.Val.getAsString(Ctx: S.Context, Ty: ParamType);
6722 S.NoteTemplateParameterLocation(Decl: *Param);
6723 return NPV_Error;
6724 }
6725
6726 // If we don't have a null pointer value, but we do have a NULL pointer
6727 // constant, suggest a cast to the appropriate type.
6728 if (Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_NeverValueDependent)) {
6729 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6730 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_untyped_null_constant)
6731 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code)
6732 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: Arg->getEndLoc()),
6733 Code: ")");
6734 S.NoteTemplateParameterLocation(Decl: *Param);
6735 return NPV_NullPointer;
6736 }
6737
6738 // FIXME: If we ever want to support general, address-constant expressions
6739 // as non-type template arguments, we should return the ExprResult here to
6740 // be interpreted by the caller.
6741 return NPV_NotNullPointer;
6742}
6743
6744/// Checks whether the given template argument is compatible with its
6745/// template parameter.
6746static bool
6747CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param,
6748 QualType ParamType, Expr *ArgIn,
6749 Expr *Arg, QualType ArgType) {
6750 bool ObjCLifetimeConversion;
6751 if (ParamType->isPointerType() &&
6752 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6753 S.IsQualificationConversion(FromType: ArgType, ToType: ParamType, CStyle: false,
6754 ObjCLifetimeConversion)) {
6755 // For pointer-to-object types, qualification conversions are
6756 // permitted.
6757 } else {
6758 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6759 if (!ParamRef->getPointeeType()->isFunctionType()) {
6760 // C++ [temp.arg.nontype]p5b3:
6761 // For a non-type template-parameter of type reference to
6762 // object, no conversions apply. The type referred to by the
6763 // reference may be more cv-qualified than the (otherwise
6764 // identical) type of the template- argument. The
6765 // template-parameter is bound directly to the
6766 // template-argument, which shall be an lvalue.
6767
6768 // FIXME: Other qualifiers?
6769 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6770 unsigned ArgQuals = ArgType.getCVRQualifiers();
6771
6772 if ((ParamQuals | ArgQuals) != ParamQuals) {
6773 S.Diag(Loc: Arg->getBeginLoc(),
6774 DiagID: diag::err_template_arg_ref_bind_ignores_quals)
6775 << ParamType << Arg->getType() << Arg->getSourceRange();
6776 S.NoteTemplateParameterLocation(Decl: *Param);
6777 return true;
6778 }
6779 }
6780 }
6781
6782 // At this point, the template argument refers to an object or
6783 // function with external linkage. We now need to check whether the
6784 // argument and parameter types are compatible.
6785 if (!S.Context.hasSameUnqualifiedType(T1: ArgType,
6786 T2: ParamType.getNonReferenceType())) {
6787 // We can't perform this conversion or binding.
6788 if (ParamType->isReferenceType())
6789 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_no_ref_bind)
6790 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6791 else
6792 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
6793 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6794 S.NoteTemplateParameterLocation(Decl: *Param);
6795 return true;
6796 }
6797 }
6798
6799 return false;
6800}
6801
6802/// Checks whether the given template argument is the address
6803/// of an object or function according to C++ [temp.arg.nontype]p1.
6804static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6805 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6806 bool IsSpecified, TemplateArgument &SugaredConverted,
6807 TemplateArgument &CanonicalConverted) {
6808 Expr *Arg = ArgIn;
6809 QualType ArgType = Arg->getType();
6810
6811 bool AddressTaken = false;
6812 SourceLocation AddrOpLoc;
6813 if (S.getLangOpts().MicrosoftExt) {
6814 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6815 // dereference and address-of operators.
6816 Arg = Arg->IgnoreParenCasts();
6817
6818 bool ExtWarnMSTemplateArg = false;
6819 UnaryOperatorKind FirstOpKind;
6820 SourceLocation FirstOpLoc;
6821 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6822 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6823 if (UnOpKind == UO_Deref)
6824 ExtWarnMSTemplateArg = true;
6825 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6826 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6827 if (!AddrOpLoc.isValid()) {
6828 FirstOpKind = UnOpKind;
6829 FirstOpLoc = UnOp->getOperatorLoc();
6830 }
6831 } else
6832 break;
6833 }
6834 if (FirstOpLoc.isValid()) {
6835 if (ExtWarnMSTemplateArg)
6836 S.Diag(Loc: ArgIn->getBeginLoc(), DiagID: diag::ext_ms_deref_template_argument)
6837 << ArgIn->getSourceRange();
6838
6839 if (FirstOpKind == UO_AddrOf)
6840 AddressTaken = true;
6841 else if (Arg->getType()->isPointerType()) {
6842 // We cannot let pointers get dereferenced here, that is obviously not a
6843 // constant expression.
6844 assert(FirstOpKind == UO_Deref);
6845 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6846 << Arg->getSourceRange();
6847 }
6848 }
6849 } else {
6850 // See through any implicit casts we added to fix the type.
6851 // Also ignore parentheses for deduced template arguments.
6852 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6853
6854 // C++ [temp.arg.nontype]p1:
6855 //
6856 // A template-argument for a non-type, non-template
6857 // template-parameter shall be one of: [...]
6858 //
6859 // -- the address of an object or function with external
6860 // linkage, including function templates and function
6861 // template-ids but excluding non-static class members,
6862 // expressed as & id-expression where the & is optional if
6863 // the name refers to a function or array, or if the
6864 // corresponding template-parameter is a reference; or
6865
6866 // In C++98/03 mode, give an extension warning on any extra parentheses.
6867 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6868 if (IsSpecified) {
6869 bool ExtraParens = false;
6870 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6871 if (!ExtraParens) {
6872 S.DiagCompat(Loc: Arg->getBeginLoc(),
6873 CompatDiagId: diag_compat::template_arg_extra_parens)
6874 << Arg->getSourceRange();
6875 ExtraParens = true;
6876 }
6877
6878 Arg = Parens->getSubExpr();
6879 }
6880 }
6881
6882 while (SubstNonTypeTemplateParmExpr *subst =
6883 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6884 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6885
6886 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6887 if (UnOp->getOpcode() == UO_AddrOf) {
6888 Arg = UnOp->getSubExpr();
6889 AddressTaken = true;
6890 AddrOpLoc = UnOp->getOperatorLoc();
6891 }
6892 }
6893
6894 while (SubstNonTypeTemplateParmExpr *subst =
6895 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6896 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6897 }
6898
6899 ValueDecl *Entity = nullptr;
6900 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg))
6901 Entity = DRE->getDecl();
6902 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Val: Arg))
6903 Entity = CUE->getGuidDecl();
6904
6905 // If our parameter has pointer type, check for a null template value.
6906 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6907 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ArgIn,
6908 Entity)) {
6909 case NPV_NullPointer:
6910 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
6911 SugaredConverted = TemplateArgument(ParamType,
6912 /*isNullPtr=*/true);
6913 CanonicalConverted =
6914 TemplateArgument(S.Context.getCanonicalType(T: ParamType),
6915 /*isNullPtr=*/true);
6916 return false;
6917
6918 case NPV_Error:
6919 return true;
6920
6921 case NPV_NotNullPointer:
6922 break;
6923 }
6924 }
6925
6926 // Stop checking the precise nature of the argument if it is value dependent,
6927 // it should be checked when instantiated.
6928 if (Arg->isValueDependent()) {
6929 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6930 CanonicalConverted =
6931 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6932 return false;
6933 }
6934
6935 if (!Entity) {
6936 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6937 << Arg->getSourceRange();
6938 S.NoteTemplateParameterLocation(Decl: *Param);
6939 return true;
6940 }
6941
6942 // Cannot refer to non-static data members
6943 if (isa<FieldDecl>(Val: Entity) || isa<IndirectFieldDecl>(Val: Entity)) {
6944 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_field)
6945 << Entity << Arg->getSourceRange();
6946 S.NoteTemplateParameterLocation(Decl: *Param);
6947 return true;
6948 }
6949
6950 // Cannot refer to non-static member functions
6951 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Entity)) {
6952 if (!Method->isStatic()) {
6953 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_method)
6954 << Method << Arg->getSourceRange();
6955 S.NoteTemplateParameterLocation(Decl: *Param);
6956 return true;
6957 }
6958 }
6959
6960 FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Entity);
6961 VarDecl *Var = dyn_cast<VarDecl>(Val: Entity);
6962 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Val: Entity);
6963
6964 // A non-type template argument must refer to an object or function.
6965 if (!Func && !Var && !Guid) {
6966 // We found something, but we don't know specifically what it is.
6967 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_object_or_func)
6968 << Arg->getSourceRange();
6969 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_refers_here);
6970 return true;
6971 }
6972
6973 // Address / reference template args must have external linkage in C++98.
6974 if (Entity->getFormalLinkage() == Linkage::Internal) {
6975 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_object_internal)
6976 << !Func << Entity << Arg->getSourceRange();
6977 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6978 << !Func;
6979 } else if (!Entity->hasLinkage()) {
6980 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_object_no_linkage)
6981 << !Func << Entity << Arg->getSourceRange();
6982 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6983 << !Func;
6984 return true;
6985 }
6986
6987 if (Var) {
6988 // A value of reference type is not an object.
6989 if (Var->getType()->isReferenceType()) {
6990 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_reference_var)
6991 << Var->getType() << Arg->getSourceRange();
6992 S.NoteTemplateParameterLocation(Decl: *Param);
6993 return true;
6994 }
6995
6996 // A template argument must have static storage duration.
6997 if (Var->getTLSKind()) {
6998 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_thread_local)
6999 << Arg->getSourceRange();
7000 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_template_arg_refers_here);
7001 return true;
7002 }
7003 }
7004
7005 if (AddressTaken && ParamType->isReferenceType()) {
7006 // If we originally had an address-of operator, but the
7007 // parameter has reference type, complain and (if things look
7008 // like they will work) drop the address-of operator.
7009 if (!S.Context.hasSameUnqualifiedType(T1: Entity->getType(),
7010 T2: ParamType.getNonReferenceType())) {
7011 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
7012 << ParamType;
7013 S.NoteTemplateParameterLocation(Decl: *Param);
7014 return true;
7015 }
7016
7017 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
7018 << ParamType
7019 << FixItHint::CreateRemoval(RemoveRange: AddrOpLoc);
7020 S.NoteTemplateParameterLocation(Decl: *Param);
7021
7022 ArgType = Entity->getType();
7023 }
7024
7025 // If the template parameter has pointer type, either we must have taken the
7026 // address or the argument must decay to a pointer.
7027 if (!AddressTaken && ParamType->isPointerType()) {
7028 if (Func) {
7029 // Function-to-pointer decay.
7030 ArgType = S.Context.getPointerType(T: Func->getType());
7031 } else if (Entity->getType()->isArrayType()) {
7032 // Array-to-pointer decay.
7033 ArgType = S.Context.getArrayDecayedType(T: Entity->getType());
7034 } else {
7035 // If the template parameter has pointer type but the address of
7036 // this object was not taken, complain and (possibly) recover by
7037 // taking the address of the entity.
7038 ArgType = S.Context.getPointerType(T: Entity->getType());
7039 if (!S.Context.hasSameUnqualifiedType(T1: ArgType, T2: ParamType)) {
7040 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
7041 << ParamType;
7042 S.NoteTemplateParameterLocation(Decl: *Param);
7043 return true;
7044 }
7045
7046 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
7047 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code: "&");
7048
7049 S.NoteTemplateParameterLocation(Decl: *Param);
7050 }
7051 }
7052
7053 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7054 Arg, ArgType))
7055 return true;
7056
7057 // Create the template argument.
7058 SugaredConverted = TemplateArgument(Entity, ParamType);
7059 CanonicalConverted =
7060 TemplateArgument(cast<ValueDecl>(Val: Entity->getCanonicalDecl()),
7061 S.Context.getCanonicalType(T: ParamType));
7062 S.MarkAnyDeclReferenced(Loc: Arg->getBeginLoc(), D: Entity, MightBeOdrUse: false);
7063 return false;
7064}
7065
7066/// Checks whether the given template argument is a pointer to
7067/// member constant according to C++ [temp.arg.nontype]p1.
7068static bool CheckTemplateArgumentPointerToMember(
7069 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7070 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7071 bool Invalid = false;
7072
7073 Expr *Arg = ResultArg;
7074 bool ObjCLifetimeConversion;
7075
7076 // C++ [temp.arg.nontype]p1:
7077 //
7078 // A template-argument for a non-type, non-template
7079 // template-parameter shall be one of: [...]
7080 //
7081 // -- a pointer to member expressed as described in 5.3.1.
7082 DeclRefExpr *DRE = nullptr;
7083
7084 // In C++98/03 mode, give an extension warning on any extra parentheses.
7085 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7086 bool ExtraParens = false;
7087 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
7088 if (!Invalid && !ExtraParens) {
7089 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
7090 << Arg->getSourceRange();
7091 ExtraParens = true;
7092 }
7093
7094 Arg = Parens->getSubExpr();
7095 }
7096
7097 while (SubstNonTypeTemplateParmExpr *subst =
7098 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
7099 Arg = subst->getReplacement()->IgnoreImpCasts();
7100
7101 // A pointer-to-member constant written &Class::member.
7102 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
7103 if (UnOp->getOpcode() == UO_AddrOf) {
7104 DRE = dyn_cast<DeclRefExpr>(Val: UnOp->getSubExpr());
7105 if (DRE && !DRE->getQualifier())
7106 DRE = nullptr;
7107 }
7108 }
7109 // A constant of pointer-to-member type.
7110 else if ((DRE = dyn_cast<DeclRefExpr>(Val: Arg))) {
7111 ValueDecl *VD = DRE->getDecl();
7112 if (VD->getType()->isMemberPointerType()) {
7113 if (isa<NonTypeTemplateParmDecl>(Val: VD)) {
7114 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7115 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7116 CanonicalConverted =
7117 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7118 } else {
7119 SugaredConverted = TemplateArgument(VD, ParamType);
7120 CanonicalConverted =
7121 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7122 S.Context.getCanonicalType(T: ParamType));
7123 }
7124 return Invalid;
7125 }
7126 }
7127
7128 DRE = nullptr;
7129 }
7130
7131 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7132
7133 // Check for a null pointer value.
7134 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ResultArg,
7135 Entity)) {
7136 case NPV_Error:
7137 return true;
7138 case NPV_NullPointer:
7139 S.Diag(Loc: ResultArg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7140 SugaredConverted = TemplateArgument(ParamType,
7141 /*isNullPtr*/ true);
7142 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(T: ParamType),
7143 /*isNullPtr*/ true);
7144 return false;
7145 case NPV_NotNullPointer:
7146 break;
7147 }
7148
7149 if (S.IsQualificationConversion(FromType: ResultArg->getType(),
7150 ToType: ParamType.getNonReferenceType(), CStyle: false,
7151 ObjCLifetimeConversion)) {
7152 ResultArg = S.ImpCastExprToType(E: ResultArg, Type: ParamType, CK: CK_NoOp,
7153 VK: ResultArg->getValueKind())
7154 .get();
7155 } else if (!S.Context.hasSameUnqualifiedType(
7156 T1: ResultArg->getType(), T2: ParamType.getNonReferenceType())) {
7157 // We can't perform this conversion.
7158 S.Diag(Loc: ResultArg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
7159 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7160 S.NoteTemplateParameterLocation(Decl: *Param);
7161 return true;
7162 }
7163
7164 if (!DRE)
7165 return S.Diag(Loc: Arg->getBeginLoc(),
7166 DiagID: diag::err_template_arg_not_pointer_to_member_form)
7167 << Arg->getSourceRange();
7168
7169 if (isa<FieldDecl>(Val: DRE->getDecl()) ||
7170 isa<IndirectFieldDecl>(Val: DRE->getDecl()) ||
7171 isa<CXXMethodDecl>(Val: DRE->getDecl())) {
7172 assert((isa<FieldDecl>(DRE->getDecl()) ||
7173 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7174 cast<CXXMethodDecl>(DRE->getDecl())
7175 ->isImplicitObjectMemberFunction()) &&
7176 "Only non-static member pointers can make it here");
7177
7178 // Okay: this is the address of a non-static member, and therefore
7179 // a member pointer constant.
7180 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7181 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7182 CanonicalConverted =
7183 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7184 } else {
7185 ValueDecl *D = DRE->getDecl();
7186 SugaredConverted = TemplateArgument(D, ParamType);
7187 CanonicalConverted =
7188 TemplateArgument(cast<ValueDecl>(Val: D->getCanonicalDecl()),
7189 S.Context.getCanonicalType(T: ParamType));
7190 }
7191 return Invalid;
7192 }
7193
7194 // We found something else, but we don't know specifically what it is.
7195 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_pointer_to_member_form)
7196 << Arg->getSourceRange();
7197 S.Diag(Loc: DRE->getDecl()->getLocation(), DiagID: diag::note_template_arg_refers_here);
7198 return true;
7199}
7200
7201/// Check a template argument against its corresponding
7202/// non-type template parameter.
7203///
7204/// This routine implements the semantics of C++ [temp.arg.nontype].
7205/// If an error occurred, it returns ExprError(); otherwise, it
7206/// returns the converted template argument. \p ParamType is the
7207/// type of the non-type template parameter after it has been instantiated.
7208ExprResult Sema::CheckTemplateArgument(NamedDecl *Param, QualType ParamType,
7209 Expr *Arg,
7210 TemplateArgument &SugaredConverted,
7211 TemplateArgument &CanonicalConverted,
7212 bool StrictCheck,
7213 CheckTemplateArgumentKind CTAK) {
7214 SourceLocation StartLoc = Arg->getBeginLoc();
7215 auto *ArgPE = dyn_cast<PackExpansionExpr>(Val: Arg);
7216 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7217 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7218 DeductionArg = NewDeductionArg;
7219 if (ArgPE) {
7220 // Recreate a pack expansion if we unwrapped one.
7221 Arg = new (Context) PackExpansionExpr(
7222 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7223 } else {
7224 Arg = DeductionArg;
7225 }
7226 };
7227
7228 // If the parameter type somehow involves auto, deduce the type now.
7229 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7230 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7231 if (IsDeduced) {
7232 // When checking a deduced template argument, deduce from its type even if
7233 // the type is dependent, in order to check the types of non-type template
7234 // arguments line up properly in partial ordering.
7235 TypeSourceInfo *TSI =
7236 Context.getTrivialTypeSourceInfo(T: ParamType, Loc: Param->getLocation());
7237 if (isa<DeducedTemplateSpecializationType>(Val: DeducedT)) {
7238 InitializedEntity Entity =
7239 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7240 InitializationKind Kind = InitializationKind::CreateForInit(
7241 Loc: DeductionArg->getBeginLoc(), /*DirectInit*/false, Init: DeductionArg);
7242 Expr *Inits[1] = {DeductionArg};
7243 ParamType =
7244 DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind, Init: Inits);
7245 if (ParamType.isNull())
7246 return ExprError();
7247 } else {
7248 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7249 Param->getTemplateDepth() + 1);
7250 ParamType = QualType();
7251 TemplateDeductionResult Result =
7252 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeductionArg, Result&: ParamType, Info,
7253 /*DependentDeduction=*/true,
7254 // We do not check constraints right now because the
7255 // immediately-declared constraint of the auto type is
7256 // also an associated constraint, and will be checked
7257 // along with the other associated constraints after
7258 // checking the template argument list.
7259 /*IgnoreConstraints=*/true);
7260 if (Result != TemplateDeductionResult::Success) {
7261 ParamType = TSI->getType();
7262 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7263 if (Result == TemplateDeductionResult::AlreadyDiagnosed)
7264 return ExprError();
7265 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param))
7266 Diag(Loc: Arg->getExprLoc(),
7267 DiagID: diag::err_non_type_template_parm_type_deduction_failure)
7268 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7269 << Arg->getSourceRange();
7270 NoteTemplateParameterLocation(Decl: *Param);
7271 return ExprError();
7272 }
7273 ParamType = SubstAutoTypeDependent(TypeWithAuto: ParamType);
7274 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7275 }
7276 }
7277 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7278 // an error. The error message normally references the parameter
7279 // declaration, but here we'll pass the argument location because that's
7280 // where the parameter type is deduced.
7281 ParamType = CheckNonTypeTemplateParameterType(T: ParamType, Loc: Arg->getExprLoc());
7282 if (ParamType.isNull()) {
7283 NoteTemplateParameterLocation(Decl: *Param);
7284 return ExprError();
7285 }
7286 }
7287
7288 // We should have already dropped all cv-qualifiers by now.
7289 assert(!ParamType.hasQualifiers() &&
7290 "non-type template parameter type cannot be qualified");
7291
7292 // If either the parameter has a dependent type or the argument is
7293 // type-dependent, there's nothing we can check now.
7294 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7295 // Force the argument to the type of the parameter to maintain invariants.
7296 if (!IsDeduced) {
7297 ExprResult E = ImpCastExprToType(
7298 E: DeductionArg, Type: ParamType.getNonLValueExprType(Context), CK: CK_Dependent,
7299 VK: ParamType->isLValueReferenceType() ? VK_LValue
7300 : ParamType->isRValueReferenceType() ? VK_XValue
7301 : VK_PRValue);
7302 if (E.isInvalid())
7303 return ExprError();
7304 setDeductionArg(E.get());
7305 }
7306 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7307 CanonicalConverted = TemplateArgument(
7308 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7309 return Arg;
7310 }
7311
7312 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7313 if (CTAK == CTAK_Deduced && !StrictCheck &&
7314 (ParamType->isReferenceType()
7315 ? !Context.hasSameType(T1: ParamType.getNonReferenceType(),
7316 T2: DeductionArg->getType())
7317 : !Context.hasSameUnqualifiedType(T1: ParamType,
7318 T2: DeductionArg->getType()))) {
7319 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7320 // we should actually be checking the type of the template argument in P,
7321 // not the type of the template argument deduced from A, against the
7322 // template parameter type.
7323 Diag(Loc: StartLoc, DiagID: diag::err_deduced_non_type_template_arg_type_mismatch)
7324 << Arg->getType() << ParamType.getUnqualifiedType();
7325 NoteTemplateParameterLocation(Decl: *Param);
7326 return ExprError();
7327 }
7328
7329 // If the argument is a pack expansion, we don't know how many times it would
7330 // expand. If we continue checking the argument, this will make the template
7331 // definition ill-formed if it would be ill-formed for any number of
7332 // expansions during instantiation time. When partial ordering or matching
7333 // template template parameters, this is exactly what we want. Otherwise, the
7334 // normal template rules apply: we accept the template if it would be valid
7335 // for any number of expansions (i.e. none).
7336 if (ArgPE && !StrictCheck) {
7337 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7338 CanonicalConverted = TemplateArgument(
7339 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7340 return Arg;
7341 }
7342
7343 // Avoid making a copy when initializing a template parameter of class type
7344 // from a template parameter object of the same type. This is going beyond
7345 // the standard, but is required for soundness: in
7346 // template<A a> struct X { X *p; X<a> *q; };
7347 // ... we need p and q to have the same type.
7348 //
7349 // Similarly, don't inject a call to a copy constructor when initializing
7350 // from a template parameter of the same type.
7351 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7352 if (ParamType->isRecordType() && isa<DeclRefExpr>(Val: InnerArg) &&
7353 Context.hasSameUnqualifiedType(T1: ParamType, T2: InnerArg->getType())) {
7354 NamedDecl *ND = cast<DeclRefExpr>(Val: InnerArg)->getDecl();
7355 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: ND)) {
7356
7357 SugaredConverted = TemplateArgument(TPO, ParamType);
7358 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7359 ParamType.getCanonicalType());
7360 return Arg;
7361 }
7362 if (isa<NonTypeTemplateParmDecl>(Val: ND)) {
7363 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7364 CanonicalConverted =
7365 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7366 return Arg;
7367 }
7368 }
7369
7370 // The initialization of the parameter from the argument is
7371 // a constant-evaluated context.
7372 EnterExpressionEvaluationContext ConstantEvaluated(
7373 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7374
7375 bool IsConvertedConstantExpression = true;
7376 if (isa<InitListExpr>(Val: DeductionArg) || ParamType->isRecordType()) {
7377 InitializationKind Kind = InitializationKind::CreateForInit(
7378 Loc: StartLoc, /*DirectInit=*/false, Init: DeductionArg);
7379 Expr *Inits[1] = {DeductionArg};
7380 InitializedEntity Entity =
7381 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7382 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7383 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Inits);
7384 if (Result.isInvalid() || !Result.get())
7385 return ExprError();
7386 Result = ActOnConstantExpression(Res: Result.get());
7387 if (Result.isInvalid() || !Result.get())
7388 return ExprError();
7389 setDeductionArg(ActOnFinishFullExpr(Expr: Result.get(), CC: Arg->getBeginLoc(),
7390 /*DiscardedValue=*/false,
7391 /*IsConstexpr=*/true,
7392 /*IsTemplateArgument=*/true)
7393 .get());
7394 IsConvertedConstantExpression = false;
7395 }
7396
7397 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7398 // C++17 [temp.arg.nontype]p1:
7399 // A template-argument for a non-type template parameter shall be
7400 // a converted constant expression of the type of the template-parameter.
7401 APValue Value;
7402 ExprResult ArgResult;
7403 if (IsConvertedConstantExpression) {
7404 ArgResult = BuildConvertedConstantExpression(
7405 From: DeductionArg, T: ParamType,
7406 CCE: StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Dest: Param);
7407 assert(!ArgResult.isUnset());
7408 if (ArgResult.isInvalid()) {
7409 NoteTemplateParameterLocation(Decl: *Param);
7410 return ExprError();
7411 }
7412 } else {
7413 ArgResult = DeductionArg;
7414 }
7415
7416 // For a value-dependent argument, CheckConvertedConstantExpression is
7417 // permitted (and expected) to be unable to determine a value.
7418 if (ArgResult.get()->isValueDependent()) {
7419 setDeductionArg(ArgResult.get());
7420 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7421 CanonicalConverted =
7422 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7423 return Arg;
7424 }
7425
7426 APValue PreNarrowingValue;
7427 ArgResult = EvaluateConvertedConstantExpression(
7428 E: ArgResult.get(), T: ParamType, Value, CCE: CCEKind::TemplateArg, /*RequireInt=*/
7429 false, PreNarrowingValue);
7430 if (ArgResult.isInvalid())
7431 return ExprError();
7432 setDeductionArg(ArgResult.get());
7433
7434 if (Value.isLValue()) {
7435 APValue::LValueBase Base = Value.getLValueBase();
7436 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7437 // For a non-type template-parameter of pointer or reference type,
7438 // the value of the constant expression shall not refer to
7439 assert(ParamType->isPointerOrReferenceType() ||
7440 ParamType->isNullPtrType());
7441 // -- a temporary object
7442 // -- a string literal
7443 // -- the result of a typeid expression, or
7444 // -- a predefined __func__ variable
7445 if (Base &&
7446 (!VD ||
7447 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(Val: VD))) {
7448 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
7449 << Arg->getSourceRange();
7450 return ExprError();
7451 }
7452
7453 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7454 VD->getType()->isArrayType() &&
7455 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7456 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7457 if (ArgPE) {
7458 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7459 CanonicalConverted =
7460 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7461 } else {
7462 SugaredConverted = TemplateArgument(VD, ParamType);
7463 CanonicalConverted =
7464 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7465 ParamType.getCanonicalType());
7466 }
7467 return Arg;
7468 }
7469
7470 // -- a subobject [until C++20]
7471 if (!getLangOpts().CPlusPlus20) {
7472 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7473 Value.isLValueOnePastTheEnd()) {
7474 Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_subobject)
7475 << Value.getAsString(Ctx: Context, Ty: ParamType);
7476 return ExprError();
7477 }
7478 assert((VD || !ParamType->isReferenceType()) &&
7479 "null reference should not be a constant expression");
7480 assert((!VD || !ParamType->isNullPtrType()) &&
7481 "non-null value of type nullptr_t?");
7482 }
7483 }
7484
7485 if (Value.isAddrLabelDiff())
7486 return Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_addr_label_diff);
7487
7488 if (ArgPE) {
7489 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7490 CanonicalConverted =
7491 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7492 } else {
7493 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7494 CanonicalConverted =
7495 TemplateArgument(Context, ParamType.getCanonicalType(), Value);
7496 }
7497 return Arg;
7498 }
7499
7500 // These should have all been handled above using the C++17 rules.
7501 assert(!ArgPE && !StrictCheck);
7502
7503 // C++ [temp.arg.nontype]p5:
7504 // The following conversions are performed on each expression used
7505 // as a non-type template-argument. If a non-type
7506 // template-argument cannot be converted to the type of the
7507 // corresponding template-parameter then the program is
7508 // ill-formed.
7509 if (ParamType->isIntegralOrEnumerationType()) {
7510 // C++11:
7511 // -- for a non-type template-parameter of integral or
7512 // enumeration type, conversions permitted in a converted
7513 // constant expression are applied.
7514 //
7515 // C++98:
7516 // -- for a non-type template-parameter of integral or
7517 // enumeration type, integral promotions (4.5) and integral
7518 // conversions (4.7) are applied.
7519
7520 if (getLangOpts().CPlusPlus11) {
7521 // C++ [temp.arg.nontype]p1:
7522 // A template-argument for a non-type, non-template template-parameter
7523 // shall be one of:
7524 //
7525 // -- for a non-type template-parameter of integral or enumeration
7526 // type, a converted constant expression of the type of the
7527 // template-parameter; or
7528 llvm::APSInt Value;
7529 ExprResult ArgResult = CheckConvertedConstantExpression(
7530 From: Arg, T: ParamType, Value, CCE: CCEKind::TemplateArg);
7531 if (ArgResult.isInvalid())
7532 return ExprError();
7533 Arg = ArgResult.get();
7534
7535 // We can't check arbitrary value-dependent arguments.
7536 if (Arg->isValueDependent()) {
7537 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7538 CanonicalConverted =
7539 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7540 return Arg;
7541 }
7542
7543 // Widen the argument value to sizeof(parameter type). This is almost
7544 // always a no-op, except when the parameter type is bool. In
7545 // that case, this may extend the argument from 1 bit to 8 bits.
7546 QualType IntegerType = ParamType;
7547 if (const auto *ED = IntegerType->getAsEnumDecl())
7548 IntegerType = ED->getIntegerType();
7549 Value = Value.extOrTrunc(width: IntegerType->isBitIntType()
7550 ? Context.getIntWidth(T: IntegerType)
7551 : Context.getTypeSize(T: IntegerType));
7552
7553 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7554 CanonicalConverted =
7555 TemplateArgument(Context, Value, Context.getCanonicalType(T: ParamType));
7556 return Arg;
7557 }
7558
7559 ExprResult ArgResult = DefaultLvalueConversion(E: Arg);
7560 if (ArgResult.isInvalid())
7561 return ExprError();
7562 Arg = ArgResult.get();
7563
7564 QualType ArgType = Arg->getType();
7565
7566 // C++ [temp.arg.nontype]p1:
7567 // A template-argument for a non-type, non-template
7568 // template-parameter shall be one of:
7569 //
7570 // -- an integral constant-expression of integral or enumeration
7571 // type; or
7572 // -- the name of a non-type template-parameter; or
7573 llvm::APSInt Value;
7574 if (!ArgType->isIntegralOrEnumerationType()) {
7575 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_integral_or_enumeral)
7576 << ArgType << Arg->getSourceRange();
7577 NoteTemplateParameterLocation(Decl: *Param);
7578 return ExprError();
7579 }
7580 if (!Arg->isValueDependent()) {
7581 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7582 QualType T;
7583
7584 public:
7585 TmplArgICEDiagnoser(QualType T) : T(T) { }
7586
7587 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7588 SourceLocation Loc) override {
7589 return S.Diag(Loc, DiagID: diag::err_template_arg_not_ice) << T;
7590 }
7591 } Diagnoser(ArgType);
7592
7593 Arg = VerifyIntegerConstantExpression(E: Arg, Result: &Value, Diagnoser).get();
7594 if (!Arg)
7595 return ExprError();
7596 }
7597
7598 // From here on out, all we care about is the unqualified form
7599 // of the argument type.
7600 ArgType = ArgType.getUnqualifiedType();
7601
7602 // Try to convert the argument to the parameter's type.
7603 if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
7604 // Okay: no conversion necessary
7605 } else if (ParamType->isBooleanType()) {
7606 // This is an integral-to-boolean conversion.
7607 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralToBoolean).get();
7608 } else if (IsIntegralPromotion(From: Arg, FromType: ArgType, ToType: ParamType) ||
7609 !ParamType->isEnumeralType()) {
7610 // This is an integral promotion or conversion.
7611 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralCast).get();
7612 } else {
7613 // We can't perform this conversion.
7614 Diag(Loc: StartLoc, DiagID: diag::err_template_arg_not_convertible)
7615 << Arg->getType() << ParamType << Arg->getSourceRange();
7616 NoteTemplateParameterLocation(Decl: *Param);
7617 return ExprError();
7618 }
7619
7620 // Add the value of this argument to the list of converted
7621 // arguments. We use the bitwidth and signedness of the template
7622 // parameter.
7623 if (Arg->isValueDependent()) {
7624 // The argument is value-dependent. Create a new
7625 // TemplateArgument with the converted expression.
7626 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7627 CanonicalConverted =
7628 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7629 return Arg;
7630 }
7631
7632 QualType IntegerType = ParamType;
7633 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7634 IntegerType = ED->getIntegerType();
7635 }
7636
7637 if (ParamType->isBooleanType()) {
7638 // Value must be zero or one.
7639 Value = Value != 0;
7640 unsigned AllowedBits = Context.getTypeSize(T: IntegerType);
7641 if (Value.getBitWidth() != AllowedBits)
7642 Value = Value.extOrTrunc(width: AllowedBits);
7643 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7644 } else {
7645 llvm::APSInt OldValue = Value;
7646
7647 // Coerce the template argument's value to the value it will have
7648 // based on the template parameter's type.
7649 unsigned AllowedBits = IntegerType->isBitIntType()
7650 ? Context.getIntWidth(T: IntegerType)
7651 : Context.getTypeSize(T: IntegerType);
7652 if (Value.getBitWidth() != AllowedBits)
7653 Value = Value.extOrTrunc(width: AllowedBits);
7654 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7655
7656 // Complain if an unsigned parameter received a negative value.
7657 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7658 (OldValue.isSigned() && OldValue.isNegative())) {
7659 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_negative)
7660 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7661 << Arg->getSourceRange();
7662 NoteTemplateParameterLocation(Decl: *Param);
7663 }
7664
7665 // Complain if we overflowed the template parameter's type.
7666 unsigned RequiredBits;
7667 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7668 RequiredBits = OldValue.getActiveBits();
7669 else if (OldValue.isUnsigned())
7670 RequiredBits = OldValue.getActiveBits() + 1;
7671 else
7672 RequiredBits = OldValue.getSignificantBits();
7673 if (RequiredBits > AllowedBits) {
7674 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_too_large)
7675 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7676 << Arg->getSourceRange();
7677 NoteTemplateParameterLocation(Decl: *Param);
7678 }
7679 }
7680
7681 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7682 SugaredConverted = TemplateArgument(Context, Value, T);
7683 CanonicalConverted =
7684 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7685 return Arg;
7686 }
7687
7688 QualType ArgType = Arg->getType();
7689 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7690 bool IsSpecified = CTAK == CTAK_Specified;
7691
7692 // Handle pointer-to-function, reference-to-function, and
7693 // pointer-to-member-function all in (roughly) the same way.
7694 if (// -- For a non-type template-parameter of type pointer to
7695 // function, only the function-to-pointer conversion (4.3) is
7696 // applied. If the template-argument represents a set of
7697 // overloaded functions (or a pointer to such), the matching
7698 // function is selected from the set (13.4).
7699 (ParamType->isPointerType() &&
7700 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7701 // -- For a non-type template-parameter of type reference to
7702 // function, no conversions apply. If the template-argument
7703 // represents a set of overloaded functions, the matching
7704 // function is selected from the set (13.4).
7705 (ParamType->isReferenceType() &&
7706 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7707 // -- For a non-type template-parameter of type pointer to
7708 // member function, no conversions apply. If the
7709 // template-argument represents a set of overloaded member
7710 // functions, the matching member function is selected from
7711 // the set (13.4).
7712 (ParamType->isMemberPointerType() &&
7713 ParamType->castAs<MemberPointerType>()->getPointeeType()
7714 ->isFunctionType())) {
7715
7716 if (Arg->getType() == Context.OverloadTy) {
7717 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg, TargetType: ParamType,
7718 Complain: true,
7719 Found&: FoundResult)) {
7720 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7721 return ExprError();
7722
7723 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7724 if (Res.isInvalid())
7725 return ExprError();
7726 Arg = Res.get();
7727 ArgType = Arg->getType();
7728 } else
7729 return ExprError();
7730 }
7731
7732 if (!ParamType->isMemberPointerType()) {
7733 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7734 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7735 CanonicalConverted))
7736 return ExprError();
7737 return Arg;
7738 }
7739
7740 if (CheckTemplateArgumentPointerToMember(
7741 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7742 return ExprError();
7743 return Arg;
7744 }
7745
7746 if (ParamType->isPointerType()) {
7747 // -- for a non-type template-parameter of type pointer to
7748 // object, qualification conversions (4.4) and the
7749 // array-to-pointer conversion (4.2) are applied.
7750 // C++0x also allows a value of std::nullptr_t.
7751 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7752 "Only object pointers allowed here");
7753
7754 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7755 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7756 CanonicalConverted))
7757 return ExprError();
7758 return Arg;
7759 }
7760
7761 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7762 // -- For a non-type template-parameter of type reference to
7763 // object, no conversions apply. The type referred to by the
7764 // reference may be more cv-qualified than the (otherwise
7765 // identical) type of the template-argument. The
7766 // template-parameter is bound directly to the
7767 // template-argument, which must be an lvalue.
7768 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7769 "Only object references allowed here");
7770
7771 if (Arg->getType() == Context.OverloadTy) {
7772 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg,
7773 TargetType: ParamRefType->getPointeeType(),
7774 Complain: true,
7775 Found&: FoundResult)) {
7776 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7777 return ExprError();
7778 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7779 if (Res.isInvalid())
7780 return ExprError();
7781 Arg = Res.get();
7782 ArgType = Arg->getType();
7783 } else
7784 return ExprError();
7785 }
7786
7787 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7788 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7789 CanonicalConverted))
7790 return ExprError();
7791 return Arg;
7792 }
7793
7794 // Deal with parameters of type std::nullptr_t.
7795 if (ParamType->isNullPtrType()) {
7796 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7797 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7798 CanonicalConverted =
7799 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7800 return Arg;
7801 }
7802
7803 switch (isNullPointerValueTemplateArgument(S&: *this, Param, ParamType, Arg)) {
7804 case NPV_NotNullPointer:
7805 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_not_convertible)
7806 << Arg->getType() << ParamType;
7807 NoteTemplateParameterLocation(Decl: *Param);
7808 return ExprError();
7809
7810 case NPV_Error:
7811 return ExprError();
7812
7813 case NPV_NullPointer:
7814 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7815 SugaredConverted = TemplateArgument(ParamType,
7816 /*isNullPtr=*/true);
7817 CanonicalConverted = TemplateArgument(Context.getCanonicalType(T: ParamType),
7818 /*isNullPtr=*/true);
7819 return Arg;
7820 }
7821 }
7822
7823 // -- For a non-type template-parameter of type pointer to data
7824 // member, qualification conversions (4.4) are applied.
7825 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7826
7827 if (CheckTemplateArgumentPointerToMember(
7828 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7829 return ExprError();
7830 return Arg;
7831}
7832
7833static void DiagnoseTemplateParameterListArityMismatch(
7834 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7835 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7836
7837bool Sema::CheckDeclCompatibleWithTemplateTemplate(
7838 TemplateDecl *Template, TemplateTemplateParmDecl *Param,
7839 const TemplateArgumentLoc &Arg) {
7840 // C++0x [temp.arg.template]p1:
7841 // A template-argument for a template template-parameter shall be
7842 // the name of a class template or an alias template, expressed as an
7843 // id-expression. When the template-argument names a class template, only
7844 // primary class templates are considered when matching the
7845 // template template argument with the corresponding parameter;
7846 // partial specializations are not considered even if their
7847 // parameter lists match that of the template template parameter.
7848 //
7849
7850 TemplateNameKind Kind = TNK_Non_template;
7851 unsigned DiagFoundKind = 0;
7852
7853 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Val: Template)) {
7854 switch (TTP->templateParameterKind()) {
7855 case TemplateNameKind::TNK_Concept_template:
7856 DiagFoundKind = 3;
7857 break;
7858 case TemplateNameKind::TNK_Var_template:
7859 DiagFoundKind = 2;
7860 break;
7861 default:
7862 DiagFoundKind = 1;
7863 break;
7864 }
7865 Kind = TTP->templateParameterKind();
7866 } else if (isa<ConceptDecl>(Val: Template)) {
7867 Kind = TemplateNameKind::TNK_Concept_template;
7868 DiagFoundKind = 3;
7869 } else if (isa<FunctionTemplateDecl>(Val: Template)) {
7870 Kind = TemplateNameKind::TNK_Function_template;
7871 DiagFoundKind = 0;
7872 } else if (isa<VarTemplateDecl>(Val: Template)) {
7873 Kind = TemplateNameKind::TNK_Var_template;
7874 DiagFoundKind = 2;
7875 } else if (isa<ClassTemplateDecl>(Val: Template) ||
7876 isa<TypeAliasTemplateDecl>(Val: Template) ||
7877 isa<BuiltinTemplateDecl>(Val: Template)) {
7878 Kind = TemplateNameKind::TNK_Type_template;
7879 DiagFoundKind = 1;
7880 } else {
7881 assert(false && "Unexpected Decl");
7882 }
7883
7884 if (Kind == Param->templateParameterKind()) {
7885 return true;
7886 }
7887
7888 unsigned DiagKind = 0;
7889 switch (Param->templateParameterKind()) {
7890 case TemplateNameKind::TNK_Concept_template:
7891 DiagKind = 2;
7892 break;
7893 case TemplateNameKind::TNK_Var_template:
7894 DiagKind = 1;
7895 break;
7896 default:
7897 DiagKind = 0;
7898 break;
7899 }
7900 Diag(Loc: Arg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
7901 << DiagKind;
7902 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_arg_refers_to_template_here)
7903 << DiagFoundKind << Template;
7904 return false;
7905}
7906
7907/// Check a template argument against its corresponding
7908/// template template parameter.
7909///
7910/// This routine implements the semantics of C++ [temp.arg.template].
7911/// It returns true if an error occurred, and false otherwise.
7912bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7913 TemplateParameterList *Params,
7914 TemplateArgumentLoc &Arg,
7915 bool PartialOrdering,
7916 bool *StrictPackMatch) {
7917 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7918 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7919 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7920 if (!Template) {
7921 // FIXME: Handle AssumedTemplateNames
7922 // Any dependent template name is fine.
7923 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7924 return false;
7925 }
7926
7927 if (Template->isInvalidDecl())
7928 return true;
7929
7930 if (!CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg)) {
7931 return true;
7932 }
7933
7934 // C++1z [temp.arg.template]p3: (DR 150)
7935 // A template-argument matches a template template-parameter P when P
7936 // is at least as specialized as the template-argument A.
7937 if (!isTemplateTemplateParameterAtLeastAsSpecializedAs(
7938 PParam: Params, PArg: Param, AArg: Template, DefaultArgs, ArgLoc: Arg.getLocation(),
7939 PartialOrdering, StrictPackMatch))
7940 return true;
7941 // P2113
7942 // C++20[temp.func.order]p2
7943 // [...] If both deductions succeed, the partial ordering selects the
7944 // more constrained template (if one exists) as determined below.
7945 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7946 Params->getAssociatedConstraints(AC&: ParamsAC);
7947 // C++20[temp.arg.template]p3
7948 // [...] In this comparison, if P is unconstrained, the constraints on A
7949 // are not considered.
7950 if (ParamsAC.empty())
7951 return false;
7952
7953 Template->getAssociatedConstraints(AC&: TemplateAC);
7954
7955 bool IsParamAtLeastAsConstrained;
7956 if (IsAtLeastAsConstrained(D1: Param, AC1: ParamsAC, D2: Template, AC2: TemplateAC,
7957 Result&: IsParamAtLeastAsConstrained))
7958 return true;
7959 if (!IsParamAtLeastAsConstrained) {
7960 Diag(Loc: Arg.getLocation(),
7961 DiagID: diag::err_template_template_parameter_not_at_least_as_constrained)
7962 << Template << Param << Arg.getSourceRange();
7963 Diag(Loc: Param->getLocation(), DiagID: diag::note_entity_declared_at) << Param;
7964 Diag(Loc: Template->getLocation(), DiagID: diag::note_entity_declared_at) << Template;
7965 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Param, AC1: ParamsAC, D2: Template,
7966 AC2: TemplateAC);
7967 return true;
7968 }
7969 return false;
7970}
7971
7972static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7973 unsigned HereDiagID,
7974 unsigned ExternalDiagID) {
7975 if (Decl.getLocation().isValid())
7976 return S.Diag(Loc: Decl.getLocation(), DiagID: HereDiagID);
7977
7978 SmallString<128> Str;
7979 llvm::raw_svector_ostream Out(Str);
7980 PrintingPolicy PP = S.getPrintingPolicy();
7981 PP.TerseOutput = 1;
7982 Decl.print(Out, Policy: PP);
7983 return S.Diag(Loc: Decl.getLocation(), DiagID: ExternalDiagID) << Out.str();
7984}
7985
7986void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7987 std::optional<SourceRange> ParamRange) {
7988 SemaDiagnosticBuilder DB =
7989 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_decl_here,
7990 ExternalDiagID: diag::note_template_decl_external);
7991 if (ParamRange && ParamRange->isValid()) {
7992 assert(Decl.getLocation().isValid() &&
7993 "Parameter range has location when Decl does not");
7994 DB << *ParamRange;
7995 }
7996}
7997
7998void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7999 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_param_here,
8000 ExternalDiagID: diag::note_template_param_external);
8001}
8002
8003/// Given a non-type template argument that refers to a
8004/// declaration and the type of its corresponding non-type template
8005/// parameter, produce an expression that properly refers to that
8006/// declaration.
8007ExprResult Sema::BuildExpressionFromDeclTemplateArgument(
8008 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
8009 // C++ [temp.param]p8:
8010 //
8011 // A non-type template-parameter of type "array of T" or
8012 // "function returning T" is adjusted to be of type "pointer to
8013 // T" or "pointer to function returning T", respectively.
8014 if (ParamType->isArrayType())
8015 ParamType = Context.getArrayDecayedType(T: ParamType);
8016 else if (ParamType->isFunctionType())
8017 ParamType = Context.getPointerType(T: ParamType);
8018
8019 // For a NULL non-type template argument, return nullptr casted to the
8020 // parameter's type.
8021 if (Arg.getKind() == TemplateArgument::NullPtr) {
8022 return ImpCastExprToType(
8023 E: new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
8024 Type: ParamType,
8025 CK: ParamType->getAs<MemberPointerType>()
8026 ? CK_NullToMemberPointer
8027 : CK_NullToPointer);
8028 }
8029 assert(Arg.getKind() == TemplateArgument::Declaration &&
8030 "Only declaration template arguments permitted here");
8031
8032 ValueDecl *VD = Arg.getAsDecl();
8033
8034 CXXScopeSpec SS;
8035 if (ParamType->isMemberPointerType()) {
8036 // If this is a pointer to member, we need to use a qualified name to
8037 // form a suitable pointer-to-member constant.
8038 assert(VD->getDeclContext()->isRecord() &&
8039 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
8040 isa<IndirectFieldDecl>(VD)));
8041 CanQualType ClassType =
8042 Context.getCanonicalTagType(TD: cast<RecordDecl>(Val: VD->getDeclContext()));
8043 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
8044 SS.MakeTrivial(Context, Qualifier, R: Loc);
8045 }
8046
8047 ExprResult RefExpr = BuildDeclarationNameExpr(
8048 SS, NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
8049 if (RefExpr.isInvalid())
8050 return ExprError();
8051
8052 // For a pointer, the argument declaration is the pointee. Take its address.
8053 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8054 if (ParamType->isPointerType() && !ElemT.isNull() &&
8055 Context.hasSimilarType(T1: ElemT, T2: ParamType->getPointeeType())) {
8056 // Decay an array argument if we want a pointer to its first element.
8057 RefExpr = DefaultFunctionArrayConversion(E: RefExpr.get());
8058 if (RefExpr.isInvalid())
8059 return ExprError();
8060 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8061 // For any other pointer, take the address (or form a pointer-to-member).
8062 RefExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_AddrOf, InputExpr: RefExpr.get());
8063 if (RefExpr.isInvalid())
8064 return ExprError();
8065 } else if (ParamType->isRecordType()) {
8066 assert(isa<TemplateParamObjectDecl>(VD) &&
8067 "arg for class template param not a template parameter object");
8068 // No conversions apply in this case.
8069 return RefExpr;
8070 } else {
8071 assert(ParamType->isReferenceType() &&
8072 "unexpected type for decl template argument");
8073 // If the parameter has reference type, wrap it in paretheses so that this
8074 // expression will have the correct type under `decltype`.
8075 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8076 }
8077
8078 // At this point we should have the right value category.
8079 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8080 "value kind mismatch for non-type template argument");
8081
8082 // The type of the template parameter can differ from the type of the
8083 // argument in various ways; convert it now if necessary.
8084 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8085 QualType SrcExprType = RefExpr.get()->getType();
8086 if (!Context.hasSameType(T1: SrcExprType, T2: DestExprType)) {
8087 CastKind CK;
8088 if (Context.hasSimilarType(T1: SrcExprType, T2: DestExprType) ||
8089 IsFunctionConversion(FromType: SrcExprType, ToType: DestExprType)) {
8090 CK = CK_NoOp;
8091 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8092 CK = CK_BitCast;
8093 } else {
8094 // FIXME: Pointers to members can need conversion derived-to-base or
8095 // base-to-derived conversions. We currently don't retain enough
8096 // information to convert properly (we need to track a cast path or
8097 // subobject number in the template argument).
8098 llvm_unreachable(
8099 "unexpected conversion required for non-type template argument");
8100 }
8101 RefExpr = ImpCastExprToType(E: RefExpr.get(), Type: DestExprType, CK,
8102 VK: RefExpr.get()->getValueKind());
8103 }
8104
8105 return RefExpr;
8106}
8107
8108/// Construct a new expression that refers to the given
8109/// integral template argument with the given source-location
8110/// information.
8111///
8112/// This routine takes care of the mapping from an integral template
8113/// argument (which may have any integral type) to the appropriate
8114/// literal value.
8115static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
8116 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8117 assert(OrigT->isIntegralOrEnumerationType());
8118
8119 // If this is an enum type that we're instantiating, we need to use an integer
8120 // type the same size as the enumerator. We don't want to build an
8121 // IntegerLiteral with enum type. The integer type of an enum type can be of
8122 // any integral type with C++11 enum classes, make sure we create the right
8123 // type of literal for it.
8124 QualType T = OrigT;
8125 if (const auto *ED = OrigT->getAsEnumDecl())
8126 T = ED->getIntegerType();
8127
8128 Expr *E;
8129 if (T->isAnyCharacterType()) {
8130 CharacterLiteralKind Kind;
8131 if (T->isWideCharType())
8132 Kind = CharacterLiteralKind::Wide;
8133 else if (T->isChar8Type() && S.getLangOpts().Char8)
8134 Kind = CharacterLiteralKind::UTF8;
8135 else if (T->isChar16Type())
8136 Kind = CharacterLiteralKind::UTF16;
8137 else if (T->isChar32Type())
8138 Kind = CharacterLiteralKind::UTF32;
8139 else
8140 Kind = CharacterLiteralKind::Ascii;
8141
8142 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8143 } else if (T->isBooleanType()) {
8144 E = CXXBoolLiteralExpr::Create(C: S.Context, Val: Int.getBoolValue(), Ty: T, Loc);
8145 } else {
8146 E = IntegerLiteral::Create(C: S.Context, V: Int, type: T, l: Loc);
8147 }
8148
8149 if (OrigT->isEnumeralType()) {
8150 // FIXME: This is a hack. We need a better way to handle substituted
8151 // non-type template parameters.
8152 E = CStyleCastExpr::Create(Context: S.Context, T: OrigT, VK: VK_PRValue, K: CK_IntegralCast, Op: E,
8153 BasePath: nullptr, FPO: S.CurFPFeatureOverrides(),
8154 WrittenTy: S.Context.getTrivialTypeSourceInfo(T: OrigT, Loc),
8155 L: Loc, R: Loc);
8156 }
8157
8158 return E;
8159}
8160
8161/// Construct a new reflect expression that refers to the given
8162/// entity with the given source-location of the reflection operator.
8163static ExprResult BuildExpressionFromReflection(Sema &S, const APValue &RV,
8164 SourceLocation CaretCaretLoc) {
8165 // TODO(Reflection): Add support for NamespaceReference, TemplateReference,
8166 // and DeclRefExpr.
8167 return CXXReflectExpr::Create(
8168 C&: S.Context, OperatorLoc: CaretCaretLoc,
8169 TSI: static_cast<TypeSourceInfo *>(
8170 const_cast<void *>(RV.getReflectionOpaqueOperand())));
8171}
8172
8173static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
8174 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8175 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8176 auto *ILE = new (S.Context)
8177 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8178 ILE->setType(T);
8179 return ILE;
8180 };
8181
8182 switch (Val.getKind()) {
8183 case APValue::AddrLabelDiff:
8184 // This cannot occur in a template argument at all.
8185 case APValue::Array:
8186 case APValue::Struct:
8187 case APValue::Union:
8188 // These can only occur within a template parameter object, which is
8189 // represented as a TemplateArgument::Declaration.
8190 llvm_unreachable("unexpected template argument value");
8191
8192 case APValue::Int:
8193 return BuildExpressionFromIntegralTemplateArgumentValue(S, OrigT: T, Int: Val.getInt(),
8194 Loc);
8195
8196 case APValue::Float:
8197 return FloatingLiteral::Create(C: S.Context, V: Val.getFloat(), /*IsExact=*/isexact: true,
8198 Type: T, L: Loc);
8199
8200 case APValue::FixedPoint:
8201 return FixedPointLiteral::CreateFromRawInt(
8202 C: S.Context, V: Val.getFixedPoint().getValue(), type: T, l: Loc,
8203 Scale: Val.getFixedPoint().getScale());
8204
8205 case APValue::ComplexInt: {
8206 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8207 return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
8208 S, OrigT: ElemT, Int: Val.getComplexIntReal(), Loc),
8209 BuildExpressionFromIntegralTemplateArgumentValue(
8210 S, OrigT: ElemT, Int: Val.getComplexIntImag(), Loc)});
8211 }
8212
8213 case APValue::ComplexFloat: {
8214 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8215 return MakeInitList(
8216 {FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatReal(), isexact: true,
8217 Type: ElemT, L: Loc),
8218 FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatImag(), isexact: true,
8219 Type: ElemT, L: Loc)});
8220 }
8221
8222 case APValue::Vector: {
8223 QualType ElemT = T->castAs<VectorType>()->getElementType();
8224 llvm::SmallVector<Expr *, 8> Elts;
8225 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8226 Elts.push_back(Elt: BuildExpressionFromNonTypeTemplateArgumentValue(
8227 S, T: ElemT, Val: Val.getVectorElt(I), Loc));
8228 return MakeInitList(Elts);
8229 }
8230
8231 case APValue::Matrix:
8232 llvm_unreachable("Matrix template argument expression not yet supported");
8233
8234 case APValue::None:
8235 case APValue::Indeterminate:
8236 llvm_unreachable("Unexpected APValue kind.");
8237 case APValue::LValue:
8238 case APValue::MemberPointer: {
8239 // There isn't necessarily a valid equivalent source-level syntax for
8240 // these; in particular, a naive lowering might violate access control.
8241 // So for now we lower to a ConstantExpr holding the value, wrapped around
8242 // an OpaqueValueExpr.
8243 // FIXME: We should have a better representation for this.
8244 ExprValueKind VK = VK_PRValue;
8245 if (T->isReferenceType()) {
8246 T = T->getPointeeType();
8247 VK = VK_LValue;
8248 }
8249 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8250 return ConstantExpr::Create(Context: S.Context, E: OVE, Result: Val);
8251 }
8252 case APValue::Reflection:
8253 return BuildExpressionFromReflection(S, RV: Val, CaretCaretLoc: Loc).get();
8254 }
8255 llvm_unreachable("Unhandled APValue::ValueKind enum");
8256}
8257
8258ExprResult
8259Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
8260 SourceLocation Loc) {
8261 switch (Arg.getKind()) {
8262 case TemplateArgument::Null:
8263 case TemplateArgument::Type:
8264 case TemplateArgument::Template:
8265 case TemplateArgument::TemplateExpansion:
8266 case TemplateArgument::Pack:
8267 llvm_unreachable("not a non-type template argument");
8268
8269 case TemplateArgument::Expression:
8270 return Arg.getAsExpr();
8271
8272 case TemplateArgument::NullPtr:
8273 case TemplateArgument::Declaration:
8274 return BuildExpressionFromDeclTemplateArgument(
8275 Arg, ParamType: Arg.getNonTypeTemplateArgumentType(), Loc);
8276
8277 case TemplateArgument::Integral:
8278 return BuildExpressionFromIntegralTemplateArgumentValue(
8279 S&: *this, OrigT: Arg.getIntegralType(), Int: Arg.getAsIntegral(), Loc);
8280
8281 case TemplateArgument::StructuralValue:
8282 return BuildExpressionFromNonTypeTemplateArgumentValue(
8283 S&: *this, T: Arg.getStructuralValueType(), Val: Arg.getAsStructuralValue(), Loc);
8284 }
8285 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8286}
8287
8288/// Match two template parameters within template parameter lists.
8289static bool MatchTemplateParameterKind(
8290 Sema &S, NamedDecl *New,
8291 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8292 const NamedDecl *OldInstFrom, bool Complain,
8293 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8294 // Check the actual kind (type, non-type, template).
8295 if (Old->getKind() != New->getKind()) {
8296 if (Complain) {
8297 unsigned NextDiag = diag::err_template_param_different_kind;
8298 if (TemplateArgLoc.isValid()) {
8299 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8300 NextDiag = diag::note_template_param_different_kind;
8301 }
8302 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8303 << (Kind != Sema::TPL_TemplateMatch);
8304 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_prev_declaration)
8305 << (Kind != Sema::TPL_TemplateMatch);
8306 }
8307
8308 return false;
8309 }
8310
8311 // Check that both are parameter packs or neither are parameter packs.
8312 // However, if we are matching a template template argument to a
8313 // template template parameter, the template template parameter can have
8314 // a parameter pack where the template template argument does not.
8315 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8316 if (Complain) {
8317 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8318 if (TemplateArgLoc.isValid()) {
8319 S.Diag(Loc: TemplateArgLoc,
8320 DiagID: diag::err_template_arg_template_params_mismatch);
8321 NextDiag = diag::note_template_parameter_pack_non_pack;
8322 }
8323
8324 unsigned ParamKind = isa<TemplateTypeParmDecl>(Val: New)? 0
8325 : isa<NonTypeTemplateParmDecl>(Val: New)? 1
8326 : 2;
8327 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8328 << ParamKind << New->isParameterPack();
8329 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_parameter_pack_here)
8330 << ParamKind << Old->isParameterPack();
8331 }
8332
8333 return false;
8334 }
8335 // For non-type template parameters, check the type of the parameter.
8336 if (NonTypeTemplateParmDecl *OldNTTP =
8337 dyn_cast<NonTypeTemplateParmDecl>(Val: Old)) {
8338 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(Val: New);
8339
8340 // If we are matching a template template argument to a template
8341 // template parameter and one of the non-type template parameter types
8342 // is dependent, then we must wait until template instantiation time
8343 // to actually compare the arguments.
8344 if (Kind != Sema::TPL_TemplateTemplateParmMatch ||
8345 (!OldNTTP->getType()->isDependentType() &&
8346 !NewNTTP->getType()->isDependentType())) {
8347 // C++20 [temp.over.link]p6:
8348 // Two [non-type] template-parameters are equivalent [if] they have
8349 // equivalent types ignoring the use of type-constraints for
8350 // placeholder types
8351 QualType OldType = S.Context.getUnconstrainedType(T: OldNTTP->getType());
8352 QualType NewType = S.Context.getUnconstrainedType(T: NewNTTP->getType());
8353 if (!S.Context.hasSameType(T1: OldType, T2: NewType)) {
8354 if (Complain) {
8355 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8356 if (TemplateArgLoc.isValid()) {
8357 S.Diag(Loc: TemplateArgLoc,
8358 DiagID: diag::err_template_arg_template_params_mismatch);
8359 NextDiag = diag::note_template_nontype_parm_different_type;
8360 }
8361 S.Diag(Loc: NewNTTP->getLocation(), DiagID: NextDiag)
8362 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8363 S.Diag(Loc: OldNTTP->getLocation(),
8364 DiagID: diag::note_template_nontype_parm_prev_declaration)
8365 << OldNTTP->getType();
8366 }
8367 return false;
8368 }
8369 }
8370 }
8371 // For template template parameters, check the template parameter types.
8372 // The template parameter lists of template template
8373 // parameters must agree.
8374 else if (TemplateTemplateParmDecl *OldTTP =
8375 dyn_cast<TemplateTemplateParmDecl>(Val: Old)) {
8376 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(Val: New);
8377 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8378 return false;
8379 if (!S.TemplateParameterListsAreEqual(
8380 NewInstFrom, New: NewTTP->getTemplateParameters(), OldInstFrom,
8381 Old: OldTTP->getTemplateParameters(), Complain,
8382 Kind: (Kind == Sema::TPL_TemplateMatch
8383 ? Sema::TPL_TemplateTemplateParmMatch
8384 : Kind),
8385 TemplateArgLoc))
8386 return false;
8387 }
8388
8389 if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8390 Kind != Sema::TPL_TemplateTemplateParmMatch &&
8391 !isa<TemplateTemplateParmDecl>(Val: Old)) {
8392 const Expr *NewC = nullptr, *OldC = nullptr;
8393
8394 if (isa<TemplateTypeParmDecl>(Val: New)) {
8395 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: New)->getTypeConstraint())
8396 NewC = TC->getImmediatelyDeclaredConstraint();
8397 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: Old)->getTypeConstraint())
8398 OldC = TC->getImmediatelyDeclaredConstraint();
8399 } else if (isa<NonTypeTemplateParmDecl>(Val: New)) {
8400 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: New)
8401 ->getPlaceholderTypeConstraint())
8402 NewC = E;
8403 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: Old)
8404 ->getPlaceholderTypeConstraint())
8405 OldC = E;
8406 } else
8407 llvm_unreachable("unexpected template parameter type");
8408
8409 auto Diagnose = [&] {
8410 S.Diag(Loc: NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8411 DiagID: diag::err_template_different_type_constraint);
8412 S.Diag(Loc: OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8413 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8414 };
8415
8416 if (!NewC != !OldC) {
8417 if (Complain)
8418 Diagnose();
8419 return false;
8420 }
8421
8422 if (NewC) {
8423 if (!S.AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldC, New: NewInstFrom,
8424 NewConstr: NewC)) {
8425 if (Complain)
8426 Diagnose();
8427 return false;
8428 }
8429 }
8430 }
8431
8432 return true;
8433}
8434
8435/// Diagnose a known arity mismatch when comparing template argument
8436/// lists.
8437static
8438void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8439 TemplateParameterList *New,
8440 TemplateParameterList *Old,
8441 Sema::TemplateParameterListEqualKind Kind,
8442 SourceLocation TemplateArgLoc) {
8443 unsigned NextDiag = diag::err_template_param_list_different_arity;
8444 if (TemplateArgLoc.isValid()) {
8445 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8446 NextDiag = diag::note_template_param_list_different_arity;
8447 }
8448 S.Diag(Loc: New->getTemplateLoc(), DiagID: NextDiag)
8449 << (New->size() > Old->size())
8450 << (Kind != Sema::TPL_TemplateMatch)
8451 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8452 S.Diag(Loc: Old->getTemplateLoc(), DiagID: diag::note_template_prev_declaration)
8453 << (Kind != Sema::TPL_TemplateMatch)
8454 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8455}
8456
8457bool Sema::TemplateParameterListsAreEqual(
8458 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8459 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8460 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8461 if (Old->size() != New->size()) {
8462 if (Complain)
8463 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8464 TemplateArgLoc);
8465
8466 return false;
8467 }
8468
8469 // C++0x [temp.arg.template]p3:
8470 // A template-argument matches a template template-parameter (call it P)
8471 // when each of the template parameters in the template-parameter-list of
8472 // the template-argument's corresponding class template or alias template
8473 // (call it A) matches the corresponding template parameter in the
8474 // template-parameter-list of P. [...]
8475 TemplateParameterList::iterator NewParm = New->begin();
8476 TemplateParameterList::iterator NewParmEnd = New->end();
8477 for (TemplateParameterList::iterator OldParm = Old->begin(),
8478 OldParmEnd = Old->end();
8479 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8480 if (NewParm == NewParmEnd) {
8481 if (Complain)
8482 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8483 TemplateArgLoc);
8484 return false;
8485 }
8486 if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm,
8487 OldInstFrom, Complain, Kind,
8488 TemplateArgLoc))
8489 return false;
8490 }
8491
8492 // Make sure we exhausted all of the arguments.
8493 if (NewParm != NewParmEnd) {
8494 if (Complain)
8495 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8496 TemplateArgLoc);
8497
8498 return false;
8499 }
8500
8501 if (Kind != TPL_TemplateParamsEquivalent) {
8502 const Expr *NewRC = New->getRequiresClause();
8503 const Expr *OldRC = Old->getRequiresClause();
8504
8505 auto Diagnose = [&] {
8506 Diag(Loc: NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8507 DiagID: diag::err_template_different_requires_clause);
8508 Diag(Loc: OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8509 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8510 };
8511
8512 if (!NewRC != !OldRC) {
8513 if (Complain)
8514 Diagnose();
8515 return false;
8516 }
8517
8518 if (NewRC) {
8519 if (!AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldRC, New: NewInstFrom,
8520 NewConstr: NewRC)) {
8521 if (Complain)
8522 Diagnose();
8523 return false;
8524 }
8525 }
8526 }
8527
8528 return true;
8529}
8530
8531bool
8532Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8533 if (!S)
8534 return false;
8535
8536 // Find the nearest enclosing declaration scope.
8537 S = S->getDeclParent();
8538
8539 // C++ [temp.pre]p6: [P2096]
8540 // A template, explicit specialization, or partial specialization shall not
8541 // have C linkage.
8542 DeclContext *Ctx = S->getEntity();
8543 if (Ctx && Ctx->isExternCContext()) {
8544 SourceRange Range =
8545 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8546 ? TemplateParams->getParam(Idx: 0)->getSourceRange()
8547 : TemplateParams->getSourceRange();
8548 Diag(Loc: Range.getBegin(), DiagID: diag::err_template_linkage) << Range;
8549 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8550 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
8551 return true;
8552 }
8553 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8554
8555 // C++ [temp]p2:
8556 // A template-declaration can appear only as a namespace scope or
8557 // class scope declaration.
8558 // C++ [temp.expl.spec]p3:
8559 // An explicit specialization may be declared in any scope in which the
8560 // corresponding primary template may be defined.
8561 // C++ [temp.class.spec]p6: [P2096]
8562 // A partial specialization may be declared in any scope in which the
8563 // corresponding primary template may be defined.
8564 if (Ctx) {
8565 if (Ctx->isFileContext())
8566 return false;
8567 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Ctx)) {
8568 // C++ [temp.mem]p2:
8569 // A local class shall not have member templates.
8570
8571 // Trace the outer context chain, bypassing nested records and OpenMP
8572 // captured regions, to determine if the class in defined inside a
8573 // function or method.
8574 const DeclContext *OutCtx = RD->getDeclContext();
8575 while (isa_and_nonnull<CapturedDecl, CXXRecordDecl>(Val: OutCtx))
8576 OutCtx = OutCtx->getParent();
8577
8578 if (OutCtx && OutCtx->isFunctionOrMethod())
8579 return Diag(Loc: TemplateParams->getTemplateLoc(),
8580 DiagID: diag::err_template_inside_local_class)
8581 << TemplateParams->getSourceRange();
8582
8583 return false;
8584 }
8585 }
8586
8587 return Diag(Loc: TemplateParams->getTemplateLoc(),
8588 DiagID: diag::err_template_outside_namespace_or_class_scope)
8589 << TemplateParams->getSourceRange();
8590}
8591
8592/// Determine what kind of template specialization the given declaration
8593/// is.
8594static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8595 if (!D)
8596 return TSK_Undeclared;
8597
8598 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D))
8599 return Record->getTemplateSpecializationKind();
8600 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D))
8601 return Function->getTemplateSpecializationKind();
8602 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D))
8603 return Var->getTemplateSpecializationKind();
8604
8605 return TSK_Undeclared;
8606}
8607
8608/// Check whether a specialization is well-formed in the current
8609/// context.
8610///
8611/// This routine determines whether a template specialization can be declared
8612/// in the current context (C++ [temp.expl.spec]p2).
8613///
8614/// \param S the semantic analysis object for which this check is being
8615/// performed.
8616///
8617/// \param Specialized the entity being specialized or instantiated, which
8618/// may be a kind of template (class template, function template, etc.) or
8619/// a member of a class template (member function, static data member,
8620/// member class).
8621///
8622/// \param PrevDecl the previous declaration of this entity, if any.
8623///
8624/// \param Loc the location of the explicit specialization or instantiation of
8625/// this entity.
8626///
8627/// \param IsPartialSpecialization whether this is a partial specialization of
8628/// a class template.
8629///
8630/// \returns true if there was an error that we cannot recover from, false
8631/// otherwise.
8632static bool CheckTemplateSpecializationScope(Sema &S,
8633 NamedDecl *Specialized,
8634 NamedDecl *PrevDecl,
8635 SourceLocation Loc,
8636 bool IsPartialSpecialization) {
8637 // Keep these "kind" numbers in sync with the %select statements in the
8638 // various diagnostics emitted by this routine.
8639 int EntityKind = 0;
8640 if (isa<ClassTemplateDecl>(Val: Specialized))
8641 EntityKind = IsPartialSpecialization? 1 : 0;
8642 else if (isa<VarTemplateDecl>(Val: Specialized))
8643 EntityKind = IsPartialSpecialization ? 3 : 2;
8644 else if (isa<FunctionTemplateDecl>(Val: Specialized))
8645 EntityKind = 4;
8646 else if (isa<CXXMethodDecl>(Val: Specialized))
8647 EntityKind = 5;
8648 else if (isa<VarDecl>(Val: Specialized))
8649 EntityKind = 6;
8650 else if (isa<RecordDecl>(Val: Specialized))
8651 EntityKind = 7;
8652 else if (isa<EnumDecl>(Val: Specialized) && S.getLangOpts().CPlusPlus11)
8653 EntityKind = 8;
8654 else {
8655 S.Diag(Loc, DiagID: diag::err_template_spec_unknown_kind)
8656 << S.getLangOpts().CPlusPlus11;
8657 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8658 return true;
8659 }
8660
8661 // C++ [temp.expl.spec]p2:
8662 // An explicit specialization may be declared in any scope in which
8663 // the corresponding primary template may be defined.
8664 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8665 S.Diag(Loc, DiagID: diag::err_template_spec_decl_function_scope)
8666 << Specialized;
8667 return true;
8668 }
8669
8670 // C++ [temp.class.spec]p6:
8671 // A class template partial specialization may be declared in any
8672 // scope in which the primary template may be defined.
8673 DeclContext *SpecializedContext =
8674 Specialized->getDeclContext()->getRedeclContext();
8675 DeclContext *DC = S.CurContext->getRedeclContext();
8676
8677 // Make sure that this redeclaration (or definition) occurs in the same
8678 // scope or an enclosing namespace.
8679 if (!(DC->isFileContext() ? DC->Encloses(DC: SpecializedContext)
8680 : DC->Equals(DC: SpecializedContext))) {
8681 if (isa<TranslationUnitDecl>(Val: SpecializedContext))
8682 S.Diag(Loc, DiagID: diag::err_template_spec_redecl_global_scope)
8683 << EntityKind << Specialized;
8684 else {
8685 auto *ND = cast<NamedDecl>(Val: SpecializedContext);
8686 int Diag = diag::err_template_spec_redecl_out_of_scope;
8687 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8688 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8689 S.Diag(Loc, DiagID: Diag) << EntityKind << Specialized
8690 << ND << isa<CXXRecordDecl>(Val: ND);
8691 }
8692
8693 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8694
8695 // Don't allow specializing in the wrong class during error recovery.
8696 // Otherwise, things can go horribly wrong.
8697 if (DC->isRecord())
8698 return true;
8699 }
8700
8701 return false;
8702}
8703
8704static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8705 if (!E->isTypeDependent())
8706 return SourceLocation();
8707 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8708 Checker.TraverseStmt(S: E);
8709 if (Checker.MatchLoc.isInvalid())
8710 return E->getSourceRange();
8711 return Checker.MatchLoc;
8712}
8713
8714static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8715 if (!TL.getType()->isDependentType())
8716 return SourceLocation();
8717 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8718 Checker.TraverseTypeLoc(TL);
8719 if (Checker.MatchLoc.isInvalid())
8720 return TL.getSourceRange();
8721 return Checker.MatchLoc;
8722}
8723
8724/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8725/// that checks non-type template partial specialization arguments.
8726static bool CheckNonTypeTemplatePartialSpecializationArgs(
8727 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8728 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8729 bool HasError = false;
8730 for (unsigned I = 0; I != NumArgs; ++I) {
8731 if (Args[I].getKind() == TemplateArgument::Pack) {
8732 if (CheckNonTypeTemplatePartialSpecializationArgs(
8733 S, TemplateNameLoc, Param, Args: Args[I].pack_begin(),
8734 NumArgs: Args[I].pack_size(), IsDefaultArgument))
8735 return true;
8736
8737 continue;
8738 }
8739
8740 if (Args[I].getKind() != TemplateArgument::Expression)
8741 continue;
8742
8743 Expr *ArgExpr = Args[I].getAsExpr();
8744 if (ArgExpr->containsErrors()) {
8745 HasError = true;
8746 continue;
8747 }
8748
8749 // We can have a pack expansion of any of the bullets below.
8750 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: ArgExpr))
8751 ArgExpr = Expansion->getPattern();
8752
8753 // Strip off any implicit casts we added as part of type checking.
8754 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
8755 ArgExpr = ICE->getSubExpr();
8756
8757 // C++ [temp.class.spec]p8:
8758 // A non-type argument is non-specialized if it is the name of a
8759 // non-type parameter. All other non-type arguments are
8760 // specialized.
8761 //
8762 // Below, we check the two conditions that only apply to
8763 // specialized non-type arguments, so skip any non-specialized
8764 // arguments.
8765 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ArgExpr))
8766 if (isa<NonTypeTemplateParmDecl>(Val: DRE->getDecl()))
8767 continue;
8768
8769 if (isa<DependentTemplateIdExpr>(Val: ArgExpr))
8770 continue;
8771
8772 // C++ [temp.class.spec]p9:
8773 // Within the argument list of a class template partial
8774 // specialization, the following restrictions apply:
8775 // -- A partially specialized non-type argument expression
8776 // shall not involve a template parameter of the partial
8777 // specialization except when the argument expression is a
8778 // simple identifier.
8779 // -- The type of a template parameter corresponding to a
8780 // specialized non-type argument shall not be dependent on a
8781 // parameter of the specialization.
8782 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8783 // We implement a compromise between the original rules and DR1315:
8784 // -- A specialized non-type template argument shall not be
8785 // type-dependent and the corresponding template parameter
8786 // shall have a non-dependent type.
8787 SourceRange ParamUseRange =
8788 findTemplateParameterInType(Depth: Param->getDepth(), E: ArgExpr);
8789 if (ParamUseRange.isValid()) {
8790 if (IsDefaultArgument) {
8791 S.Diag(Loc: TemplateNameLoc,
8792 DiagID: diag::err_dependent_non_type_arg_in_partial_spec);
8793 S.Diag(Loc: ParamUseRange.getBegin(),
8794 DiagID: diag::note_dependent_non_type_default_arg_in_partial_spec)
8795 << ParamUseRange;
8796 } else {
8797 S.Diag(Loc: ParamUseRange.getBegin(),
8798 DiagID: diag::err_dependent_non_type_arg_in_partial_spec)
8799 << ParamUseRange;
8800 }
8801 return true;
8802 }
8803
8804 ParamUseRange = findTemplateParameter(
8805 Depth: Param->getDepth(), TL: Param->getTypeSourceInfo()->getTypeLoc());
8806 if (ParamUseRange.isValid()) {
8807 S.Diag(Loc: IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8808 DiagID: diag::err_dependent_typed_non_type_arg_in_partial_spec)
8809 << Param->getType();
8810 S.NoteTemplateParameterLocation(Decl: *Param);
8811 return true;
8812 }
8813 }
8814
8815 return HasError;
8816}
8817
8818bool Sema::CheckTemplatePartialSpecializationArgs(
8819 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8820 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8821 // We have to be conservative when checking a template in a dependent
8822 // context.
8823 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8824 return false;
8825
8826 TemplateParameterList *TemplateParams =
8827 PrimaryTemplate->getTemplateParameters();
8828 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8829 NonTypeTemplateParmDecl *Param
8830 = dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: I));
8831 if (!Param)
8832 continue;
8833
8834 if (CheckNonTypeTemplatePartialSpecializationArgs(S&: *this, TemplateNameLoc,
8835 Param, Args: &TemplateArgs[I],
8836 NumArgs: 1, IsDefaultArgument: I >= NumExplicit))
8837 return true;
8838 }
8839
8840 return false;
8841}
8842
8843DeclResult Sema::ActOnClassTemplateSpecialization(
8844 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8845 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8846 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8847 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8848 assert(TUK != TagUseKind::Reference && "References are not specializations");
8849
8850 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8851 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8852 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8853
8854 // Find the class template we're specializing
8855 TemplateName Name = TemplateId.Template.get();
8856 ClassTemplateDecl *ClassTemplate
8857 = dyn_cast_or_null<ClassTemplateDecl>(Val: Name.getAsTemplateDecl());
8858
8859 if (!ClassTemplate) {
8860 Diag(Loc: TemplateNameLoc, DiagID: diag::err_not_class_template_specialization)
8861 << (Name.getAsTemplateDecl() &&
8862 isa<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl()));
8863 return true;
8864 }
8865
8866 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8867 auto Message = DSA->getMessage();
8868 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
8869 << ClassTemplate << !Message.empty() << Message;
8870 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
8871 }
8872
8873 if (S->isTemplateParamScope())
8874 EnterTemplatedContext(S, DC: ClassTemplate->getTemplatedDecl());
8875
8876 DeclContext *DC = ClassTemplate->getDeclContext();
8877
8878 bool isMemberSpecialization = false;
8879 bool isPartialSpecialization = false;
8880
8881 if (SS.isSet()) {
8882 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8883 diagnoseQualifiedDeclaration(SS, DC, Name: ClassTemplate->getDeclName(),
8884 Loc: TemplateNameLoc, TemplateId: &TemplateId,
8885 /*IsMemberSpecialization=*/false))
8886 return true;
8887 }
8888
8889 // Check the validity of the template headers that introduce this
8890 // template.
8891 // FIXME: We probably shouldn't complain about these headers for
8892 // friend declarations.
8893 bool Invalid = false;
8894 TemplateParameterList *TemplateParams =
8895 MatchTemplateParametersToScopeSpecifier(
8896 DeclStartLoc: KWLoc, DeclLoc: TemplateNameLoc, SS, TemplateId: &TemplateId, ParamLists: TemplateParameterLists,
8897 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
8898 if (Invalid)
8899 return true;
8900
8901 // Check that we can declare a template specialization here.
8902 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8903 return true;
8904
8905 if (TemplateParams && DC->isDependentContext()) {
8906 ContextRAII SavedContext(*this, DC);
8907 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
8908 return true;
8909 }
8910
8911 if (TemplateParams && TemplateParams->size() > 0) {
8912 isPartialSpecialization = true;
8913
8914 if (TUK == TagUseKind::Friend) {
8915 Diag(Loc: KWLoc, DiagID: diag::err_partial_specialization_friend)
8916 << SourceRange(LAngleLoc, RAngleLoc);
8917 return true;
8918 }
8919
8920 // C++ [temp.class.spec]p10:
8921 // The template parameter list of a specialization shall not
8922 // contain default template argument values.
8923 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8924 Decl *Param = TemplateParams->getParam(Idx: I);
8925 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
8926 if (TTP->hasDefaultArgument()) {
8927 Diag(Loc: TTP->getDefaultArgumentLoc(),
8928 DiagID: diag::err_default_arg_in_partial_spec);
8929 TTP->removeDefaultArgument();
8930 }
8931 } else if (NonTypeTemplateParmDecl *NTTP
8932 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
8933 if (NTTP->hasDefaultArgument()) {
8934 Diag(Loc: NTTP->getDefaultArgumentLoc(),
8935 DiagID: diag::err_default_arg_in_partial_spec)
8936 << NTTP->getDefaultArgument().getSourceRange();
8937 NTTP->removeDefaultArgument();
8938 }
8939 } else {
8940 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
8941 if (TTP->hasDefaultArgument()) {
8942 Diag(Loc: TTP->getDefaultArgument().getLocation(),
8943 DiagID: diag::err_default_arg_in_partial_spec)
8944 << TTP->getDefaultArgument().getSourceRange();
8945 TTP->removeDefaultArgument();
8946 }
8947 }
8948 }
8949 } else if (TemplateParams) {
8950 if (TUK == TagUseKind::Friend)
8951 Diag(Loc: KWLoc, DiagID: diag::err_template_spec_friend)
8952 << FixItHint::CreateRemoval(
8953 RemoveRange: SourceRange(TemplateParams->getTemplateLoc(),
8954 TemplateParams->getRAngleLoc()))
8955 << SourceRange(LAngleLoc, RAngleLoc);
8956 } else {
8957 assert(TUK == TagUseKind::Friend &&
8958 "should have a 'template<>' for this decl");
8959 }
8960
8961 // Check that the specialization uses the same tag kind as the
8962 // original template.
8963 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
8964 assert(Kind != TagTypeKind::Enum &&
8965 "Invalid enum tag in class template spec!");
8966 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(), NewTag: Kind,
8967 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
8968 Name: ClassTemplate->getIdentifier())) {
8969 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
8970 << ClassTemplate
8971 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
8972 Code: ClassTemplate->getTemplatedDecl()->getKindName());
8973 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
8974 DiagID: diag::note_previous_use);
8975 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8976 }
8977
8978 // Translate the parser's template argument list in our AST format.
8979 TemplateArgumentListInfo TemplateArgs =
8980 makeTemplateArgumentListInfo(S&: *this, TemplateId);
8981
8982 // Check for unexpanded parameter packs in any of the template arguments.
8983 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8984 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
8985 UPPC: isPartialSpecialization
8986 ? UPPC_PartialSpecialization
8987 : UPPC_ExplicitSpecialization))
8988 return true;
8989
8990 // Check that the template argument list is well-formed for this
8991 // template.
8992 CheckTemplateArgumentInfo CTAI;
8993 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
8994 /*DefaultArgs=*/{},
8995 /*PartialTemplateArgs=*/false, CTAI,
8996 /*UpdateArgsWithConversions=*/true))
8997 return true;
8998
8999 // Find the class template (partial) specialization declaration that
9000 // corresponds to these arguments.
9001 if (isPartialSpecialization) {
9002 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, PrimaryTemplate: ClassTemplate,
9003 NumExplicit: TemplateArgs.size(),
9004 TemplateArgs: CTAI.CanonicalConverted))
9005 return true;
9006
9007 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
9008 // also do it during instantiation.
9009 if (!Name.isDependent() &&
9010 !TemplateSpecializationType::anyDependentTemplateArguments(
9011 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
9012 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
9013 << ClassTemplate->getDeclName();
9014 isPartialSpecialization = false;
9015 Invalid = true;
9016 }
9017 }
9018
9019 llvm::FoldingSetInsertToken InsertToken;
9020 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
9021
9022 if (isPartialSpecialization)
9023 PrevDecl = ClassTemplate->findPartialSpecialization(
9024 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertToken);
9025 else
9026 PrevDecl =
9027 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertToken);
9028
9029 ClassTemplateSpecializationDecl *Specialization = nullptr;
9030
9031 // Check whether we can declare a class template specialization in
9032 // the current scope.
9033 if (TUK != TagUseKind::Friend &&
9034 CheckTemplateSpecializationScope(S&: *this, Specialized: ClassTemplate, PrevDecl,
9035 Loc: TemplateNameLoc,
9036 IsPartialSpecialization: isPartialSpecialization))
9037 return true;
9038
9039 if (!isPartialSpecialization) {
9040 // Create a new class template specialization declaration node for
9041 // this explicit specialization or friend declaration.
9042 Specialization = ClassTemplateSpecializationDecl::Create(
9043 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
9044 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
9045 Specialization->setTemplateArgsAsWritten(TemplateArgs);
9046 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
9047 if (TemplateParameterLists.size() > 0) {
9048 Specialization->setTemplateParameterListsInfo(Context,
9049 TPLists: TemplateParameterLists);
9050 }
9051
9052 if (!PrevDecl)
9053 ClassTemplate->AddSpecialization(D: Specialization, InsertToken);
9054 } else {
9055 CanQualType CanonType = CanQualType::CreateUnsafe(
9056 Other: Context.getCanonicalTemplateSpecializationType(
9057 Keyword: ElaboratedTypeKeyword::None,
9058 T: TemplateName(ClassTemplate->getCanonicalDecl()),
9059 CanonicalArgs: CTAI.CanonicalConverted));
9060 if (Context.hasSameType(
9061 T1: CanonType,
9062 T2: ClassTemplate->getCanonicalInjectedSpecializationType(Ctx: Context)) &&
9063 (!Context.getLangOpts().CPlusPlus20 ||
9064 !TemplateParams->hasAssociatedConstraints())) {
9065 // C++ [temp.class.spec]p9b3:
9066 //
9067 // -- The argument list of the specialization shall not be identical
9068 // to the implicit argument list of the primary template.
9069 //
9070 // This rule has since been removed, because it's redundant given DR1495,
9071 // but we keep it because it produces better diagnostics and recovery.
9072 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
9073 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
9074 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
9075 return CheckClassTemplate(
9076 S, TagSpec, TUK, KWLoc, SS, Name: ClassTemplate->getIdentifier(),
9077 NameLoc: TemplateNameLoc, Attr, TemplateParams, AS: AS_none,
9078 /*ModulePrivateLoc=*/SourceLocation(),
9079 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
9080 OuterTemplateParamLists: TemplateParameterLists.data(), IsMemberSpecialization: isMemberSpecialization);
9081 }
9082
9083 // Create a new class template partial specialization declaration node.
9084 ClassTemplatePartialSpecializationDecl *PrevPartial =
9085 cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl);
9086 ClassTemplatePartialSpecializationDecl *Partial =
9087 ClassTemplatePartialSpecializationDecl::Create(
9088 Context, TK: Kind, DC, StartLoc: KWLoc, IdLoc: TemplateNameLoc, Params: TemplateParams,
9089 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, CanonInjectedTST: CanonType, PrevDecl: PrevPartial);
9090 Partial->setTemplateArgsAsWritten(TemplateArgs);
9091 SetNestedNameSpecifier(S&: *this, T: Partial, SS);
9092 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9093 Partial->setTemplateParameterListsInfo(
9094 Context, TPLists: TemplateParameterLists.drop_back(N: 1));
9095 }
9096
9097 if (!PrevPartial)
9098 ClassTemplate->AddPartialSpecialization(D: Partial, InsertToken);
9099 Specialization = Partial;
9100
9101 // If we are providing an explicit specialization of a member class
9102 // template specialization, make a note of that.
9103 if (isMemberSpecialization)
9104 Partial->setMemberSpecialization();
9105
9106 CheckTemplatePartialSpecialization(Partial);
9107 }
9108
9109 // C++ [temp.expl.spec]p6:
9110 // If a template, a member template or the member of a class template is
9111 // explicitly specialized then that specialization shall be declared
9112 // before the first use of that specialization that would cause an implicit
9113 // instantiation to take place, in every translation unit in which such a
9114 // use occurs; no diagnostic is required.
9115 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9116 bool Okay = false;
9117 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9118 // Is there any previous explicit specialization declaration?
9119 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9120 Okay = true;
9121 break;
9122 }
9123 }
9124
9125 if (!Okay) {
9126 SourceRange Range(TemplateNameLoc, RAngleLoc);
9127 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
9128 << Context.getCanonicalTagType(TD: Specialization) << Range;
9129
9130 Diag(Loc: PrevDecl->getPointOfInstantiation(),
9131 DiagID: diag::note_instantiation_required_here)
9132 << (PrevDecl->getTemplateSpecializationKind()
9133 != TSK_ImplicitInstantiation);
9134 return true;
9135 }
9136 }
9137
9138 // If this is not a friend, note that this is an explicit specialization.
9139 if (TUK != TagUseKind::Friend)
9140 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9141
9142 // Check that this isn't a redefinition of this specialization.
9143 if (TUK == TagUseKind::Definition) {
9144 RecordDecl *Def = Specialization->getDefinition();
9145 NamedDecl *Hidden = nullptr;
9146 bool HiddenDefVisible = false;
9147 if (Def && SkipBody &&
9148 isRedefinitionAllowedFor(D: Def, NewDefinitionLoc: TemplateNameLoc, Suggested: &Hidden,
9149 Visible&: HiddenDefVisible)) {
9150 SkipBody->ShouldSkip = true;
9151 SkipBody->Previous = Def;
9152 if (!HiddenDefVisible && Hidden)
9153 makeMergedDefinitionVisible(ND: Hidden);
9154 } else if (Def) {
9155 SourceRange Range(TemplateNameLoc, RAngleLoc);
9156 Diag(Loc: TemplateNameLoc, DiagID: diag::err_redefinition) << Specialization << Range;
9157 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
9158 Specialization->setInvalidDecl();
9159 return true;
9160 }
9161 }
9162
9163 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
9164 ProcessAPINotes(D: Specialization);
9165
9166 // Add alignment attributes if necessary; these attributes are checked when
9167 // the ASTContext lays out the structure.
9168 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9169 if (LangOpts.HLSL)
9170 Specialization->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
9171 AddAlignmentAttributesForRecord(RD: Specialization);
9172 AddMsStructLayoutForRecord(RD: Specialization);
9173 }
9174
9175 if (ModulePrivateLoc.isValid())
9176 Diag(Loc: Specialization->getLocation(), DiagID: diag::err_module_private_specialization)
9177 << (isPartialSpecialization? 1 : 0)
9178 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
9179
9180 // C++ [temp.expl.spec]p9:
9181 // A template explicit specialization is in the scope of the
9182 // namespace in which the template was defined.
9183 //
9184 // We actually implement this paragraph where we set the semantic
9185 // context (in the creation of the ClassTemplateSpecializationDecl),
9186 // but we also maintain the lexical context where the actual
9187 // definition occurs.
9188 Specialization->setLexicalDeclContext(CurContext);
9189
9190 // We may be starting the definition of this specialization.
9191 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9192 Specialization->startDefinition();
9193
9194 if (TUK == TagUseKind::Friend) {
9195 CanQualType CanonType = Context.getCanonicalTagType(TD: Specialization);
9196 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9197 Keyword: ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9198 QualifierLoc: SS.getWithLocInContext(Context),
9199 /*TemplateKeywordLoc=*/SourceLocation(), T: Name, TLoc: TemplateNameLoc,
9200 SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted, Canon: CanonType);
9201
9202 // Build the fully-sugared type for this class template
9203 // specialization as the user wrote in the specialization
9204 // itself. This means that we'll pretty-print the type retrieved
9205 // from the specialization's declaration the way that the user
9206 // actually wrote the specialization, rather than formatting the
9207 // name based on the "canonical" representation used to store the
9208 // template arguments in the specialization.
9209 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext,
9210 L: TemplateNameLoc,
9211 Friend: WrittenTy,
9212 /*FIXME:*/FriendL: KWLoc);
9213 Friend->setAccess(AS_public);
9214 CurContext->addDecl(D: Friend);
9215 } else {
9216 // Add the specialization into its lexical context, so that it can
9217 // be seen when iterating through the list of declarations in that
9218 // context. However, specializations are not found by name lookup.
9219 CurContext->addDecl(D: Specialization);
9220 }
9221
9222 if (SkipBody && SkipBody->ShouldSkip)
9223 return SkipBody->Previous;
9224
9225 Specialization->setInvalidDecl(Invalid);
9226 inferGslOwnerPointerAttribute(Record: Specialization);
9227 return Specialization;
9228}
9229
9230Decl *Sema::ActOnTemplateDeclarator(Scope *S,
9231 MultiTemplateParamsArg TemplateParameterLists,
9232 Declarator &D) {
9233 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9234 ActOnDocumentableDecl(D: NewDecl);
9235 return NewDecl;
9236}
9237
9238ConceptDecl *Sema::ActOnStartConceptDefinition(
9239 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9240 const IdentifierInfo *Name, SourceLocation NameLoc) {
9241 DeclContext *DC = CurContext;
9242
9243 if (!DC->getRedeclContext()->isFileContext()) {
9244 Diag(Loc: NameLoc,
9245 DiagID: diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9246 return nullptr;
9247 }
9248
9249 if (TemplateParameterLists.size() > 1) {
9250 Diag(Loc: NameLoc, DiagID: diag::err_concept_extra_headers);
9251 return nullptr;
9252 }
9253
9254 TemplateParameterList *Params = TemplateParameterLists.front();
9255
9256 if (Params->size() == 0) {
9257 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_parameters);
9258 return nullptr;
9259 }
9260
9261 // Ensure that the parameter pack, if present, is the last parameter in the
9262 // template.
9263 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9264 ParamEnd = Params->end();
9265 ParamIt != ParamEnd; ++ParamIt) {
9266 Decl const *Param = *ParamIt;
9267 if (Param->isParameterPack()) {
9268 if (++ParamIt == ParamEnd)
9269 break;
9270 Diag(Loc: Param->getLocation(),
9271 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
9272 return nullptr;
9273 }
9274 }
9275
9276 ConceptDecl *NewDecl =
9277 ConceptDecl::Create(C&: Context, DC, L: NameLoc, Name, Params);
9278
9279 if (NewDecl->hasAssociatedConstraints()) {
9280 // C++2a [temp.concept]p4:
9281 // A concept shall not have associated constraints.
9282 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_associated_constraints);
9283 NewDecl->setInvalidDecl();
9284 }
9285
9286 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9287 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9288 forRedeclarationInCurContext());
9289 LookupName(R&: Previous, S);
9290 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9291 /*AllowInlineNamespace*/ false);
9292
9293 // We cannot properly handle redeclarations until we parse the constraint
9294 // expression, so only inject the name if we are sure we are not redeclaring a
9295 // symbol
9296 if (Previous.empty())
9297 PushOnScopeChains(D: NewDecl, S, AddToContext: true);
9298
9299 return NewDecl;
9300}
9301
9302static bool RemoveLookupResult(LookupResult &R, NamedDecl *C) {
9303 bool Found = false;
9304 LookupResult::Filter F = R.makeFilter();
9305 while (F.hasNext()) {
9306 NamedDecl *D = F.next();
9307 if (D == C) {
9308 F.erase();
9309 Found = true;
9310 break;
9311 }
9312 }
9313 F.done();
9314 return Found;
9315}
9316
9317ConceptDecl *
9318Sema::ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
9319 Expr *ConstraintExpr,
9320 const ParsedAttributesView &Attrs) {
9321 assert(!C->hasDefinition() && "Concept already defined");
9322 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr)) {
9323 C->setInvalidDecl();
9324 return nullptr;
9325 }
9326 C->setDefinition(ConstraintExpr);
9327 ProcessDeclAttributeList(S, D: C, AttrList: Attrs);
9328
9329 // Check for conflicting previous declaration.
9330 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9331 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9332 forRedeclarationInCurContext());
9333 LookupName(R&: Previous, S);
9334 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9335 /*AllowInlineNamespace*/ false);
9336 bool WasAlreadyAdded = RemoveLookupResult(R&: Previous, C);
9337 bool AddToScope = true;
9338 CheckConceptRedefinition(NewDecl: C, Previous, AddToScope);
9339
9340 ActOnDocumentableDecl(D: C);
9341 if (!WasAlreadyAdded && AddToScope)
9342 PushOnScopeChains(D: C, S);
9343
9344 return C;
9345}
9346
9347void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
9348 LookupResult &Previous, bool &AddToScope) {
9349 AddToScope = true;
9350
9351 if (Previous.empty())
9352 return;
9353
9354 auto *OldConcept = dyn_cast<ConceptDecl>(Val: Previous.getRepresentativeDecl()->getUnderlyingDecl());
9355 if (!OldConcept) {
9356 auto *Old = Previous.getRepresentativeDecl();
9357 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_kind)
9358 << NewDecl->getDeclName();
9359 notePreviousDefinition(Old, New: NewDecl->getLocation());
9360 AddToScope = false;
9361 return;
9362 }
9363 // Check if we can merge with a concept declaration.
9364 bool IsSame = Context.isSameEntity(X: NewDecl, Y: OldConcept);
9365 if (!IsSame) {
9366 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_concept)
9367 << NewDecl->getDeclName();
9368 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9369 AddToScope = false;
9370 return;
9371 }
9372 if (hasReachableDefinition(D: OldConcept) &&
9373 IsRedefinitionInModule(New: NewDecl, Old: OldConcept)) {
9374 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition)
9375 << NewDecl->getDeclName();
9376 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9377 AddToScope = false;
9378 return;
9379 }
9380 if (!Previous.isSingleResult()) {
9381 // FIXME: we should produce an error in case of ambig and failed lookups.
9382 // Other decls (e.g. namespaces) also have this shortcoming.
9383 return;
9384 }
9385 // We unwrap canonical decl late to check for module visibility.
9386 Context.setPrimaryMergedDecl(D: NewDecl, Primary: OldConcept->getCanonicalDecl());
9387}
9388
9389bool Sema::CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc) {
9390 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Val: Concept);
9391 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9392 Diag(Loc, DiagID: diag::err_recursive_concept) << CE;
9393 Diag(Loc: CE->getLocation(), DiagID: diag::note_declared_at);
9394 CE->setInvalidDecl();
9395 return true;
9396 }
9397 // Concept template parameters don't have a definition and can't
9398 // be defined recursively.
9399 return false;
9400}
9401
9402/// \brief Strips various properties off an implicit instantiation
9403/// that has just been explicitly specialized.
9404static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9405 if (MinGW || (isa<FunctionDecl>(Val: D) &&
9406 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization()))
9407 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9408
9409 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D))
9410 FD->setInlineSpecified(false);
9411}
9412
9413/// Create an ExplicitInstantiationDecl to record source-location info for an
9414/// explicit template instantiation statement, and add it to \p CurContext.
9415///
9416/// For class templates / nested classes, the caller should build a
9417/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9418/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9419///
9420/// For function / variable templates, the caller should pass TypeAsWritten for
9421/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9422static void addExplicitInstantiationDecl(
9423 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9424 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9425 NestedNameSpecifierLoc QualifierLoc,
9426 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9427 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9428 auto *EID = ExplicitInstantiationDecl::Create(
9429 C&: Context, DC: CurContext, Specialization: Spec, ExternLoc, TemplateLoc, QualifierLoc,
9430 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9431 Context.addExplicitInstantiationDecl(Spec, EID);
9432 CurContext->addDecl(D: EID);
9433}
9434
9435/// Compute the diagnostic location for an explicit instantiation
9436// declaration or definition.
9437static SourceLocation
9438DiagLocForExplicitInstantiation(NamedDecl *D,
9439 SourceLocation PointOfInstantiation) {
9440 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(Spec: D))
9441 if (EID->getTemplateSpecializationKind() ==
9442 TSK_ExplicitInstantiationDefinition)
9443 return EID->getTemplateLoc();
9444
9445 // Explicit instantiations following a specialization have no effect and
9446 // hence no PointOfInstantiation. In that case, walk decl backwards
9447 // until a valid name loc is found.
9448 SourceLocation PrevDiagLoc = PointOfInstantiation;
9449 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9450 Prev = Prev->getPreviousDecl()) {
9451 PrevDiagLoc = Prev->getLocation();
9452 }
9453 assert(PrevDiagLoc.isValid() &&
9454 "Explicit instantiation without point of instantiation?");
9455 return PrevDiagLoc;
9456}
9457
9458bool
9459Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9460 TemplateSpecializationKind NewTSK,
9461 NamedDecl *PrevDecl,
9462 TemplateSpecializationKind PrevTSK,
9463 SourceLocation PrevPointOfInstantiation,
9464 bool &HasNoEffect) {
9465 HasNoEffect = false;
9466
9467 switch (NewTSK) {
9468 case TSK_Undeclared:
9469 case TSK_ImplicitInstantiation:
9470 assert(
9471 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9472 "previous declaration must be implicit!");
9473 return false;
9474
9475 case TSK_ExplicitSpecialization:
9476 switch (PrevTSK) {
9477 case TSK_Undeclared:
9478 case TSK_ExplicitSpecialization:
9479 // Okay, we're just specializing something that is either already
9480 // explicitly specialized or has merely been mentioned without any
9481 // instantiation.
9482 return false;
9483
9484 case TSK_ImplicitInstantiation:
9485 if (PrevPointOfInstantiation.isInvalid()) {
9486 // The declaration itself has not actually been instantiated, so it is
9487 // still okay to specialize it.
9488 StripImplicitInstantiation(
9489 D: PrevDecl, MinGW: Context.getTargetInfo().getTriple().isOSCygMing());
9490 return false;
9491 }
9492 // Fall through
9493 [[fallthrough]];
9494
9495 case TSK_ExplicitInstantiationDeclaration:
9496 case TSK_ExplicitInstantiationDefinition:
9497 assert((PrevTSK == TSK_ImplicitInstantiation ||
9498 PrevPointOfInstantiation.isValid()) &&
9499 "Explicit instantiation without point of instantiation?");
9500
9501 // C++ [temp.expl.spec]p6:
9502 // If a template, a member template or the member of a class template
9503 // is explicitly specialized then that specialization shall be declared
9504 // before the first use of that specialization that would cause an
9505 // implicit instantiation to take place, in every translation unit in
9506 // which such a use occurs; no diagnostic is required.
9507 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9508 // Is there any previous explicit specialization declaration?
9509 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization)
9510 return false;
9511 }
9512
9513 Diag(Loc: NewLoc, DiagID: diag::err_specialization_after_instantiation)
9514 << PrevDecl;
9515 Diag(Loc: PrevPointOfInstantiation, DiagID: diag::note_instantiation_required_here)
9516 << (PrevTSK != TSK_ImplicitInstantiation);
9517
9518 return true;
9519 }
9520 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9521
9522 case TSK_ExplicitInstantiationDeclaration:
9523 switch (PrevTSK) {
9524 case TSK_ExplicitInstantiationDeclaration:
9525 // This explicit instantiation declaration is redundant (that's okay).
9526 HasNoEffect = true;
9527 return false;
9528
9529 case TSK_Undeclared:
9530 case TSK_ImplicitInstantiation:
9531 // We're explicitly instantiating something that may have already been
9532 // implicitly instantiated; that's fine.
9533 return false;
9534
9535 case TSK_ExplicitSpecialization:
9536 // C++0x [temp.explicit]p4:
9537 // For a given set of template parameters, if an explicit instantiation
9538 // of a template appears after a declaration of an explicit
9539 // specialization for that template, the explicit instantiation has no
9540 // effect.
9541 HasNoEffect = true;
9542 return false;
9543
9544 case TSK_ExplicitInstantiationDefinition:
9545 // C++0x [temp.explicit]p10:
9546 // If an entity is the subject of both an explicit instantiation
9547 // declaration and an explicit instantiation definition in the same
9548 // translation unit, the definition shall follow the declaration.
9549 Diag(Loc: NewLoc,
9550 DiagID: diag::err_explicit_instantiation_declaration_after_definition);
9551
9552 // Explicit instantiations following a specialization have no effect and
9553 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9554 // until a valid name loc is found.
9555 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9556 DiagID: diag::note_explicit_instantiation_definition_here);
9557 HasNoEffect = true;
9558 return false;
9559 }
9560 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9561
9562 case TSK_ExplicitInstantiationDefinition:
9563 switch (PrevTSK) {
9564 case TSK_Undeclared:
9565 case TSK_ImplicitInstantiation:
9566 // We're explicitly instantiating something that may have already been
9567 // implicitly instantiated; that's fine.
9568 return false;
9569
9570 case TSK_ExplicitSpecialization:
9571 // C++ DR 259, C++0x [temp.explicit]p4:
9572 // For a given set of template parameters, if an explicit
9573 // instantiation of a template appears after a declaration of
9574 // an explicit specialization for that template, the explicit
9575 // instantiation has no effect.
9576 Diag(Loc: NewLoc, DiagID: diag::warn_explicit_instantiation_after_specialization)
9577 << PrevDecl;
9578 Diag(Loc: PrevDecl->getLocation(),
9579 DiagID: diag::note_previous_template_specialization);
9580 HasNoEffect = true;
9581 return false;
9582
9583 case TSK_ExplicitInstantiationDeclaration:
9584 // We're explicitly instantiating a definition for something for which we
9585 // were previously asked to suppress instantiations. That's fine.
9586
9587 // C++0x [temp.explicit]p4:
9588 // For a given set of template parameters, if an explicit instantiation
9589 // of a template appears after a declaration of an explicit
9590 // specialization for that template, the explicit instantiation has no
9591 // effect.
9592 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9593 // Is there any previous explicit specialization declaration?
9594 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9595 HasNoEffect = true;
9596 break;
9597 }
9598 }
9599
9600 return false;
9601
9602 case TSK_ExplicitInstantiationDefinition:
9603 // C++0x [temp.spec]p5:
9604 // For a given template and a given set of template-arguments,
9605 // - an explicit instantiation definition shall appear at most once
9606 // in a program,
9607
9608 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9609 Diag(Loc: NewLoc, DiagID: (getLangOpts().MSVCCompat)
9610 ? diag::ext_explicit_instantiation_duplicate
9611 : diag::err_explicit_instantiation_duplicate)
9612 << PrevDecl;
9613 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9614 DiagID: diag::note_previous_explicit_instantiation);
9615 HasNoEffect = true;
9616 return false;
9617 }
9618 }
9619
9620 llvm_unreachable("Missing specialization/instantiation case?");
9621}
9622
9623bool Sema::CheckDependentFunctionTemplateSpecialization(
9624 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9625 LookupResult &Previous) {
9626 // Remove anything from Previous that isn't a function template in
9627 // the correct context.
9628 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9629 LookupResult::Filter F = Previous.makeFilter();
9630 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9631 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9632 while (F.hasNext()) {
9633 NamedDecl *D = F.next()->getUnderlyingDecl();
9634 if (!isa<FunctionTemplateDecl>(Val: D)) {
9635 F.erase();
9636 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAFunctionTemplate, y&: D));
9637 continue;
9638 }
9639
9640 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9641 NS: D->getDeclContext()->getRedeclContext())) {
9642 F.erase();
9643 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAMemberOfEnclosing, y&: D));
9644 continue;
9645 }
9646 }
9647 F.done();
9648
9649 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9650 if (Previous.empty()) {
9651 NestedNameSpecifier FriendQualifier = FD->getQualifier();
9652 if (IsFriend && FriendQualifier.isDependent() &&
9653 FriendQualifier.getKind() == NestedNameSpecifier::Kind::Type &&
9654 FriendQualifier.getAsType()->getAs<TemplateSpecializationType>()) {
9655 FD->setDependentTemplateSpecialization(
9656 Context, Templates: Previous.asUnresolvedSet(), TemplateArgs: ExplicitTemplateArgs);
9657 return false;
9658 }
9659
9660 Diag(Loc: FD->getLocation(), DiagID: diag::err_dependent_function_template_spec_no_match)
9661 << IsFriend;
9662 for (auto &P : DiscardedCandidates)
9663 Diag(Loc: P.second->getLocation(),
9664 DiagID: diag::note_dependent_function_template_spec_discard_reason)
9665 << P.first << IsFriend;
9666 return true;
9667 }
9668
9669 FD->setDependentTemplateSpecialization(Context, Templates: Previous.asUnresolvedSet(),
9670 TemplateArgs: ExplicitTemplateArgs);
9671 return false;
9672}
9673
9674bool Sema::CheckFunctionTemplateSpecialization(
9675 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9676 LookupResult &Previous, bool QualifiedFriend) {
9677 // The set of function template specializations that could match this
9678 // explicit function template specialization.
9679 UnresolvedSet<8> Candidates;
9680 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9681 /*ForTakingAddress=*/false);
9682
9683 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9684 ConvertedTemplateArgs;
9685
9686 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9687 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9688 I != E; ++I) {
9689 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9690 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Ovl)) {
9691 // Only consider templates found within the same semantic lookup scope as
9692 // FD.
9693 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9694 NS: Ovl->getDeclContext()->getRedeclContext()))
9695 continue;
9696
9697 QualType FT = FD->getType();
9698 // C++11 [dcl.constexpr]p8:
9699 // A constexpr specifier for a non-static member function that is not
9700 // a constructor declares that member function to be const.
9701 //
9702 // When matching a constexpr member function template specialization
9703 // against the primary template, we don't yet know whether the
9704 // specialization has an implicit 'const' (because we don't know whether
9705 // it will be a static member function until we know which template it
9706 // specializes). This rule was removed in C++14.
9707 if (auto *NewMD = dyn_cast<CXXMethodDecl>(Val: FD);
9708 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9709 !isa<CXXConstructorDecl, CXXDestructorDecl>(Val: NewMD)) {
9710 auto *OldMD = dyn_cast<CXXMethodDecl>(Val: FunTmpl->getTemplatedDecl());
9711 if (OldMD && OldMD->isConst()) {
9712 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9713 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9714 EPI.TypeQuals.addConst();
9715 FT = Context.getFunctionType(ResultTy: FPT->getReturnType(),
9716 Args: FPT->getParamTypes(), EPI);
9717 }
9718 }
9719
9720 TemplateArgumentListInfo Args;
9721 if (ExplicitTemplateArgs)
9722 Args = *ExplicitTemplateArgs;
9723
9724 // C++ [temp.expl.spec]p11:
9725 // A trailing template-argument can be left unspecified in the
9726 // template-id naming an explicit function template specialization
9727 // provided it can be deduced from the function argument type.
9728 // Perform template argument deduction to determine whether we may be
9729 // specializing this template.
9730 // FIXME: It is somewhat wasteful to build
9731 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9732 FunctionDecl *Specialization = nullptr;
9733 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9734 FunctionTemplate: cast<FunctionTemplateDecl>(Val: FunTmpl->getFirstDecl()),
9735 ExplicitTemplateArgs: ExplicitTemplateArgs ? &Args : nullptr, ArgFunctionType: FT, Specialization, Info);
9736 TDK != TemplateDeductionResult::Success) {
9737 // Template argument deduction failed; record why it failed, so
9738 // that we can provide nifty diagnostics.
9739 FailedCandidates.addCandidate().set(
9740 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9741 Info: MakeDeductionFailureInfo(Context, TDK, Info));
9742 (void)TDK;
9743 continue;
9744 }
9745
9746 // Target attributes are part of the cuda function signature, so
9747 // the deduced template's cuda target must match that of the
9748 // specialization. Given that C++ template deduction does not
9749 // take target attributes into account, we reject candidates
9750 // here that have a different target.
9751 if (LangOpts.CUDA &&
9752 CUDA().IdentifyTarget(D: Specialization,
9753 /* IgnoreImplicitHDAttr = */ true) !=
9754 CUDA().IdentifyTarget(D: FD, /* IgnoreImplicitHDAttr = */ true)) {
9755 FailedCandidates.addCandidate().set(
9756 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9757 Info: MakeDeductionFailureInfo(
9758 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
9759 continue;
9760 }
9761
9762 // Record this candidate.
9763 if (ExplicitTemplateArgs)
9764 ConvertedTemplateArgs[Specialization] = std::move(Args);
9765 Candidates.addDecl(D: Specialization, AS: I.getAccess());
9766 }
9767 }
9768
9769 // For a qualified friend declaration (with no explicit marker to indicate
9770 // that a template specialization was intended), note all (template and
9771 // non-template) candidates.
9772 if (QualifiedFriend && Candidates.empty()) {
9773 Diag(Loc: FD->getLocation(), DiagID: diag::err_qualified_friend_no_match)
9774 << FD->getDeclName() << FDLookupContext;
9775 // FIXME: We should form a single candidate list and diagnose all
9776 // candidates at once, to get proper sorting and limiting.
9777 for (auto *OldND : Previous) {
9778 if (auto *OldFD = dyn_cast<FunctionDecl>(Val: OldND->getUnderlyingDecl()))
9779 NoteOverloadCandidate(Found: OldND, Fn: OldFD, RewriteKind: CRK_None, DestType: FD->getType(), TakingAddress: false);
9780 }
9781 FailedCandidates.NoteCandidates(S&: *this, Loc: FD->getLocation());
9782 return true;
9783 }
9784
9785 // Find the most specialized function template.
9786 UnresolvedSetIterator Result = getMostSpecialized(
9787 SBegin: Candidates.begin(), SEnd: Candidates.end(), FailedCandidates, Loc: FD->getLocation(),
9788 NoneDiag: PDiag(DiagID: diag::err_function_template_spec_no_match) << FD->getDeclName(),
9789 AmbigDiag: PDiag(DiagID: diag::err_function_template_spec_ambiguous)
9790 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9791 CandidateDiag: PDiag(DiagID: diag::note_function_template_spec_matched));
9792
9793 if (Result == Candidates.end())
9794 return true;
9795
9796 // Ignore access information; it doesn't figure into redeclaration checking.
9797 FunctionDecl *Specialization = cast<FunctionDecl>(Val: *Result);
9798
9799 if (const auto *PT = Specialization->getPrimaryTemplate();
9800 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9801 auto Message = DSA->getMessage();
9802 Diag(Loc: FD->getLocation(), DiagID: diag::warn_invalid_specialization)
9803 << PT << !Message.empty() << Message;
9804 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
9805 }
9806
9807 // C++23 [except.spec]p13:
9808 // An exception specification is considered to be needed when:
9809 // - [...]
9810 // - the exception specification is compared to that of another declaration
9811 // (e.g., an explicit specialization or an overriding virtual function);
9812 // - [...]
9813 //
9814 // The exception specification of a defaulted function is evaluated as
9815 // described above only when needed; similarly, the noexcept-specifier of a
9816 // specialization of a function template or member function of a class
9817 // template is instantiated only when needed.
9818 //
9819 // The standard doesn't specify what the "comparison with another declaration"
9820 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9821 // not state which properties of an explicit specialization must match the
9822 // primary template.
9823 //
9824 // We assume that an explicit specialization must correspond with (per
9825 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9826 // the declaration produced by substitution into the function template.
9827 //
9828 // Since the determination whether two function declarations correspond does
9829 // not consider exception specification, we only need to instantiate it once
9830 // we determine the primary template when comparing types per
9831 // [basic.link]p11.1.
9832 auto *SpecializationFPT =
9833 Specialization->getType()->castAs<FunctionProtoType>();
9834 // If the function has a dependent exception specification, resolve it after
9835 // we have selected the primary template so we can check whether it matches.
9836 if (getLangOpts().CPlusPlus17 &&
9837 isUnresolvedExceptionSpec(ESpecType: SpecializationFPT->getExceptionSpecType()) &&
9838 !ResolveExceptionSpec(Loc: FD->getLocation(), FPT: SpecializationFPT))
9839 return true;
9840
9841 FunctionTemplateSpecializationInfo *SpecInfo
9842 = Specialization->getTemplateSpecializationInfo();
9843 assert(SpecInfo && "Function template specialization info missing?");
9844
9845 // Note: do not overwrite location info if previous template
9846 // specialization kind was explicit.
9847 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9848 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9849 Specialization->setLocation(FD->getLocation());
9850 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9851 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9852 // function can differ from the template declaration with respect to
9853 // the constexpr specifier.
9854 // FIXME: We need an update record for this AST mutation.
9855 // FIXME: What if there are multiple such prior declarations (for instance,
9856 // from different modules)?
9857 Specialization->setConstexprKind(FD->getConstexprKind());
9858 }
9859
9860 // FIXME: Check if the prior specialization has a point of instantiation.
9861 // If so, we have run afoul of .
9862
9863 // If this is a friend declaration, then we're not really declaring
9864 // an explicit specialization.
9865 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9866
9867 // Check the scope of this explicit specialization.
9868 if (!isFriend &&
9869 CheckTemplateSpecializationScope(S&: *this,
9870 Specialized: Specialization->getPrimaryTemplate(),
9871 PrevDecl: Specialization, Loc: FD->getLocation(),
9872 IsPartialSpecialization: false))
9873 return true;
9874
9875 // C++ [temp.expl.spec]p6:
9876 // If a template, a member template or the member of a class template is
9877 // explicitly specialized then that specialization shall be declared
9878 // before the first use of that specialization that would cause an implicit
9879 // instantiation to take place, in every translation unit in which such a
9880 // use occurs; no diagnostic is required.
9881 bool HasNoEffect = false;
9882 if (!isFriend &&
9883 CheckSpecializationInstantiationRedecl(NewLoc: FD->getLocation(),
9884 NewTSK: TSK_ExplicitSpecialization,
9885 PrevDecl: Specialization,
9886 PrevTSK: SpecInfo->getTemplateSpecializationKind(),
9887 PrevPointOfInstantiation: SpecInfo->getPointOfInstantiation(),
9888 HasNoEffect))
9889 return true;
9890
9891 // Mark the prior declaration as an explicit specialization, so that later
9892 // clients know that this is an explicit specialization.
9893 // A dependent friend specialization which has a definition should be treated
9894 // as explicit specialization, despite being invalid.
9895 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9896 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9897 // Since explicit specializations do not inherit '=delete' from their
9898 // primary function template - check if the 'specialization' that was
9899 // implicitly generated (during template argument deduction for partial
9900 // ordering) from the most specialized of all the function templates that
9901 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9902 // first check that it was implicitly generated during template argument
9903 // deduction by making sure it wasn't referenced, and then reset the deleted
9904 // flag to not-deleted, so that we can inherit that information from 'FD'.
9905 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9906 !Specialization->getCanonicalDecl()->isReferenced()) {
9907 // FIXME: This assert will not hold in the presence of modules.
9908 assert(
9909 Specialization->getCanonicalDecl() == Specialization &&
9910 "This must be the only existing declaration of this specialization");
9911 // FIXME: We need an update record for this AST mutation.
9912 Specialization->setDeletedAsWritten(D: false);
9913 }
9914 // FIXME: We need an update record for this AST mutation.
9915 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9916 MarkUnusedFileScopedDecl(D: Specialization);
9917 }
9918
9919 // Turn the given function declaration into a function template
9920 // specialization, with the template arguments from the previous
9921 // specialization.
9922 // Take copies of (semantic and syntactic) template argument lists.
9923 TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
9924 Context, Args: Specialization->getTemplateSpecializationArgs()->asArray());
9925 FD->setFunctionTemplateSpecialization(
9926 Template: Specialization->getPrimaryTemplate(), TemplateArgs: TemplArgs, /*InsertToken=*/{},
9927 TSK: SpecInfo->getTemplateSpecializationKind(),
9928 TemplateArgsAsWritten: ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9929
9930 // A function template specialization inherits the target attributes
9931 // of its template. (We require the attributes explicitly in the
9932 // code to match, but a template may have implicit attributes by
9933 // virtue e.g. of being constexpr, and it passes these implicit
9934 // attributes on to its specializations.)
9935 if (LangOpts.CUDA)
9936 CUDA().inheritTargetAttrs(FD, TD: *Specialization->getPrimaryTemplate());
9937
9938 // The "previous declaration" for this function template specialization is
9939 // the prior function template specialization.
9940 Previous.clear();
9941 Previous.addDecl(D: Specialization);
9942 return false;
9943}
9944
9945bool
9946Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9947 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9948 "Only for non-template members");
9949
9950 // Try to find the member we are instantiating.
9951 NamedDecl *FoundInstantiation = nullptr;
9952 NamedDecl *Instantiation = nullptr;
9953 NamedDecl *InstantiatedFrom = nullptr;
9954 MemberSpecializationInfo *MSInfo = nullptr;
9955
9956 if (Previous.empty()) {
9957 // Nowhere to look anyway.
9958 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Member)) {
9959 UnresolvedSet<8> Candidates;
9960 for (NamedDecl *Candidate : Previous) {
9961 auto *Method = dyn_cast<CXXMethodDecl>(Val: Candidate->getUnderlyingDecl());
9962 // Ignore any candidates that aren't member functions.
9963 if (!Method)
9964 continue;
9965
9966 QualType Adjusted = Function->getType();
9967 if (!hasExplicitCallingConv(T: Adjusted))
9968 Adjusted = adjustCCAndNoReturn(ArgFunctionType: Adjusted, FunctionType: Method->getType());
9969 // Ignore any candidates with the wrong type.
9970 // This doesn't handle deduced return types, but both function
9971 // declarations should be undeduced at this point.
9972 // FIXME: The exception specification should probably be ignored when
9973 // comparing the types.
9974 if (!Context.hasSameType(T1: Adjusted, T2: Method->getType()))
9975 continue;
9976
9977 // Ignore any candidates with unsatisfied constraints.
9978 if (ConstraintSatisfaction Satisfaction;
9979 Method->getTrailingRequiresClause() &&
9980 (CheckFunctionConstraints(FD: Method, Satisfaction,
9981 /*UsageLoc=*/Member->getLocation(),
9982 /*ForOverloadResolution=*/true) ||
9983 !Satisfaction.IsSatisfied))
9984 continue;
9985
9986 Candidates.addDecl(D: Candidate);
9987 }
9988
9989 // If we have no viable candidates left after filtering, we are done.
9990 if (Candidates.empty())
9991 return false;
9992
9993 // Find the function that is more constrained than every other function it
9994 // has been compared to.
9995 UnresolvedSetIterator Best = Candidates.begin();
9996 CXXMethodDecl *BestMethod = nullptr;
9997 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9998 I != E; ++I) {
9999 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
10000 if (I == Best ||
10001 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) == Method) {
10002 Best = I;
10003 BestMethod = Method;
10004 }
10005 }
10006
10007 FoundInstantiation = *Best;
10008 Instantiation = BestMethod;
10009 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
10010 MSInfo = BestMethod->getMemberSpecializationInfo();
10011
10012 // Make sure the best candidate is more constrained than all of the others.
10013 bool Ambiguous = false;
10014 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
10015 I != E; ++I) {
10016 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
10017 if (I != Best &&
10018 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) != BestMethod) {
10019 Ambiguous = true;
10020 break;
10021 }
10022 }
10023
10024 if (Ambiguous) {
10025 Diag(Loc: Member->getLocation(), DiagID: diag::err_function_member_spec_ambiguous)
10026 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
10027 for (NamedDecl *Candidate : Candidates) {
10028 Candidate = Candidate->getUnderlyingDecl();
10029 Diag(Loc: Candidate->getLocation(), DiagID: diag::note_function_member_spec_matched)
10030 << Candidate;
10031 }
10032 return true;
10033 }
10034 } else if (isa<VarDecl>(Val: Member)) {
10035 VarDecl *PrevVar;
10036 if (Previous.isSingleResult() &&
10037 (PrevVar = dyn_cast<VarDecl>(Val: Previous.getFoundDecl())))
10038 if (PrevVar->isStaticDataMember()) {
10039 FoundInstantiation = Previous.getRepresentativeDecl();
10040 Instantiation = PrevVar;
10041 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
10042 MSInfo = PrevVar->getMemberSpecializationInfo();
10043 }
10044 } else if (isa<RecordDecl>(Val: Member)) {
10045 CXXRecordDecl *PrevRecord;
10046 if (Previous.isSingleResult() &&
10047 (PrevRecord = dyn_cast<CXXRecordDecl>(Val: Previous.getFoundDecl()))) {
10048 FoundInstantiation = Previous.getRepresentativeDecl();
10049 Instantiation = PrevRecord;
10050 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
10051 MSInfo = PrevRecord->getMemberSpecializationInfo();
10052 }
10053 } else if (isa<EnumDecl>(Val: Member)) {
10054 EnumDecl *PrevEnum;
10055 if (Previous.isSingleResult() &&
10056 (PrevEnum = dyn_cast<EnumDecl>(Val: Previous.getFoundDecl()))) {
10057 FoundInstantiation = Previous.getRepresentativeDecl();
10058 Instantiation = PrevEnum;
10059 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
10060 MSInfo = PrevEnum->getMemberSpecializationInfo();
10061 }
10062 }
10063
10064 if (!Instantiation) {
10065 // There is no previous declaration that matches. Since member
10066 // specializations are always out-of-line, the caller will complain about
10067 // this mismatch later.
10068 return false;
10069 }
10070
10071 // A member specialization in a friend declaration isn't really declaring
10072 // an explicit specialization, just identifying a specific (possibly implicit)
10073 // specialization. Don't change the template specialization kind.
10074 //
10075 // FIXME: Is this really valid? Other compilers reject.
10076 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10077 // Preserve instantiation information.
10078 if (InstantiatedFrom && isa<CXXMethodDecl>(Val: Member)) {
10079 cast<CXXMethodDecl>(Val: Member)->setInstantiationOfMemberFunction(
10080 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom),
10081 TSK: cast<CXXMethodDecl>(Val: Instantiation)->getTemplateSpecializationKind());
10082 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Val: Member)) {
10083 cast<CXXRecordDecl>(Val: Member)->setInstantiationOfMemberClass(
10084 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom),
10085 TSK: cast<CXXRecordDecl>(Val: Instantiation)->getTemplateSpecializationKind());
10086 }
10087
10088 Previous.clear();
10089 Previous.addDecl(D: FoundInstantiation);
10090 return false;
10091 }
10092
10093 // Make sure that this is a specialization of a member.
10094 if (!InstantiatedFrom) {
10095 Diag(Loc: Member->getLocation(), DiagID: diag::err_spec_member_not_instantiated)
10096 << Member;
10097 Diag(Loc: Instantiation->getLocation(), DiagID: diag::note_specialized_decl);
10098 return true;
10099 }
10100
10101 // C++ [temp.expl.spec]p6:
10102 // If a template, a member template or the member of a class template is
10103 // explicitly specialized then that specialization shall be declared
10104 // before the first use of that specialization that would cause an implicit
10105 // instantiation to take place, in every translation unit in which such a
10106 // use occurs; no diagnostic is required.
10107 assert(MSInfo && "Member specialization info missing?");
10108
10109 bool HasNoEffect = false;
10110 if (CheckSpecializationInstantiationRedecl(NewLoc: Member->getLocation(),
10111 NewTSK: TSK_ExplicitSpecialization,
10112 PrevDecl: Instantiation,
10113 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10114 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10115 HasNoEffect))
10116 return true;
10117
10118 // Check the scope of this explicit specialization.
10119 if (CheckTemplateSpecializationScope(S&: *this,
10120 Specialized: InstantiatedFrom,
10121 PrevDecl: Instantiation, Loc: Member->getLocation(),
10122 IsPartialSpecialization: false))
10123 return true;
10124
10125 // Note that this member specialization is an "instantiation of" the
10126 // corresponding member of the original template.
10127 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Val: Member)) {
10128 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Val: Instantiation);
10129 if (InstantiationFunction->getTemplateSpecializationKind() ==
10130 TSK_ImplicitInstantiation) {
10131 // Explicit specializations of member functions of class templates do not
10132 // inherit '=delete' from the member function they are specializing.
10133 if (InstantiationFunction->isDeleted()) {
10134 // FIXME: This assert will not hold in the presence of modules.
10135 assert(InstantiationFunction->getCanonicalDecl() ==
10136 InstantiationFunction);
10137 // FIXME: We need an update record for this AST mutation.
10138 InstantiationFunction->setDeletedAsWritten(D: false);
10139 }
10140 }
10141
10142 MemberFunction->setInstantiationOfMemberFunction(
10143 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10144 } else if (auto *MemberVar = dyn_cast<VarDecl>(Val: Member)) {
10145 MemberVar->setInstantiationOfStaticDataMember(
10146 VD: cast<VarDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10147 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
10148 MemberClass->setInstantiationOfMemberClass(
10149 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10150 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Val: Member)) {
10151 MemberEnum->setInstantiationOfMemberEnum(
10152 ED: cast<EnumDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10153 } else {
10154 llvm_unreachable("unknown member specialization kind");
10155 }
10156
10157 // Save the caller the trouble of having to figure out which declaration
10158 // this specialization matches.
10159 Previous.clear();
10160 Previous.addDecl(D: FoundInstantiation);
10161 return false;
10162}
10163
10164/// Complete the explicit specialization of a member of a class template by
10165/// updating the instantiated member to be marked as an explicit specialization.
10166///
10167/// \param OrigD The member declaration instantiated from the template.
10168/// \param Loc The location of the explicit specialization of the member.
10169template<typename DeclT>
10170static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10171 SourceLocation Loc) {
10172 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10173 return;
10174
10175 // FIXME: Inform AST mutation listeners of this AST mutation.
10176 // FIXME: If there are multiple in-class declarations of the member (from
10177 // multiple modules, or a declaration and later definition of a member type),
10178 // should we update all of them?
10179 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10180 OrigD->setLocation(Loc);
10181}
10182
10183void Sema::CompleteMemberSpecialization(NamedDecl *Member,
10184 LookupResult &Previous) {
10185 NamedDecl *Instantiation = cast<NamedDecl>(Val: Member->getCanonicalDecl());
10186 if (Instantiation == Member)
10187 return;
10188
10189 if (auto *Function = dyn_cast<CXXMethodDecl>(Val: Instantiation))
10190 completeMemberSpecializationImpl(S&: *this, OrigD: Function, Loc: Member->getLocation());
10191 else if (auto *Var = dyn_cast<VarDecl>(Val: Instantiation))
10192 completeMemberSpecializationImpl(S&: *this, OrigD: Var, Loc: Member->getLocation());
10193 else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: Instantiation))
10194 completeMemberSpecializationImpl(S&: *this, OrigD: Record, Loc: Member->getLocation());
10195 else if (auto *Enum = dyn_cast<EnumDecl>(Val: Instantiation))
10196 completeMemberSpecializationImpl(S&: *this, OrigD: Enum, Loc: Member->getLocation());
10197 else
10198 llvm_unreachable("unknown member specialization kind");
10199}
10200
10201/// Check the scope of an explicit instantiation.
10202///
10203/// \returns true if a serious error occurs, false otherwise.
10204static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
10205 SourceLocation InstLoc,
10206 bool WasQualifiedName) {
10207 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
10208 DeclContext *CurContext = S.CurContext->getRedeclContext();
10209
10210 if (CurContext->isRecord()) {
10211 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_in_class)
10212 << D;
10213 return true;
10214 }
10215
10216 // C++11 [temp.explicit]p3:
10217 // An explicit instantiation shall appear in an enclosing namespace of its
10218 // template. If the name declared in the explicit instantiation is an
10219 // unqualified name, the explicit instantiation shall appear in the
10220 // namespace where its template is declared or, if that namespace is inline
10221 // (7.3.1), any namespace from its enclosing namespace set.
10222 //
10223 // This is DR275, which we do not retroactively apply to C++98/03.
10224 if (WasQualifiedName) {
10225 if (CurContext->Encloses(DC: OrigContext))
10226 return false;
10227 } else {
10228 if (CurContext->InEnclosingNamespaceSetOf(NS: OrigContext))
10229 return false;
10230 }
10231
10232 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: OrigContext)) {
10233 if (WasQualifiedName)
10234 S.Diag(Loc: InstLoc,
10235 DiagID: S.getLangOpts().CPlusPlus11?
10236 diag::err_explicit_instantiation_out_of_scope :
10237 diag::warn_explicit_instantiation_out_of_scope_0x)
10238 << D << NS;
10239 else
10240 S.Diag(Loc: InstLoc,
10241 DiagID: S.getLangOpts().CPlusPlus11?
10242 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10243 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10244 << D << NS;
10245 } else
10246 S.Diag(Loc: InstLoc,
10247 DiagID: S.getLangOpts().CPlusPlus11?
10248 diag::err_explicit_instantiation_must_be_global :
10249 diag::warn_explicit_instantiation_must_be_global_0x)
10250 << D;
10251 S.Diag(Loc: D->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10252 return false;
10253}
10254
10255/// Common checks for whether an explicit instantiation of \p D is valid.
10256static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
10257 SourceLocation InstLoc,
10258 bool WasQualifiedName,
10259 TemplateSpecializationKind TSK) {
10260 // C++ [temp.explicit]p13:
10261 // An explicit instantiation declaration shall not name a specialization of
10262 // a template with internal linkage.
10263 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10264 D->getFormalLinkage() == Linkage::Internal) {
10265 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_internal_linkage) << D;
10266 return true;
10267 }
10268
10269 // C++11 [temp.explicit]p3: [DR 275]
10270 // An explicit instantiation shall appear in an enclosing namespace of its
10271 // template.
10272 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10273 return true;
10274
10275 return false;
10276}
10277
10278/// Determine whether the given scope specifier has a template-id in it.
10279static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
10280 // C++11 [temp.explicit]p3:
10281 // If the explicit instantiation is for a member function, a member class
10282 // or a static data member of a class template specialization, the name of
10283 // the class template specialization in the qualified-id for the member
10284 // name shall be a simple-template-id.
10285 //
10286 // C++98 has the same restriction, just worded differently.
10287 for (NestedNameSpecifier NNS = SS.getScopeRep();
10288 NNS.getKind() == NestedNameSpecifier::Kind::Type;
10289 /**/) {
10290 const Type *T = NNS.getAsType();
10291 if (isa<TemplateSpecializationType>(Val: T))
10292 return true;
10293 NNS = T->getPrefix();
10294 }
10295 return false;
10296}
10297
10298/// Make a dllexport or dllimport attr on a class template specialization take
10299/// effect.
10300static void dllExportImportClassTemplateSpecialization(
10301 Sema &S, ClassTemplateSpecializationDecl *Def) {
10302 auto *A = cast_or_null<InheritableAttr>(Val: getDLLAttr(D: Def));
10303 assert(A && "dllExportImportClassTemplateSpecialization called "
10304 "on Def without dllexport or dllimport");
10305
10306 // We reject explicit instantiations in class scope, so there should
10307 // never be any delayed exported classes to worry about.
10308 assert(S.DelayedDllExportClasses.empty() &&
10309 "delayed exports present at explicit instantiation");
10310 S.checkClassLevelDLLAttribute(Class: Def);
10311
10312 // Propagate attribute to base class templates.
10313 for (auto &B : Def->bases()) {
10314 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10315 Val: B.getType()->getAsCXXRecordDecl()))
10316 S.propagateDLLAttrToBaseClassTemplate(Class: Def, ClassAttr: A, BaseTemplateSpec: BT, BaseLoc: B.getBeginLoc());
10317 }
10318
10319 S.referenceDLLExportedClassMethods();
10320}
10321
10322DeclResult Sema::ActOnExplicitInstantiation(
10323 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10324 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10325 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10326 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10327 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10328 // Find the class template we're specializing
10329 TemplateName Name = TemplateD.get();
10330 TemplateDecl *TD = Name.getAsTemplateDecl();
10331 // Check that the specialization uses the same tag kind as the
10332 // original template.
10333 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10334 assert(Kind != TagTypeKind::Enum &&
10335 "Invalid enum tag in class template explicit instantiation!");
10336
10337 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: TD);
10338
10339 if (!ClassTemplate) {
10340 NonTagKind NTK = getNonTagTypeDeclKind(D: TD, TTK: Kind);
10341 Diag(Loc: TemplateNameLoc, DiagID: diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10342 Diag(Loc: TD->getLocation(), DiagID: diag::note_previous_use);
10343 return true;
10344 }
10345
10346 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(),
10347 NewTag: Kind, /*isDefinition*/false, NewTagLoc: KWLoc,
10348 Name: ClassTemplate->getIdentifier())) {
10349 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
10350 << ClassTemplate
10351 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
10352 Code: ClassTemplate->getTemplatedDecl()->getKindName());
10353 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
10354 DiagID: diag::note_previous_use);
10355 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10356 }
10357
10358 // C++0x [temp.explicit]p2:
10359 // There are two forms of explicit instantiation: an explicit instantiation
10360 // definition and an explicit instantiation declaration. An explicit
10361 // instantiation declaration begins with the extern keyword. [...]
10362 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10363 ? TSK_ExplicitInstantiationDefinition
10364 : TSK_ExplicitInstantiationDeclaration;
10365
10366 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10367 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10368 // Check for dllexport class template instantiation declarations,
10369 // except for MinGW mode.
10370 for (const ParsedAttr &AL : Attr) {
10371 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10372 Diag(Loc: ExternLoc,
10373 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10374 Diag(Loc: AL.getLoc(), DiagID: diag::note_attribute);
10375 break;
10376 }
10377 }
10378
10379 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10380 Diag(Loc: ExternLoc,
10381 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10382 Diag(Loc: A->getLocation(), DiagID: diag::note_attribute);
10383 }
10384 }
10385
10386 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10387 // instantiation declarations for most purposes.
10388 bool DLLImportExplicitInstantiationDef = false;
10389 if (TSK == TSK_ExplicitInstantiationDefinition &&
10390 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10391 // Check for dllimport class template instantiation definitions.
10392 bool DLLImport =
10393 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10394 for (const ParsedAttr &AL : Attr) {
10395 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10396 DLLImport = true;
10397 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10398 // dllexport trumps dllimport here.
10399 DLLImport = false;
10400 break;
10401 }
10402 }
10403 if (DLLImport) {
10404 TSK = TSK_ExplicitInstantiationDeclaration;
10405 DLLImportExplicitInstantiationDef = true;
10406 }
10407 }
10408
10409 // Translate the parser's template argument list in our AST format.
10410 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10411 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10412
10413 // Check that the template argument list is well-formed for this
10414 // template.
10415 CheckTemplateArgumentInfo CTAI;
10416 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
10417 /*DefaultArgs=*/{}, PartialTemplateArgs: false, CTAI,
10418 /*UpdateArgsWithConversions=*/true,
10419 /*ConstraintsNotSatisfied=*/nullptr))
10420 return true;
10421
10422 // Find the class template specialization declaration that
10423 // corresponds to these arguments.
10424 llvm::FoldingSetInsertToken InsertToken;
10425 ClassTemplateSpecializationDecl *PrevDecl =
10426 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertToken);
10427
10428 TemplateSpecializationKind PrevDecl_TSK
10429 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10430
10431 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10432 Context.getTargetInfo().getTriple().isOSCygMing()) {
10433 // Check for dllexport class template instantiation definitions in MinGW
10434 // mode, if a previous declaration of the instantiation was seen.
10435 for (const ParsedAttr &AL : Attr) {
10436 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10437 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10438 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attr_dllexport_explicit_inst_def);
10439 } else {
10440 Diag(Loc: AL.getLoc(),
10441 DiagID: diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10442 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_prev_decl_missing_dllexport);
10443 }
10444 break;
10445 }
10446 }
10447 }
10448
10449 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10450 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10451 llvm::none_of(Range: Attr, P: [](const ParsedAttr &AL) {
10452 return AL.getKind() == ParsedAttr::AT_DLLExport;
10453 })) {
10454 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10455 Diag(Loc: TemplateLoc, DiagID: diag::warn_dllexport_on_decl_ignored);
10456 Diag(Loc: DEA->getLoc(), DiagID: diag::note_dllexport_on_decl);
10457 }
10458 }
10459
10460 if (CheckExplicitInstantiation(S&: *this, D: ClassTemplate, InstLoc: TemplateNameLoc,
10461 WasQualifiedName: SS.isSet(), TSK))
10462 return true;
10463
10464 ClassTemplateSpecializationDecl *Specialization = nullptr;
10465
10466 bool HasNoEffect = false;
10467 if (PrevDecl) {
10468 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateNameLoc, NewTSK: TSK,
10469 PrevDecl, PrevTSK: PrevDecl_TSK,
10470 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
10471 HasNoEffect))
10472 return PrevDecl;
10473
10474 // Even though HasNoEffect == true means that this explicit instantiation
10475 // has no effect on semantics, we go on to put its syntax in the AST.
10476
10477 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10478 PrevDecl_TSK == TSK_Undeclared) {
10479 // Since the only prior class template specialization with these
10480 // arguments was referenced but not declared, reuse that
10481 // declaration node as our own, updating the source location
10482 // for the template name to reflect our new declaration.
10483 // (Other source locations will be updated later.)
10484 Specialization = PrevDecl;
10485 Specialization->setLocation(TemplateNameLoc);
10486 PrevDecl = nullptr;
10487 }
10488
10489 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10490 DLLImportExplicitInstantiationDef) {
10491 // The new specialization might add a dllimport attribute.
10492 HasNoEffect = false;
10493 }
10494 }
10495
10496 if (!Specialization) {
10497 // Create a new class template specialization declaration node for
10498 // this explicit specialization.
10499 Specialization = ClassTemplateSpecializationDecl::Create(
10500 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
10501 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
10502 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
10503
10504 // A MSInheritanceAttr attached to the previous declaration must be
10505 // propagated to the new node prior to instantiation.
10506 if (PrevDecl) {
10507 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10508 auto *Clone = A->clone(C&: getASTContext());
10509 Clone->setInherited(true);
10510 Specialization->addAttr(A: Clone);
10511 Consumer.AssignInheritanceModel(RD: Specialization);
10512 }
10513 }
10514
10515 if (!HasNoEffect && !PrevDecl) {
10516 // Insert the new specialization.
10517 ClassTemplate->AddSpecialization(D: Specialization, InsertToken);
10518 }
10519 }
10520
10521 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10522
10523 // Set source locations for keywords.
10524 Specialization->setExternKeywordLoc(ExternLoc);
10525 Specialization->setTemplateKeywordLoc(TemplateLoc);
10526 Specialization->setBraceRange(SourceRange());
10527
10528 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10529 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
10530 ProcessAPINotes(D: Specialization);
10531
10532 // Add the explicit instantiation into its lexical context. However,
10533 // since explicit instantiations are never found by name lookup, we
10534 // just put it into the declaration context directly.
10535 Specialization->setLexicalDeclContext(CurContext);
10536 CurContext->addDecl(D: Specialization);
10537
10538 // Syntax is now OK, so return if it has no other effect on semantics.
10539 if (HasNoEffect) {
10540 // Set the template specialization kind.
10541 Specialization->setTemplateSpecializationKind(TSK);
10542
10543 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
10544 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10545 Keyword: KW, ElaboratedKeywordLoc: KWLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: SourceLocation(), T: Name,
10546 TLoc: TemplateNameLoc, SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted,
10547 Canon: Context.getCanonicalTagType(TD: Specialization));
10548 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
10549 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10550 NameLoc: TemplateNameLoc, TypeAsWritten: TSI, TSK);
10551 return Specialization;
10552 }
10553
10554 // C++ [temp.explicit]p3:
10555 // A definition of a class template or class member template
10556 // shall be in scope at the point of the explicit instantiation of
10557 // the class template or class member template.
10558 //
10559 // This check comes when we actually try to perform the
10560 // instantiation.
10561 ClassTemplateSpecializationDecl *Def
10562 = cast_or_null<ClassTemplateSpecializationDecl>(
10563 Val: Specialization->getDefinition());
10564 if (!Def)
10565 InstantiateClassTemplateSpecialization(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Specialization, TSK,
10566 /*Complain=*/true,
10567 PrimaryStrictPackMatch: CTAI.StrictPackMatch);
10568 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10569 MarkVTableUsed(Loc: TemplateNameLoc, Class: Specialization, DefinitionRequired: true);
10570 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10571 }
10572
10573 // Instantiate the members of this class template specialization.
10574 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10575 Val: Specialization->getDefinition());
10576 if (Def) {
10577 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10578 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10579 // TSK_ExplicitInstantiationDefinition
10580 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10581 (TSK == TSK_ExplicitInstantiationDefinition ||
10582 DLLImportExplicitInstantiationDef)) {
10583 // FIXME: Need to notify the ASTMutationListener that we did this.
10584 Def->setTemplateSpecializationKind(TSK);
10585
10586 if (!getDLLAttr(D: Def) && getDLLAttr(D: Specialization) &&
10587 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10588 // An explicit instantiation definition can add a dll attribute to a
10589 // template with a previous instantiation declaration. MinGW doesn't
10590 // allow this.
10591 auto *A = cast<InheritableAttr>(
10592 Val: getDLLAttr(D: Specialization)->clone(C&: getASTContext()));
10593 A->setInherited(true);
10594 Def->addAttr(A);
10595 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10596 }
10597 }
10598
10599 // Fix a TSK_ImplicitInstantiation followed by a
10600 // TSK_ExplicitInstantiationDefinition
10601 bool NewlyDLLExported =
10602 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10603 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10604 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10605 // An explicit instantiation definition can add a dll attribute to a
10606 // template with a previous implicit instantiation. MinGW doesn't allow
10607 // this. We limit clang to only adding dllexport, to avoid potentially
10608 // strange codegen behavior. For example, if we extend this conditional
10609 // to dllimport, and we have a source file calling a method on an
10610 // implicitly instantiated template class instance and then declaring a
10611 // dllimport explicit instantiation definition for the same template
10612 // class, the codegen for the method call will not respect the dllimport,
10613 // while it will with cl. The Def will already have the DLL attribute,
10614 // since the Def and Specialization will be the same in the case of
10615 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10616 // attribute to the Specialization; we just need to make it take effect.
10617 assert(Def == Specialization &&
10618 "Def and Specialization should match for implicit instantiation");
10619 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10620 }
10621
10622 // In MinGW mode, export the template instantiation if the declaration
10623 // was marked dllexport.
10624 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10625 Context.getTargetInfo().getTriple().isOSCygMing() &&
10626 PrevDecl->hasAttr<DLLExportAttr>()) {
10627 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10628 }
10629
10630 // Set the template specialization kind. Make sure it is set before
10631 // instantiating the members which will trigger ASTConsumer callbacks.
10632 Specialization->setTemplateSpecializationKind(TSK);
10633 InstantiateClassTemplateSpecializationMembers(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Def, TSK);
10634 } else {
10635
10636 // Set the template specialization kind.
10637 Specialization->setTemplateSpecializationKind(TSK);
10638 }
10639
10640 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
10641 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10642 Keyword: KW, ElaboratedKeywordLoc: KWLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: SourceLocation(), T: Name,
10643 TLoc: TemplateNameLoc, SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted,
10644 Canon: Context.getCanonicalTagType(TD: Specialization));
10645 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
10646 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10647 NameLoc: TemplateNameLoc, TypeAsWritten: TSI, TSK);
10648 return Specialization;
10649}
10650
10651DeclResult
10652Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10653 SourceLocation TemplateLoc, unsigned TagSpec,
10654 SourceLocation KWLoc, CXXScopeSpec &SS,
10655 IdentifierInfo *Name, SourceLocation NameLoc,
10656 const ParsedAttributesView &Attr) {
10657
10658 bool Owned = false;
10659 bool IsDependent = false;
10660 Decl *TagD =
10661 ActOnTag(S, TagSpec, TUK: TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10662 Attr, AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10663 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent, ScopedEnumKWLoc: SourceLocation(),
10664 ScopedEnumUsesClassTag: false, UnderlyingType: TypeResult(), /*IsTypeSpecifier*/ false,
10665 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10666 .get();
10667
10668 if (!TagD)
10669 return true;
10670
10671 assert(!IsDependent &&
10672 "explicit instantiation of dependent name not yet handled");
10673
10674 TagDecl *Tag = cast<TagDecl>(Val: TagD);
10675 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10676
10677 if (Tag->isInvalidDecl())
10678 return true;
10679
10680 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: Tag);
10681 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10682 if (!Pattern) {
10683 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_nontemplate_type)
10684 << Context.getCanonicalTagType(TD: Record);
10685 Diag(Loc: Record->getLocation(), DiagID: diag::note_nontemplate_decl_here);
10686 return true;
10687 }
10688
10689 // C++0x [temp.explicit]p2:
10690 // If the explicit instantiation is for a class or member class, the
10691 // elaborated-type-specifier in the declaration shall include a
10692 // simple-template-id.
10693 //
10694 // C++98 has the same restriction, just worded differently.
10695 if (!ScopeSpecifierHasTemplateId(SS))
10696 Diag(Loc: TemplateLoc, DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10697 << Record << SS.getRange();
10698
10699 // C++0x [temp.explicit]p2:
10700 // There are two forms of explicit instantiation: an explicit instantiation
10701 // definition and an explicit instantiation declaration. An explicit
10702 // instantiation declaration begins with the extern keyword. [...]
10703 TemplateSpecializationKind TSK
10704 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10705 : TSK_ExplicitInstantiationDeclaration;
10706
10707 CheckExplicitInstantiation(S&: *this, D: Record, InstLoc: NameLoc, WasQualifiedName: true, TSK);
10708
10709 // Verify that it is okay to explicitly instantiate here.
10710 CXXRecordDecl *PrevDecl
10711 = cast_or_null<CXXRecordDecl>(Val: Record->getPreviousDecl());
10712 if (!PrevDecl && Record->getDefinition())
10713 PrevDecl = Record;
10714 if (PrevDecl) {
10715 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10716 bool HasNoEffect = false;
10717 assert(MSInfo && "No member specialization information?");
10718 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateLoc, NewTSK: TSK,
10719 PrevDecl,
10720 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10721 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10722 HasNoEffect))
10723 return true;
10724 if (HasNoEffect) {
10725 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10726 ElaboratedTypeKeyword KW =
10727 TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
10728 QualType TagTy = Context.getTagType(Keyword: KW, Qualifier: SS.getScopeRep(), TD: Record, OwnsTag: false);
10729 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T: TagTy);
10730 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10731 TL.setElaboratedKeywordLoc(KWLoc);
10732 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10733 TL.setNameLoc(NameLoc);
10734 addExplicitInstantiationDecl(Context, CurContext, Spec: Record, ExternLoc,
10735 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(),
10736 ArgsAsWritten: nullptr, NameLoc, TypeAsWritten: TSI, TSK);
10737 return TagD;
10738 }
10739 }
10740
10741 CXXRecordDecl *RecordDef
10742 = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10743 if (!RecordDef) {
10744 // C++ [temp.explicit]p3:
10745 // A definition of a member class of a class template shall be in scope
10746 // at the point of an explicit instantiation of the member class.
10747 CXXRecordDecl *Def
10748 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
10749 if (!Def) {
10750 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_undefined_member)
10751 << 0 << Record->getDeclName() << Record->getDeclContext();
10752 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_forward_declaration)
10753 << Pattern;
10754 return true;
10755 } else {
10756 if (InstantiateClass(PointOfInstantiation: NameLoc, Instantiation: Record, Pattern: Def,
10757 TemplateArgs: getTemplateInstantiationArgs(D: Record),
10758 TSK))
10759 return true;
10760
10761 RecordDef = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10762 if (!RecordDef)
10763 return true;
10764 }
10765 }
10766
10767 // Instantiate all of the members of the class.
10768 InstantiateClassMembers(PointOfInstantiation: NameLoc, Instantiation: RecordDef,
10769 TemplateArgs: getTemplateInstantiationArgs(D: Record), TSK);
10770
10771 if (TSK == TSK_ExplicitInstantiationDefinition)
10772 MarkVTableUsed(Loc: NameLoc, Class: RecordDef, DefinitionRequired: true);
10773
10774 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10775 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
10776 QualType TagTy = Context.getTagType(Keyword: KW, Qualifier: SS.getScopeRep(), TD: Record, OwnsTag: false);
10777 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T: TagTy);
10778 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10779 TL.setElaboratedKeywordLoc(KWLoc);
10780 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10781 TL.setNameLoc(NameLoc);
10782 addExplicitInstantiationDecl(Context, CurContext, Spec: Record, ExternLoc,
10783 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10784 NameLoc, TypeAsWritten: TSI, TSK);
10785 return TagD;
10786}
10787
10788DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10789 SourceLocation ExternLoc,
10790 SourceLocation TemplateLoc,
10791 Declarator &D) {
10792 // Explicit instantiations always require a name.
10793 // TODO: check if/when DNInfo should replace Name.
10794 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10795 DeclarationName Name = NameInfo.getName();
10796 if (!Name) {
10797 if (!D.isInvalidType())
10798 Diag(Loc: D.getDeclSpec().getBeginLoc(),
10799 DiagID: diag::err_explicit_instantiation_requires_name)
10800 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10801
10802 return true;
10803 }
10804
10805 // Get the innermost enclosing declaration scope.
10806 S = S->getDeclParent();
10807
10808 // Determine the type of the declaration.
10809 TypeSourceInfo *T = GetTypeForDeclarator(D);
10810 QualType R = T->getType();
10811 if (R.isNull())
10812 return true;
10813
10814 // C++ [dcl.stc]p1:
10815 // A storage-class-specifier shall not be specified in [...] an explicit
10816 // instantiation (14.7.2) directive.
10817 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10818 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_of_typedef)
10819 << Name;
10820 return true;
10821 } else if (D.getDeclSpec().getStorageClassSpec()
10822 != DeclSpec::SCS_unspecified) {
10823 // Complain about then remove the storage class specifier.
10824 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_storage_class)
10825 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10826
10827 D.getMutableDeclSpec().ClearStorageClassSpecs();
10828 }
10829
10830 // C++0x [temp.explicit]p1:
10831 // [...] An explicit instantiation of a function template shall not use the
10832 // inline or constexpr specifiers.
10833 // Presumably, this also applies to member functions of class templates as
10834 // well.
10835 if (D.getDeclSpec().isInlineSpecified())
10836 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10837 DiagID: getLangOpts().CPlusPlus11 ?
10838 diag::err_explicit_instantiation_inline :
10839 diag::warn_explicit_instantiation_inline_0x)
10840 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10841 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10842 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10843 // not already specified.
10844 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10845 DiagID: diag::err_explicit_instantiation_constexpr);
10846
10847 // A deduction guide is not on the list of entities that can be explicitly
10848 // instantiated.
10849 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10850 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
10851 << /*explicit instantiation*/ 0;
10852 return true;
10853 }
10854
10855 // C++0x [temp.explicit]p2:
10856 // There are two forms of explicit instantiation: an explicit instantiation
10857 // definition and an explicit instantiation declaration. An explicit
10858 // instantiation declaration begins with the extern keyword. [...]
10859 TemplateSpecializationKind TSK
10860 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10861 : TSK_ExplicitInstantiationDeclaration;
10862
10863 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10864 LookupParsedName(R&: Previous, S, SS: &D.getCXXScopeSpec(),
10865 /*ObjectType=*/QualType());
10866
10867 if (!R->isFunctionType()) {
10868 // C++ [temp.explicit]p1:
10869 // A [...] static data member of a class template can be explicitly
10870 // instantiated from the member definition associated with its class
10871 // template.
10872 // C++1y [temp.explicit]p1:
10873 // A [...] variable [...] template specialization can be explicitly
10874 // instantiated from its template.
10875 if (Previous.isAmbiguous())
10876 return true;
10877
10878 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10879 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10880 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10881
10882 if (!PrevTemplate) {
10883 if (!Prev || !Prev->isStaticDataMember()) {
10884 // We expect to see a static data member here.
10885 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_not_known)
10886 << Name;
10887 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10888 P != PEnd; ++P)
10889 Diag(Loc: (*P)->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10890 return true;
10891 }
10892
10893 if (!Prev->getInstantiatedFromStaticDataMember()) {
10894 // FIXME: Check for explicit specialization?
10895 Diag(Loc: D.getIdentifierLoc(),
10896 DiagID: diag::err_explicit_instantiation_data_member_not_instantiated)
10897 << Prev;
10898 Diag(Loc: Prev->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10899 // FIXME: Can we provide a note showing where this was declared?
10900 return true;
10901 }
10902 } else {
10903 // Explicitly instantiate a variable template.
10904
10905 // C++1y [dcl.spec.auto]p6:
10906 // ... A program that uses auto or decltype(auto) in a context not
10907 // explicitly allowed in this section is ill-formed.
10908 //
10909 // This includes auto-typed variable template instantiations.
10910 if (R->isUndeducedType()) {
10911 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10912 DiagID: diag::err_auto_not_allowed_var_inst);
10913 return true;
10914 }
10915
10916 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10917 // C++1y [temp.explicit]p3:
10918 // If the explicit instantiation is for a variable, the unqualified-id
10919 // in the declaration shall be a template-id.
10920 Diag(Loc: D.getIdentifierLoc(),
10921 DiagID: diag::err_explicit_instantiation_without_template_id)
10922 << PrevTemplate;
10923 Diag(Loc: PrevTemplate->getLocation(),
10924 DiagID: diag::note_explicit_instantiation_here);
10925 return true;
10926 }
10927
10928 // Translate the parser's template argument list into our AST format.
10929 TemplateArgumentListInfo TemplateArgs =
10930 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10931
10932 DeclResult Res =
10933 CheckVarTemplateId(Template: PrevTemplate, TemplateLoc, TemplateNameLoc: D.getIdentifierLoc(),
10934 TemplateArgs, /*SetWrittenArgs=*/true);
10935 if (Res.isInvalid())
10936 return true;
10937
10938 if (!Res.isUsable()) {
10939 // We somehow specified dependent template arguments in an explicit
10940 // instantiation. This should probably only happen during error
10941 // recovery.
10942 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_dependent);
10943 return true;
10944 }
10945
10946 // Ignore access control bits, we don't need them for redeclaration
10947 // checking.
10948 Prev = cast<VarDecl>(Val: Res.get());
10949 ArgsAsWritten =
10950 ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
10951 }
10952
10953 // C++0x [temp.explicit]p2:
10954 // If the explicit instantiation is for a member function, a member class
10955 // or a static data member of a class template specialization, the name of
10956 // the class template specialization in the qualified-id for the member
10957 // name shall be a simple-template-id.
10958 //
10959 // C++98 has the same restriction, just worded differently.
10960 //
10961 // This does not apply to variable template specializations, where the
10962 // template-id is in the unqualified-id instead.
10963 if (!ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()) && !PrevTemplate)
10964 Diag(Loc: D.getIdentifierLoc(),
10965 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10966 << Prev << D.getCXXScopeSpec().getRange();
10967
10968 CheckExplicitInstantiation(S&: *this, D: Prev, InstLoc: D.getIdentifierLoc(), WasQualifiedName: true, TSK);
10969
10970 // Verify that it is okay to explicitly instantiate here.
10971 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10972 SourceLocation POI = Prev->getPointOfInstantiation();
10973 bool HasNoEffect = false;
10974 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK, PrevDecl: Prev,
10975 PrevTSK, PrevPointOfInstantiation: POI, HasNoEffect))
10976 return true;
10977
10978 if (!HasNoEffect) {
10979 // Instantiate static data member or variable template.
10980 Prev->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
10981 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: Prev)) {
10982 VTSD->setExternKeywordLoc(ExternLoc);
10983 VTSD->setTemplateKeywordLoc(TemplateLoc);
10984 }
10985
10986 // Merge attributes.
10987 ProcessDeclAttributeList(S, D: Prev, AttrList: D.getDeclSpec().getAttributes());
10988 if (PrevTemplate)
10989 ProcessAPINotes(D: Prev);
10990
10991 if (TSK == TSK_ExplicitInstantiationDefinition)
10992 InstantiateVariableDefinition(PointOfInstantiation: D.getIdentifierLoc(), Var: Prev);
10993 }
10994
10995 // Check the new variable specialization against the parsed input.
10996 if (PrevTemplate && !Context.hasSameType(T1: Prev->getType(), T2: R)) {
10997 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10998 DiagID: diag::err_invalid_var_template_spec_type)
10999 << 0 << PrevTemplate << R << Prev->getType();
11000 Diag(Loc: PrevTemplate->getLocation(), DiagID: diag::note_template_declared_here)
11001 << 2 << PrevTemplate->getDeclName();
11002 return true;
11003 }
11004
11005 addExplicitInstantiationDecl(
11006 Context, CurContext, Spec: Prev, ExternLoc, TemplateLoc,
11007 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11008 NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
11009 return (Decl *)nullptr;
11010 }
11011
11012 // If the declarator is a template-id, translate the parser's template
11013 // argument list into our AST format.
11014 bool HasExplicitTemplateArgs = false;
11015 TemplateArgumentListInfo TemplateArgs;
11016 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
11017 TemplateArgs = makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
11018 HasExplicitTemplateArgs = true;
11019 }
11020
11021 // C++ [temp.explicit]p1:
11022 // A [...] function [...] can be explicitly instantiated from its template.
11023 // A member function [...] of a class template can be explicitly
11024 // instantiated from the member definition associated with its class
11025 // template.
11026 UnresolvedSet<8> TemplateMatches;
11027 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
11028 OverloadCandidateSet::CSK_Normal);
11029 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
11030 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
11031 P != PEnd; ++P) {
11032 NamedDecl *Prev = *P;
11033 if (!HasExplicitTemplateArgs) {
11034 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Prev)) {
11035 QualType Adjusted = adjustCCAndNoReturn(ArgFunctionType: R, FunctionType: Method->getType(),
11036 /*AdjustExceptionSpec*/true);
11037 if (Context.hasSameUnqualifiedType(T1: Method->getType(), T2: Adjusted)) {
11038 if (Method->getPrimaryTemplate()) {
11039 TemplateMatches.addDecl(D: Method, AS: P.getAccess());
11040 } else {
11041 OverloadCandidate &C = NonTemplateMatches.addCandidate();
11042 C.FoundDecl = P.getPair();
11043 C.Function = Method;
11044 C.Viable = true;
11045 ConstraintSatisfaction S;
11046 if (Method->getTrailingRequiresClause() &&
11047 (CheckFunctionConstraints(FD: Method, Satisfaction&: S, UsageLoc: D.getIdentifierLoc(),
11048 /*ForOverloadResolution=*/true) ||
11049 !S.IsSatisfied)) {
11050 C.Viable = false;
11051 C.FailureKind = ovl_fail_constraints_not_satisfied;
11052 }
11053 }
11054 }
11055 }
11056 }
11057
11058 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Prev);
11059 if (!FunTmpl)
11060 continue;
11061
11062 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
11063 FunctionDecl *Specialization = nullptr;
11064 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
11065 FunctionTemplate: FunTmpl, ExplicitTemplateArgs: (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), ArgFunctionType: R,
11066 Specialization, Info);
11067 TDK != TemplateDeductionResult::Success) {
11068 // Keep track of almost-matches.
11069 FailedTemplateCandidates.addCandidate().set(
11070 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
11071 Info: MakeDeductionFailureInfo(Context, TDK, Info));
11072 (void)TDK;
11073 continue;
11074 }
11075
11076 // Target attributes are part of the cuda function signature, so
11077 // the cuda target of the instantiated function must match that of its
11078 // template. Given that C++ template deduction does not take
11079 // target attributes into account, we reject candidates here that
11080 // have a different target.
11081 if (LangOpts.CUDA &&
11082 CUDA().IdentifyTarget(D: Specialization,
11083 /* IgnoreImplicitHDAttr = */ true) !=
11084 CUDA().IdentifyTarget(Attrs: D.getDeclSpec().getAttributes())) {
11085 FailedTemplateCandidates.addCandidate().set(
11086 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
11087 Info: MakeDeductionFailureInfo(
11088 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
11089 continue;
11090 }
11091
11092 TemplateMatches.addDecl(D: Specialization, AS: P.getAccess());
11093 }
11094
11095 FunctionDecl *Specialization = nullptr;
11096 if (!NonTemplateMatches.empty()) {
11097 unsigned Msg = 0;
11098 OverloadCandidateDisplayKind DisplayKind;
11099 OverloadCandidateSet::iterator Best;
11100 switch (NonTemplateMatches.BestViableFunction(S&: *this, Loc: D.getIdentifierLoc(),
11101 Best)) {
11102 case OR_Success:
11103 case OR_Deleted:
11104 Specialization = cast<FunctionDecl>(Val: Best->Function);
11105 break;
11106 case OR_Ambiguous:
11107 Msg = diag::err_explicit_instantiation_ambiguous;
11108 DisplayKind = OCD_AmbiguousCandidates;
11109 break;
11110 case OR_No_Viable_Function:
11111 Msg = diag::err_explicit_instantiation_no_candidate;
11112 DisplayKind = OCD_AllCandidates;
11113 break;
11114 }
11115 if (Msg) {
11116 PartialDiagnostic Diag = PDiag(DiagID: Msg) << Name;
11117 NonTemplateMatches.NoteCandidates(
11118 PA: PartialDiagnosticAt(D.getIdentifierLoc(), Diag), S&: *this, OCD: DisplayKind,
11119 Args: {});
11120 return true;
11121 }
11122 }
11123
11124 if (!Specialization) {
11125 // Find the most specialized function template specialization.
11126 UnresolvedSetIterator Result = getMostSpecialized(
11127 SBegin: TemplateMatches.begin(), SEnd: TemplateMatches.end(),
11128 FailedCandidates&: FailedTemplateCandidates, Loc: D.getIdentifierLoc(),
11129 NoneDiag: PDiag(DiagID: diag::err_explicit_instantiation_not_known) << Name,
11130 AmbigDiag: PDiag(DiagID: diag::err_explicit_instantiation_ambiguous) << Name,
11131 CandidateDiag: PDiag(DiagID: diag::note_explicit_instantiation_candidate));
11132
11133 if (Result == TemplateMatches.end())
11134 return true;
11135
11136 // Ignore access control bits, we don't need them for redeclaration checking.
11137 Specialization = cast<FunctionDecl>(Val: *Result);
11138 }
11139
11140 // C++11 [except.spec]p4
11141 // In an explicit instantiation an exception-specification may be specified,
11142 // but is not required.
11143 // If an exception-specification is specified in an explicit instantiation
11144 // directive, it shall be compatible with the exception-specifications of
11145 // other declarations of that function.
11146 if (auto *FPT = R->getAs<FunctionProtoType>())
11147 if (FPT->hasExceptionSpec()) {
11148 unsigned DiagID =
11149 diag::err_mismatched_exception_spec_explicit_instantiation;
11150 if (getLangOpts().MicrosoftExt)
11151 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11152 bool Result = CheckEquivalentExceptionSpec(
11153 DiagID: PDiag(DiagID) << Specialization->getType(),
11154 NoteID: PDiag(DiagID: diag::note_explicit_instantiation_here),
11155 Old: Specialization->getType()->getAs<FunctionProtoType>(),
11156 OldLoc: Specialization->getLocation(), New: FPT, NewLoc: D.getBeginLoc());
11157 // In Microsoft mode, mismatching exception specifications just cause a
11158 // warning.
11159 if (!getLangOpts().MicrosoftExt && Result)
11160 return true;
11161 }
11162
11163 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11164 Diag(Loc: D.getIdentifierLoc(),
11165 DiagID: diag::err_explicit_instantiation_member_function_not_instantiated)
11166 << Specialization
11167 << (Specialization->getTemplateSpecializationKind() ==
11168 TSK_ExplicitSpecialization);
11169 Diag(Loc: Specialization->getLocation(), DiagID: diag::note_explicit_instantiation_here);
11170 return true;
11171 }
11172
11173 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11174 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11175 PrevDecl = Specialization;
11176
11177 if (PrevDecl) {
11178 bool HasNoEffect = false;
11179 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK,
11180 PrevDecl,
11181 PrevTSK: PrevDecl->getTemplateSpecializationKind(),
11182 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
11183 HasNoEffect))
11184 return true;
11185
11186 if (HasNoEffect) {
11187 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11188 if (HasExplicitTemplateArgs)
11189 ArgsAsWritten =
11190 ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
11191 addExplicitInstantiationDecl(
11192 Context, CurContext, Spec: Specialization, ExternLoc, TemplateLoc,
11193 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11194 NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
11195 return (Decl *)nullptr;
11196 }
11197 }
11198
11199 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11200 // functions
11201 // valarray<size_t>::valarray(size_t) and
11202 // valarray<size_t>::~valarray()
11203 // that it declared to have internal linkage with the internal_linkage
11204 // attribute. Ignore the explicit instantiation declaration in this case.
11205 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11206 TSK == TSK_ExplicitInstantiationDeclaration) {
11207 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getDeclContext()))
11208 if (RD->getIdentifier() && RD->getIdentifier()->isStr(Str: "valarray") &&
11209 RD->isInStdNamespace())
11210 return (Decl*) nullptr;
11211 }
11212
11213 ProcessDeclAttributeList(S, D: Specialization, AttrList: D.getDeclSpec().getAttributes());
11214 ProcessAPINotes(D: Specialization);
11215
11216 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11217 // instantiation declarations.
11218 if (TSK == TSK_ExplicitInstantiationDefinition &&
11219 Specialization->hasAttr<DLLImportAttr>() &&
11220 Context.getTargetInfo().getCXXABI().isMicrosoft())
11221 TSK = TSK_ExplicitInstantiationDeclaration;
11222
11223 Specialization->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
11224 if (Specialization->isDefined()) {
11225 // Let the ASTConsumer know that this function has been explicitly
11226 // instantiated now, and its linkage might have changed.
11227 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Specialization));
11228 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11229 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11230 // be explicitly instantiated.
11231 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getParent());
11232 RD && RD->isLambda()) {
11233 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_lambda_explicit_temp_spec)
11234 << /*instantiation*/ 1;
11235 Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here) << RD;
11236 return (Decl *)nullptr;
11237 }
11238 InstantiateFunctionDefinition(PointOfInstantiation: D.getIdentifierLoc(), Function: Specialization);
11239 }
11240
11241 // C++0x [temp.explicit]p2:
11242 // If the explicit instantiation is for a member function, a member class
11243 // or a static data member of a class template specialization, the name of
11244 // the class template specialization in the qualified-id for the member
11245 // name shall be a simple-template-id.
11246 //
11247 // C++98 has the same restriction, just worded differently.
11248 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11249 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11250 D.getCXXScopeSpec().isSet() &&
11251 !ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()))
11252 Diag(Loc: D.getIdentifierLoc(),
11253 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
11254 << Specialization << D.getCXXScopeSpec().getRange();
11255
11256 CheckExplicitInstantiation(
11257 S&: *this,
11258 D: FunTmpl ? (NamedDecl *)FunTmpl
11259 : Specialization->getInstantiatedFromMemberFunction(),
11260 InstLoc: D.getIdentifierLoc(), WasQualifiedName: D.getCXXScopeSpec().isSet(), TSK);
11261
11262 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11263 if (HasExplicitTemplateArgs)
11264 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
11265 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
11266 TemplateLoc,
11267 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context),
11268 ArgsAsWritten, NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
11269 return (Decl *)nullptr;
11270}
11271
11272TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11273 const CXXScopeSpec &SS,
11274 const IdentifierInfo *Name,
11275 SourceLocation TagLoc,
11276 SourceLocation NameLoc) {
11277 // This has to hold, because SS is expected to be defined.
11278 assert(Name && "Expected a name in a dependent tag");
11279
11280 NestedNameSpecifier NNS = SS.getScopeRep();
11281 if (!NNS)
11282 return true;
11283
11284 if (TUK == TagUseKind::Friend &&
11285 DiagnosePackIndexingInFriendNNS(Loc: NameLoc, NNSLoc: SS.getWithLocInContext(Context)))
11286 return true;
11287
11288 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
11289
11290 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11291 Diag(Loc: NameLoc, DiagID: diag::err_dependent_tag_decl)
11292 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11293 return true;
11294 }
11295
11296 // Create the resulting type.
11297 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
11298 QualType Result = Context.getDependentNameType(Keyword: Kwd, NNS, Name);
11299
11300 // Create type-source location information for this type.
11301 TypeLocBuilder TLB;
11302 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: Result);
11303 TL.setElaboratedKeywordLoc(TagLoc);
11304 TL.setQualifierLoc(SS.getWithLocInContext(Context));
11305 TL.setNameLoc(NameLoc);
11306 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
11307}
11308
11309TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11310 const CXXScopeSpec &SS,
11311 const IdentifierInfo &II,
11312 SourceLocation IdLoc,
11313 ImplicitTypenameContext IsImplicitTypename) {
11314 if (SS.isInvalid())
11315 return true;
11316
11317 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11318 DiagCompat(Loc: TypenameLoc, CompatDiagId: diag_compat::typename_outside_of_template)
11319 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11320
11321 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11322 TypeSourceInfo *TSI = nullptr;
11323 QualType T =
11324 CheckTypenameType(Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11325 : ElaboratedTypeKeyword::None,
11326 KeywordLoc: TypenameLoc, QualifierLoc, II, IILoc: IdLoc, TSI: &TSI,
11327 /*DeducedTSTContext=*/true);
11328 if (T.isNull())
11329 return true;
11330 return CreateParsedType(T, TInfo: TSI);
11331}
11332
11333TypeResult
11334Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11335 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11336 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11337 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11338 ASTTemplateArgsPtr TemplateArgsIn,
11339 SourceLocation RAngleLoc) {
11340 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11341 Diag(Loc: TypenameLoc, DiagID: getLangOpts().CPlusPlus11
11342 ? diag::compat_cxx11_typename_outside_of_template
11343 : diag::compat_pre_cxx11_typename_outside_of_template)
11344 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11345
11346 // Strangely, non-type results are not ignored by this lookup, so the
11347 // program is ill-formed if it finds an injected-class-name.
11348 if (TypenameLoc.isValid()) {
11349 auto *LookupRD =
11350 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: false));
11351 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11352 Diag(Loc: TemplateIILoc,
11353 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
11354 << TemplateII << 0 /*injected-class-name used as template name*/
11355 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11356 }
11357 }
11358
11359 // Translate the parser's template argument list in our AST format.
11360 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11361 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11362
11363 QualType T = CheckTemplateIdType(
11364 Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11365 : ElaboratedTypeKeyword::None,
11366 Name: TemplateIn.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
11367 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11368 if (T.isNull())
11369 return true;
11370
11371 // Provide source-location information for the template specialization type.
11372 TypeLocBuilder Builder;
11373 TemplateSpecializationTypeLoc SpecTL
11374 = Builder.push<TemplateSpecializationTypeLoc>(T);
11375 SpecTL.set(ElaboratedKeywordLoc: TypenameLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
11376 NameLoc: TemplateIILoc, TAL: TemplateArgs);
11377 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11378 return CreateParsedType(T, TInfo: TSI);
11379}
11380
11381/// Determine whether this failed name lookup should be treated as being
11382/// disabled by a usage of std::enable_if.
11383static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
11384 SourceRange &CondRange, Expr *&Cond) {
11385 // We must be looking for a ::type...
11386 if (!II.isStr(Str: "type"))
11387 return false;
11388
11389 // ... within an explicitly-written template specialization...
11390 if (NNS.getNestedNameSpecifier().getKind() != NestedNameSpecifier::Kind::Type)
11391 return false;
11392
11393 // FIXME: Look through sugar.
11394 auto EnableIfTSTLoc =
11395 NNS.castAsTypeLoc().getAs<TemplateSpecializationTypeLoc>();
11396 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11397 return false;
11398 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11399
11400 // ... which names a complete class template declaration...
11401 const TemplateDecl *EnableIfDecl =
11402 EnableIfTST->getTemplateName().getAsTemplateDecl();
11403 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11404 return false;
11405
11406 // ... called "enable_if".
11407 const IdentifierInfo *EnableIfII =
11408 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11409 if (!EnableIfII || !EnableIfII->isStr(Str: "enable_if"))
11410 return false;
11411
11412 // Assume the first template argument is the condition.
11413 CondRange = EnableIfTSTLoc.getArgLoc(i: 0).getSourceRange();
11414
11415 // Dig out the condition.
11416 Cond = nullptr;
11417 if (EnableIfTSTLoc.getArgLoc(i: 0).getArgument().getKind()
11418 != TemplateArgument::Expression)
11419 return true;
11420
11421 Cond = EnableIfTSTLoc.getArgLoc(i: 0).getSourceExpression();
11422
11423 // Ignore Boolean literals; they add no value.
11424 if (isa<CXXBoolLiteralExpr>(Val: Cond->IgnoreParenCasts()))
11425 Cond = nullptr;
11426
11427 return true;
11428}
11429
11430QualType
11431Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11432 SourceLocation KeywordLoc,
11433 NestedNameSpecifierLoc QualifierLoc,
11434 const IdentifierInfo &II,
11435 SourceLocation IILoc,
11436 TypeSourceInfo **TSI,
11437 bool DeducedTSTContext) {
11438 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11439 DeducedTSTContext);
11440 if (T.isNull())
11441 return QualType();
11442
11443 TypeLocBuilder TLB;
11444 if (isa<DependentNameType>(Val: T)) {
11445 auto TL = TLB.push<DependentNameTypeLoc>(T);
11446 TL.setElaboratedKeywordLoc(KeywordLoc);
11447 TL.setQualifierLoc(QualifierLoc);
11448 TL.setNameLoc(IILoc);
11449 } else if (isa<DeducedTemplateSpecializationType>(Val: T)) {
11450 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
11451 TL.setElaboratedKeywordLoc(KeywordLoc);
11452 TL.setQualifierLoc(QualifierLoc);
11453 TL.setNameLoc(IILoc);
11454 } else if (isa<TemplateTypeParmType>(Val: T)) {
11455 // FIXME: There might be a 'typename' keyword here, but we just drop it
11456 // as it can't be represented.
11457 assert(!QualifierLoc);
11458 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11459 } else if (isa<TagType>(Val: T)) {
11460 auto TL = TLB.push<TagTypeLoc>(T);
11461 TL.setElaboratedKeywordLoc(KeywordLoc);
11462 TL.setQualifierLoc(QualifierLoc);
11463 TL.setNameLoc(IILoc);
11464 } else if (isa<TypedefType>(Val: T)) {
11465 TLB.push<TypedefTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11466 } else {
11467 TLB.push<UnresolvedUsingTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11468 }
11469 *TSI = TLB.getTypeSourceInfo(Context, T);
11470 return T;
11471}
11472
11473/// Build the type that describes a C++ typename specifier,
11474/// e.g., "typename T::type".
11475QualType
11476Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11477 SourceLocation KeywordLoc,
11478 NestedNameSpecifierLoc QualifierLoc,
11479 const IdentifierInfo &II,
11480 SourceLocation IILoc, bool DeducedTSTContext) {
11481 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11482
11483 CXXScopeSpec SS;
11484 SS.Adopt(Other: QualifierLoc);
11485
11486 DeclContext *Ctx = nullptr;
11487 if (QualifierLoc) {
11488 Ctx = computeDeclContext(SS);
11489 if (!Ctx) {
11490 // If the nested-name-specifier is dependent and couldn't be
11491 // resolved to a type, build a typename type.
11492 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11493 return Context.getDependentNameType(Keyword,
11494 NNS: QualifierLoc.getNestedNameSpecifier(),
11495 Name: &II);
11496 }
11497
11498 // If the nested-name-specifier refers to the current instantiation,
11499 // the "typename" keyword itself is superfluous. In C++03, the
11500 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11501 // allows such extraneous "typename" keywords, and we retroactively
11502 // apply this DR to C++03 code with only a warning. In any case we continue.
11503
11504 if (RequireCompleteDeclContext(SS, DC: Ctx))
11505 return QualType();
11506 }
11507
11508 DeclarationName Name(&II);
11509 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11510 if (Ctx)
11511 LookupQualifiedName(R&: Result, LookupCtx: Ctx, SS);
11512 else
11513 LookupName(R&: Result, S: CurScope);
11514 unsigned DiagID = 0;
11515 Decl *Referenced = nullptr;
11516 switch (Result.getResultKind()) {
11517 case LookupResultKind::NotFound: {
11518 // If we're looking up 'type' within a template named 'enable_if', produce
11519 // a more specific diagnostic.
11520 SourceRange CondRange;
11521 Expr *Cond = nullptr;
11522 if (Ctx && isEnableIf(NNS: QualifierLoc, II, CondRange, Cond)) {
11523 // If we have a condition, narrow it down to the specific failed
11524 // condition.
11525 if (Cond) {
11526 Expr *FailedCond;
11527 std::string FailedDescription;
11528 std::tie(args&: FailedCond, args&: FailedDescription) =
11529 findFailedBooleanCondition(Cond);
11530
11531 Diag(Loc: FailedCond->getExprLoc(),
11532 DiagID: diag::err_typename_nested_not_found_requirement)
11533 << FailedDescription
11534 << FailedCond->getSourceRange();
11535 return QualType();
11536 }
11537
11538 Diag(Loc: CondRange.getBegin(),
11539 DiagID: diag::err_typename_nested_not_found_enable_if)
11540 << Ctx << CondRange;
11541 return QualType();
11542 }
11543
11544 DiagID = Ctx ? diag::err_typename_nested_not_found
11545 : diag::err_unknown_typename;
11546 break;
11547 }
11548
11549 case LookupResultKind::FoundUnresolvedValue: {
11550 // We found a using declaration that is a value. Most likely, the using
11551 // declaration itself is meant to have the 'typename' keyword.
11552 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11553 IILoc);
11554 Diag(Loc: IILoc, DiagID: diag::err_typename_refers_to_using_value_decl)
11555 << Name << Ctx << FullRange;
11556 if (UnresolvedUsingValueDecl *Using
11557 = dyn_cast<UnresolvedUsingValueDecl>(Val: Result.getRepresentativeDecl())){
11558 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11559 Diag(Loc, DiagID: diag::note_using_value_decl_missing_typename)
11560 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
11561 }
11562 }
11563 // Fall through to create a dependent typename type, from which we can
11564 // recover better.
11565 [[fallthrough]];
11566
11567 case LookupResultKind::NotFoundInCurrentInstantiation:
11568 // Okay, it's a member of an unknown instantiation.
11569 return Context.getDependentNameType(Keyword,
11570 NNS: QualifierLoc.getNestedNameSpecifier(),
11571 Name: &II);
11572
11573 case LookupResultKind::Found:
11574 // FXIME: Missing support for UsingShadowDecl on this path?
11575 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: Result.getFoundDecl())) {
11576 // C++ [class.qual]p2:
11577 // In a lookup in which function names are not ignored and the
11578 // nested-name-specifier nominates a class C, if the name specified
11579 // after the nested-name-specifier, when looked up in C, is the
11580 // injected-class-name of C [...] then the name is instead considered
11581 // to name the constructor of class C.
11582 //
11583 // Unlike in an elaborated-type-specifier, function names are not ignored
11584 // in typename-specifier lookup. However, they are ignored in all the
11585 // contexts where we form a typename type with no keyword (that is, in
11586 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11587 //
11588 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11589 // ignore functions, but that appears to be an oversight.
11590 checkTypeDeclType(LookupCtx: Ctx,
11591 DCK: Keyword == ElaboratedTypeKeyword::Typename
11592 ? DiagCtorKind::Typename
11593 : DiagCtorKind::None,
11594 TD: Type, NameLoc: IILoc);
11595 // FIXME: This appears to be the only case where a template type parameter
11596 // can have an elaborated keyword. We should preserve it somehow.
11597 if (isa<TemplateTypeParmDecl>(Val: Type)) {
11598 assert(Keyword == ElaboratedTypeKeyword::Typename);
11599 assert(!QualifierLoc);
11600 Keyword = ElaboratedTypeKeyword::None;
11601 }
11602 return Context.getTypeDeclType(
11603 Keyword, Qualifier: QualifierLoc.getNestedNameSpecifier(), Decl: Type);
11604 }
11605
11606 // C++ [dcl.type.simple]p2:
11607 // A type-specifier of the form
11608 // typename[opt] nested-name-specifier[opt] template-name
11609 // is a placeholder for a deduced class type [...].
11610 if (getLangOpts().CPlusPlus17) {
11611 if (auto *TD = getAsTypeTemplateDecl(D: Result.getFoundDecl())) {
11612 if (!DeducedTSTContext) {
11613 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11614 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11615 Diag(Loc: IILoc, DiagID: diag::err_dependent_deduced_tst)
11616 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
11617 << QualType(Qualifier.getAsType(), 0);
11618 else
11619 Diag(Loc: IILoc, DiagID: diag::err_deduced_tst)
11620 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD));
11621 NoteTemplateLocation(Decl: *TD);
11622 return QualType();
11623 }
11624 TemplateName Name = Context.getQualifiedTemplateName(
11625 Qualifier: QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11626 Template: TemplateName(TD));
11627 return Context.getDeducedTemplateSpecializationType(
11628 DK: DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11629 Template: Name);
11630 }
11631 }
11632
11633 DiagID = Ctx ? diag::err_typename_nested_not_type
11634 : diag::err_typename_not_type;
11635 Referenced = Result.getFoundDecl();
11636 break;
11637
11638 case LookupResultKind::FoundOverloaded:
11639 DiagID = Ctx ? diag::err_typename_nested_not_type
11640 : diag::err_typename_not_type;
11641 Referenced = *Result.begin();
11642 break;
11643
11644 case LookupResultKind::Ambiguous:
11645 return QualType();
11646 }
11647
11648 // If we get here, it's because name lookup did not find a
11649 // type. Emit an appropriate diagnostic and return an error.
11650 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11651 IILoc);
11652 if (Ctx)
11653 Diag(Loc: IILoc, DiagID) << FullRange << Name << Ctx;
11654 else
11655 Diag(Loc: IILoc, DiagID) << FullRange << Name;
11656 if (Referenced)
11657 Diag(Loc: Referenced->getLocation(),
11658 DiagID: Ctx ? diag::note_typename_member_refers_here
11659 : diag::note_typename_refers_here)
11660 << Name;
11661 return QualType();
11662}
11663
11664namespace {
11665 // See Sema::RebuildTypeInCurrentInstantiation
11666 class CurrentInstantiationRebuilder
11667 : public TreeTransform<CurrentInstantiationRebuilder> {
11668 SourceLocation Loc;
11669 DeclarationName Entity;
11670
11671 public:
11672 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11673
11674 CurrentInstantiationRebuilder(Sema &SemaRef,
11675 SourceLocation Loc,
11676 DeclarationName Entity)
11677 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11678 Loc(Loc), Entity(Entity) { }
11679
11680 /// Determine whether the given type \p T has already been
11681 /// transformed.
11682 ///
11683 /// For the purposes of type reconstruction, a type has already been
11684 /// transformed if it is NULL or if it is not dependent.
11685 bool AlreadyTransformed(QualType T) {
11686 return T.isNull() || !T->isInstantiationDependentType();
11687 }
11688
11689 /// Returns the location of the entity whose type is being
11690 /// rebuilt.
11691 SourceLocation getBaseLocation() { return Loc; }
11692
11693 /// Returns the name of the entity whose type is being rebuilt.
11694 DeclarationName getBaseEntity() { return Entity; }
11695
11696 /// Sets the "base" location and entity when that
11697 /// information is known based on another transformation.
11698 void setBase(SourceLocation Loc, DeclarationName Entity) {
11699 this->Loc = Loc;
11700 this->Entity = Entity;
11701 }
11702
11703 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11704 // Lambdas never need to be transformed.
11705 return E;
11706 }
11707 };
11708} // end anonymous namespace
11709
11710TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11711 SourceLocation Loc,
11712 DeclarationName Name) {
11713 if (!T || !T->getType()->isInstantiationDependentType())
11714 return T;
11715
11716 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11717 return Rebuilder.TransformType(TSI: T);
11718}
11719
11720ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11721 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11722 DeclarationName());
11723 return Rebuilder.TransformExpr(E);
11724}
11725
11726bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11727 if (SS.isInvalid())
11728 return true;
11729
11730 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11731 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11732 DeclarationName());
11733 NestedNameSpecifierLoc Rebuilt
11734 = Rebuilder.TransformNestedNameSpecifierLoc(NNS: QualifierLoc);
11735 if (!Rebuilt)
11736 return true;
11737
11738 SS.Adopt(Other: Rebuilt);
11739 return false;
11740}
11741
11742bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11743 TemplateParameterList *Params) {
11744 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11745 Decl *Param = Params->getParam(Idx: I);
11746
11747 // There is nothing to rebuild in a type parameter.
11748 if (isa<TemplateTypeParmDecl>(Val: Param))
11749 continue;
11750
11751 // Rebuild the template parameter list of a template template parameter.
11752 if (TemplateTemplateParmDecl *TTP
11753 = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) {
11754 if (RebuildTemplateParamsInCurrentInstantiation(
11755 Params: TTP->getTemplateParameters()))
11756 return true;
11757
11758 continue;
11759 }
11760
11761 // Rebuild the type of a non-type template parameter.
11762 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Val: Param);
11763 TypeSourceInfo *NewTSI
11764 = RebuildTypeInCurrentInstantiation(T: NTTP->getTypeSourceInfo(),
11765 Loc: NTTP->getLocation(),
11766 Name: NTTP->getDeclName());
11767 if (!NewTSI)
11768 return true;
11769
11770 if (NewTSI->getType()->isUndeducedType()) {
11771 // C++17 [temp.dep.expr]p3:
11772 // An id-expression is type-dependent if it contains
11773 // - an identifier associated by name lookup with a non-type
11774 // template-parameter declared with a type that contains a
11775 // placeholder type (7.1.7.4),
11776 NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: NewTSI);
11777 }
11778
11779 if (NewTSI != NTTP->getTypeSourceInfo()) {
11780 NTTP->setTypeSourceInfo(NewTSI);
11781 NTTP->setType(NewTSI->getType());
11782 }
11783 }
11784
11785 return false;
11786}
11787
11788std::string
11789Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11790 const TemplateArgumentList &Args) {
11791 return getTemplateArgumentBindingsText(Params, Args: Args.data(), NumArgs: Args.size());
11792}
11793
11794std::string
11795Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11796 const TemplateArgument *Args,
11797 unsigned NumArgs) {
11798 SmallString<128> Str;
11799 llvm::raw_svector_ostream Out(Str);
11800
11801 if (!Params || Params->size() == 0 || NumArgs == 0)
11802 return std::string();
11803
11804 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11805 if (I >= NumArgs)
11806 break;
11807
11808 if (I == 0)
11809 Out << "[with ";
11810 else
11811 Out << ", ";
11812
11813 if (const IdentifierInfo *Id = Params->getParam(Idx: I)->getIdentifier()) {
11814 Out << Id->getName();
11815 } else {
11816 Out << '$' << I;
11817 }
11818
11819 Out << " = ";
11820 Args[I].print(Policy: getPrintingPolicy(), Out,
11821 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
11822 Policy: getPrintingPolicy(), TPL: Params, Idx: I));
11823 }
11824
11825 Out << ']';
11826 return std::string(Out.str());
11827}
11828
11829void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11830 CachedTokens &Toks) {
11831 if (!FD)
11832 return;
11833
11834 auto LPT = std::make_unique<LateParsedTemplate>();
11835
11836 // Take tokens to avoid allocations
11837 LPT->Toks.swap(RHS&: Toks);
11838 LPT->D = FnD;
11839 LPT->FPO = getCurFPFeatures();
11840 LateParsedTemplateMap.insert(KV: std::make_pair(x&: FD, y: std::move(LPT)));
11841
11842 FD->setLateTemplateParsed(true);
11843}
11844
11845void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11846 if (!FD)
11847 return;
11848 FD->setLateTemplateParsed(false);
11849}
11850
11851bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11852 DeclContext *DC = CurContext;
11853
11854 while (DC) {
11855 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
11856 const FunctionDecl *FD = RD->isLocalClass();
11857 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11858 } else if (DC->isTranslationUnit() || DC->isNamespace())
11859 return false;
11860
11861 DC = DC->getParent();
11862 }
11863 return false;
11864}
11865
11866namespace {
11867/// Walk the path from which a declaration was instantiated, and check
11868/// that every explicit specialization along that path is visible. This enforces
11869/// C++ [temp.expl.spec]/6:
11870///
11871/// If a template, a member template or a member of a class template is
11872/// explicitly specialized then that specialization shall be declared before
11873/// the first use of that specialization that would cause an implicit
11874/// instantiation to take place, in every translation unit in which such a
11875/// use occurs; no diagnostic is required.
11876///
11877/// and also C++ [temp.class.spec]/1:
11878///
11879/// A partial specialization shall be declared before the first use of a
11880/// class template specialization that would make use of the partial
11881/// specialization as the result of an implicit or explicit instantiation
11882/// in every translation unit in which such a use occurs; no diagnostic is
11883/// required.
11884class ExplicitSpecializationVisibilityChecker {
11885 Sema &S;
11886 SourceLocation Loc;
11887 llvm::SmallVector<Module *, 8> Modules;
11888 Sema::AcceptableKind Kind;
11889
11890public:
11891 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11892 Sema::AcceptableKind Kind)
11893 : S(S), Loc(Loc), Kind(Kind) {}
11894
11895 void check(NamedDecl *ND) {
11896 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
11897 return checkImpl(Spec: FD);
11898 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
11899 return checkImpl(Spec: RD);
11900 if (auto *VD = dyn_cast<VarDecl>(Val: ND))
11901 return checkImpl(Spec: VD);
11902 if (auto *ED = dyn_cast<EnumDecl>(Val: ND))
11903 return checkImpl(Spec: ED);
11904 }
11905
11906private:
11907 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11908 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11909 : Sema::MissingImportKind::ExplicitSpecialization;
11910 const bool Recover = true;
11911
11912 // If we got a custom set of modules (because only a subset of the
11913 // declarations are interesting), use them, otherwise let
11914 // diagnoseMissingImport intelligently pick some.
11915 if (Modules.empty())
11916 S.diagnoseMissingImport(Loc, Decl: D, MIK: Kind, Recover);
11917 else
11918 S.diagnoseMissingImport(Loc, Decl: D, DeclLoc: D->getLocation(), Modules, MIK: Kind, Recover);
11919 }
11920
11921 bool CheckMemberSpecialization(const NamedDecl *D) {
11922 return Kind == Sema::AcceptableKind::Visible
11923 ? S.hasVisibleMemberSpecialization(D)
11924 : S.hasReachableMemberSpecialization(D);
11925 }
11926
11927 bool CheckExplicitSpecialization(const NamedDecl *D) {
11928 return Kind == Sema::AcceptableKind::Visible
11929 ? S.hasVisibleExplicitSpecialization(D)
11930 : S.hasReachableExplicitSpecialization(D);
11931 }
11932
11933 bool CheckDeclaration(const NamedDecl *D) {
11934 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11935 : S.hasReachableDeclaration(D);
11936 }
11937
11938 // Check a specific declaration. There are three problematic cases:
11939 //
11940 // 1) The declaration is an explicit specialization of a template
11941 // specialization.
11942 // 2) The declaration is an explicit specialization of a member of an
11943 // templated class.
11944 // 3) The declaration is an instantiation of a template, and that template
11945 // is an explicit specialization of a member of a templated class.
11946 //
11947 // We don't need to go any deeper than that, as the instantiation of the
11948 // surrounding class / etc is not triggered by whatever triggered this
11949 // instantiation, and thus should be checked elsewhere.
11950 template<typename SpecDecl>
11951 void checkImpl(SpecDecl *Spec) {
11952 bool IsHiddenExplicitSpecialization = false;
11953 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11954 // Some invalid friend declarations are written as specializations but are
11955 // instantiated implicitly.
11956 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11957 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11958 if (SpecKind == TSK_ExplicitSpecialization) {
11959 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11960 ? !CheckMemberSpecialization(D: Spec)
11961 : !CheckExplicitSpecialization(D: Spec);
11962 } else {
11963 checkInstantiated(Spec);
11964 }
11965
11966 if (IsHiddenExplicitSpecialization)
11967 diagnose(D: Spec->getMostRecentDecl(), IsPartialSpec: false);
11968 }
11969
11970 void checkInstantiated(FunctionDecl *FD) {
11971 if (auto *TD = FD->getPrimaryTemplate())
11972 checkTemplate(TD);
11973 }
11974
11975 void checkInstantiated(CXXRecordDecl *RD) {
11976 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD);
11977 if (!SD)
11978 return;
11979
11980 auto From = SD->getSpecializedTemplateOrPartial();
11981 if (auto *TD = dyn_cast<ClassTemplateDecl *>(Val&: From))
11982 checkTemplate(TD);
11983 else if (auto *TD =
11984 dyn_cast<ClassTemplatePartialSpecializationDecl *>(Val&: From)) {
11985 if (!CheckDeclaration(D: TD))
11986 diagnose(D: TD, IsPartialSpec: true);
11987 checkTemplate(TD);
11988 }
11989 }
11990
11991 void checkInstantiated(VarDecl *RD) {
11992 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(Val: RD);
11993 if (!SD)
11994 return;
11995
11996 auto From = SD->getSpecializedTemplateOrPartial();
11997 if (auto *TD = dyn_cast<VarTemplateDecl *>(Val&: From))
11998 checkTemplate(TD);
11999 else if (auto *TD =
12000 dyn_cast<VarTemplatePartialSpecializationDecl *>(Val&: From)) {
12001 if (!CheckDeclaration(D: TD))
12002 diagnose(D: TD, IsPartialSpec: true);
12003 checkTemplate(TD);
12004 }
12005 }
12006
12007 void checkInstantiated(EnumDecl *FD) {}
12008
12009 template<typename TemplDecl>
12010 void checkTemplate(TemplDecl *TD) {
12011 if (TD->isMemberSpecialization()) {
12012 if (!CheckMemberSpecialization(D: TD))
12013 diagnose(D: TD->getMostRecentDecl(), IsPartialSpec: false);
12014 }
12015 }
12016};
12017} // end anonymous namespace
12018
12019void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
12020 if (!getLangOpts().Modules)
12021 return;
12022
12023 ExplicitSpecializationVisibilityChecker(*this, Loc,
12024 Sema::AcceptableKind::Visible)
12025 .check(ND: Spec);
12026}
12027
12028void Sema::checkSpecializationReachability(SourceLocation Loc,
12029 NamedDecl *Spec) {
12030 if (!getLangOpts().CPlusPlusModules)
12031 return checkSpecializationVisibility(Loc, Spec);
12032
12033 ExplicitSpecializationVisibilityChecker(*this, Loc,
12034 Sema::AcceptableKind::Reachable)
12035 .check(ND: Spec);
12036}
12037
12038SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
12039 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
12040 return N->getLocation();
12041 if (const auto *FD = dyn_cast<FunctionDecl>(Val: N)) {
12042 if (!FD->isFunctionTemplateSpecialization())
12043 return FD->getLocation();
12044 } else if (!isa<ClassTemplateSpecializationDecl,
12045 VarTemplateSpecializationDecl>(Val: N)) {
12046 return N->getLocation();
12047 }
12048 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
12049 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
12050 continue;
12051 return CSC.PointOfInstantiation;
12052 }
12053 return N->getLocation();
12054}
12055