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/ASTConsumer.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/Decl.h"
15#include "clang/AST/DeclFriend.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DynamicRecursiveASTVisitor.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/TemplateName.h"
21#include "clang/AST/TypeVisitor.h"
22#include "clang/Basic/Builtins.h"
23#include "clang/Basic/DiagnosticSema.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/PartialDiagnostic.h"
26#include "clang/Basic/SourceLocation.h"
27#include "clang/Basic/TargetInfo.h"
28#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/EnterExpressionEvaluationContext.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/SemaCUDA.h"
36#include "clang/Sema/SemaInternal.h"
37#include "clang/Sema/Template.h"
38#include "clang/Sema/TemplateDeduction.h"
39#include "llvm/ADT/SmallBitVector.h"
40#include "llvm/ADT/StringExtras.h"
41#include "llvm/Support/SaveAndRestore.h"
42
43#include <optional>
44using namespace clang;
45using namespace sema;
46
47// Exported for use by Parser.
48SourceRange
49clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
50 unsigned N) {
51 if (!N) return SourceRange();
52 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
53}
54
55unsigned Sema::getTemplateDepth(Scope *S) const {
56 unsigned Depth = 0;
57
58 // Each template parameter scope represents one level of template parameter
59 // depth.
60 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
61 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
62 ++Depth;
63 }
64
65 // Note that there are template parameters with the given depth.
66 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(a: Depth, b: D + 1); };
67
68 // Look for parameters of an enclosing generic lambda. We don't create a
69 // template parameter scope for these.
70 for (FunctionScopeInfo *FSI : getFunctionScopes()) {
71 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FSI)) {
72 if (!LSI->TemplateParams.empty()) {
73 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
74 break;
75 }
76 if (LSI->GLTemplateParameterList) {
77 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
78 break;
79 }
80 }
81 }
82
83 // Look for parameters of an enclosing terse function template. We don't
84 // create a template parameter scope for these either.
85 for (const InventedTemplateParameterInfo &Info :
86 getInventedParameterInfos()) {
87 if (!Info.TemplateParams.empty()) {
88 ParamsAtDepth(Info.AutoTemplateParameterDepth);
89 break;
90 }
91 }
92
93 return Depth;
94}
95
96/// \brief Determine whether the declaration found is acceptable as the name
97/// of a template and, if so, return that template declaration. Otherwise,
98/// returns null.
99///
100/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
101/// is true. In all other cases it will return a TemplateDecl (or null).
102NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
103 bool AllowFunctionTemplates,
104 bool AllowDependent) {
105 D = D->getUnderlyingDecl();
106
107 if (isa<TemplateDecl>(Val: D)) {
108 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(Val: D))
109 return nullptr;
110
111 return D;
112 }
113
114 if (const auto *Record = dyn_cast<CXXRecordDecl>(Val: D)) {
115 // C++ [temp.local]p1:
116 // Like normal (non-template) classes, class templates have an
117 // injected-class-name (Clause 9). The injected-class-name
118 // can be used with or without a template-argument-list. When
119 // it is used without a template-argument-list, it is
120 // equivalent to the injected-class-name followed by the
121 // template-parameters of the class template enclosed in
122 // <>. When it is used with a template-argument-list, it
123 // refers to the specified class template specialization,
124 // which could be the current specialization or another
125 // specialization.
126 if (Record->isInjectedClassName()) {
127 Record = cast<CXXRecordDecl>(Record->getDeclContext());
128 if (Record->getDescribedClassTemplate())
129 return Record->getDescribedClassTemplate();
130
131 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record))
132 return Spec->getSpecializedTemplate();
133 }
134
135 return nullptr;
136 }
137
138 // 'using Dependent::foo;' can resolve to a template name.
139 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
140 // injected-class-name).
141 if (AllowDependent && isa<UnresolvedUsingValueDecl>(Val: D))
142 return D;
143
144 return nullptr;
145}
146
147void Sema::FilterAcceptableTemplateNames(LookupResult &R,
148 bool AllowFunctionTemplates,
149 bool AllowDependent) {
150 LookupResult::Filter filter = R.makeFilter();
151 while (filter.hasNext()) {
152 NamedDecl *Orig = filter.next();
153 if (!getAsTemplateNameDecl(D: Orig, AllowFunctionTemplates, AllowDependent))
154 filter.erase();
155 }
156 filter.done();
157}
158
159bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
160 bool AllowFunctionTemplates,
161 bool AllowDependent,
162 bool AllowNonTemplateFunctions) {
163 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
164 if (getAsTemplateNameDecl(D: *I, AllowFunctionTemplates, AllowDependent))
165 return true;
166 if (AllowNonTemplateFunctions &&
167 isa<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
168 return true;
169 }
170
171 return false;
172}
173
174TemplateNameKind Sema::isTemplateName(Scope *S,
175 CXXScopeSpec &SS,
176 bool hasTemplateKeyword,
177 const UnqualifiedId &Name,
178 ParsedType ObjectTypePtr,
179 bool EnteringContext,
180 TemplateTy &TemplateResult,
181 bool &MemberOfUnknownSpecialization,
182 bool Disambiguation) {
183 assert(getLangOpts().CPlusPlus && "No template names in C!");
184
185 DeclarationName TName;
186 MemberOfUnknownSpecialization = false;
187
188 switch (Name.getKind()) {
189 case UnqualifiedIdKind::IK_Identifier:
190 TName = DeclarationName(Name.Identifier);
191 break;
192
193 case UnqualifiedIdKind::IK_OperatorFunctionId:
194 TName = Context.DeclarationNames.getCXXOperatorName(
195 Op: Name.OperatorFunctionId.Operator);
196 break;
197
198 case UnqualifiedIdKind::IK_LiteralOperatorId:
199 TName = Context.DeclarationNames.getCXXLiteralOperatorName(II: Name.Identifier);
200 break;
201
202 default:
203 return TNK_Non_template;
204 }
205
206 QualType ObjectType = ObjectTypePtr.get();
207
208 AssumedTemplateKind AssumedTemplate;
209 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
210 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
211 /*RequiredTemplate=*/SourceLocation(),
212 ATK: &AssumedTemplate,
213 /*AllowTypoCorrection=*/!Disambiguation))
214 return TNK_Non_template;
215 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
216
217 if (AssumedTemplate != AssumedTemplateKind::None) {
218 TemplateResult = TemplateTy::make(P: Context.getAssumedTemplateName(Name: TName));
219 // Let the parser know whether we found nothing or found functions; if we
220 // found nothing, we want to more carefully check whether this is actually
221 // a function template name versus some other kind of undeclared identifier.
222 return AssumedTemplate == AssumedTemplateKind::FoundNothing
223 ? TNK_Undeclared_template
224 : TNK_Function_template;
225 }
226
227 if (R.empty())
228 return TNK_Non_template;
229
230 NamedDecl *D = nullptr;
231 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *R.begin());
232 if (R.isAmbiguous()) {
233 // If we got an ambiguity involving a non-function template, treat this
234 // as a template name, and pick an arbitrary template for error recovery.
235 bool AnyFunctionTemplates = false;
236 for (NamedDecl *FoundD : R) {
237 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(D: FoundD)) {
238 if (isa<FunctionTemplateDecl>(Val: FoundTemplate))
239 AnyFunctionTemplates = true;
240 else {
241 D = FoundTemplate;
242 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: FoundD);
243 break;
244 }
245 }
246 }
247
248 // If we didn't find any templates at all, this isn't a template name.
249 // Leave the ambiguity for a later lookup to diagnose.
250 if (!D && !AnyFunctionTemplates) {
251 R.suppressDiagnostics();
252 return TNK_Non_template;
253 }
254
255 // If the only templates were function templates, filter out the rest.
256 // We'll diagnose the ambiguity later.
257 if (!D)
258 FilterAcceptableTemplateNames(R);
259 }
260
261 // At this point, we have either picked a single template name declaration D
262 // or we have a non-empty set of results R containing either one template name
263 // declaration or a set of function templates.
264
265 TemplateName Template;
266 TemplateNameKind TemplateKind;
267
268 unsigned ResultCount = R.end() - R.begin();
269 if (!D && ResultCount > 1) {
270 // We assume that we'll preserve the qualifier from a function
271 // template name in other ways.
272 Template = Context.getOverloadedTemplateName(Begin: R.begin(), End: R.end());
273 TemplateKind = TNK_Function_template;
274
275 // We'll do this lookup again later.
276 R.suppressDiagnostics();
277 } else {
278 if (!D) {
279 D = getAsTemplateNameDecl(D: *R.begin());
280 assert(D && "unambiguous result is not a template name");
281 }
282
283 if (isa<UnresolvedUsingValueDecl>(Val: D)) {
284 // We don't yet know whether this is a template-name or not.
285 MemberOfUnknownSpecialization = true;
286 return TNK_Non_template;
287 }
288
289 TemplateDecl *TD = cast<TemplateDecl>(Val: D);
290 Template =
291 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
292 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
293 if (!SS.isInvalid()) {
294 NestedNameSpecifier *Qualifier = SS.getScopeRep();
295 Template = Context.getQualifiedTemplateName(NNS: Qualifier, TemplateKeyword: hasTemplateKeyword,
296 Template);
297 }
298
299 if (isa<FunctionTemplateDecl>(Val: TD)) {
300 TemplateKind = TNK_Function_template;
301
302 // We'll do this lookup again later.
303 R.suppressDiagnostics();
304 } else {
305 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
306 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
307 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
308 TemplateKind =
309 isa<VarTemplateDecl>(Val: TD) ? TNK_Var_template :
310 isa<ConceptDecl>(Val: TD) ? TNK_Concept_template :
311 TNK_Type_template;
312 }
313 }
314
315 TemplateResult = TemplateTy::make(P: Template);
316 return TemplateKind;
317}
318
319bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
320 SourceLocation NameLoc, CXXScopeSpec &SS,
321 ParsedTemplateTy *Template /*=nullptr*/) {
322 // We could use redeclaration lookup here, but we don't need to: the
323 // syntactic form of a deduction guide is enough to identify it even
324 // if we can't look up the template name at all.
325 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
326 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
327 /*EnteringContext*/ false))
328 return false;
329
330 if (R.empty()) return false;
331 if (R.isAmbiguous()) {
332 // FIXME: Diagnose an ambiguity if we find at least one template.
333 R.suppressDiagnostics();
334 return false;
335 }
336
337 // We only treat template-names that name type templates as valid deduction
338 // guide names.
339 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
340 if (!TD || !getAsTypeTemplateDecl(TD))
341 return false;
342
343 if (Template) {
344 TemplateName Name = Context.getQualifiedTemplateName(
345 NNS: SS.getScopeRep(), /*TemplateKeyword=*/false, Template: TemplateName(TD));
346 *Template = TemplateTy::make(P: Name);
347 }
348 return true;
349}
350
351bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
352 SourceLocation IILoc,
353 Scope *S,
354 const CXXScopeSpec *SS,
355 TemplateTy &SuggestedTemplate,
356 TemplateNameKind &SuggestedKind) {
357 // We can't recover unless there's a dependent scope specifier preceding the
358 // template name.
359 // FIXME: Typo correction?
360 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(SS: *SS) ||
361 computeDeclContext(SS: *SS))
362 return false;
363
364 // The code is missing a 'template' keyword prior to the dependent template
365 // name.
366 NestedNameSpecifier *Qualifier = (NestedNameSpecifier *)SS->getScopeRep();
367 SuggestedTemplate = TemplateTy::make(P: Context.getDependentTemplateName(
368 Name: {Qualifier, &II, /*HasTemplateKeyword=*/false}));
369 Diag(IILoc, diag::err_template_kw_missing)
370 << SuggestedTemplate.get()
371 << FixItHint::CreateInsertion(IILoc, "template ");
372 SuggestedKind = TNK_Dependent_template_name;
373 return true;
374}
375
376bool Sema::LookupTemplateName(LookupResult &Found, Scope *S, CXXScopeSpec &SS,
377 QualType ObjectType, bool EnteringContext,
378 RequiredTemplateKind RequiredTemplate,
379 AssumedTemplateKind *ATK,
380 bool AllowTypoCorrection) {
381 if (ATK)
382 *ATK = AssumedTemplateKind::None;
383
384 if (SS.isInvalid())
385 return true;
386
387 Found.setTemplateNameLookup(true);
388
389 // Determine where to perform name lookup
390 DeclContext *LookupCtx = nullptr;
391 bool IsDependent = false;
392 if (!ObjectType.isNull()) {
393 // This nested-name-specifier occurs in a member access expression, e.g.,
394 // x->B::f, and we are looking into the type of the object.
395 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
396 LookupCtx = computeDeclContext(T: ObjectType);
397 IsDependent = !LookupCtx && ObjectType->isDependentType();
398 assert((IsDependent || !ObjectType->isIncompleteType() ||
399 !ObjectType->getAs<TagType>() ||
400 ObjectType->castAs<TagType>()->isBeingDefined()) &&
401 "Caller should have completed object type");
402
403 // Template names cannot appear inside an Objective-C class or object type
404 // or a vector type.
405 //
406 // FIXME: This is wrong. For example:
407 //
408 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
409 // Vec<int> vi;
410 // vi.Vec<int>::~Vec<int>();
411 //
412 // ... should be accepted but we will not treat 'Vec' as a template name
413 // here. The right thing to do would be to check if the name is a valid
414 // vector component name, and look up a template name if not. And similarly
415 // for lookups into Objective-C class and object types, where the same
416 // problem can arise.
417 if (ObjectType->isObjCObjectOrInterfaceType() ||
418 ObjectType->isVectorType()) {
419 Found.clear();
420 return false;
421 }
422 } else if (SS.isNotEmpty()) {
423 // This nested-name-specifier occurs after another nested-name-specifier,
424 // so long into the context associated with the prior nested-name-specifier.
425 LookupCtx = computeDeclContext(SS, EnteringContext);
426 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
427
428 // The declaration context must be complete.
429 if (LookupCtx && RequireCompleteDeclContext(SS, DC: LookupCtx))
430 return true;
431 }
432
433 bool ObjectTypeSearchedInScope = false;
434 bool AllowFunctionTemplatesInLookup = true;
435 if (LookupCtx) {
436 // Perform "qualified" name lookup into the declaration context we
437 // computed, which is either the type of the base of a member access
438 // expression or the declaration context associated with a prior
439 // nested-name-specifier.
440 LookupQualifiedName(R&: Found, LookupCtx);
441
442 // FIXME: The C++ standard does not clearly specify what happens in the
443 // case where the object type is dependent, and implementations vary. In
444 // Clang, we treat a name after a . or -> as a template-name if lookup
445 // finds a non-dependent member or member of the current instantiation that
446 // is a type template, or finds no such members and lookup in the context
447 // of the postfix-expression finds a type template. In the latter case, the
448 // name is nonetheless dependent, and we may resolve it to a member of an
449 // unknown specialization when we come to instantiate the template.
450 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
451 }
452
453 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
454 // C++ [basic.lookup.classref]p1:
455 // In a class member access expression (5.2.5), if the . or -> token is
456 // immediately followed by an identifier followed by a <, the
457 // identifier must be looked up to determine whether the < is the
458 // beginning of a template argument list (14.2) or a less-than operator.
459 // The identifier is first looked up in the class of the object
460 // expression. If the identifier is not found, it is then looked up in
461 // the context of the entire postfix-expression and shall name a class
462 // template.
463 if (S)
464 LookupName(R&: Found, S);
465
466 if (!ObjectType.isNull()) {
467 // FIXME: We should filter out all non-type templates here, particularly
468 // variable templates and concepts. But the exclusion of alias templates
469 // and template template parameters is a wording defect.
470 AllowFunctionTemplatesInLookup = false;
471 ObjectTypeSearchedInScope = true;
472 }
473
474 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
475 }
476
477 if (Found.isAmbiguous())
478 return false;
479
480 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
481 !RequiredTemplate.hasTemplateKeyword()) {
482 // C++2a [temp.names]p2:
483 // A name is also considered to refer to a template if it is an
484 // unqualified-id followed by a < and name lookup finds either one or more
485 // functions or finds nothing.
486 //
487 // To keep our behavior consistent, we apply the "finds nothing" part in
488 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
489 // successfully form a call to an undeclared template-id.
490 bool AllFunctions =
491 getLangOpts().CPlusPlus20 && llvm::all_of(Range&: Found, P: [](NamedDecl *ND) {
492 return isa<FunctionDecl>(Val: ND->getUnderlyingDecl());
493 });
494 if (AllFunctions || (Found.empty() && !IsDependent)) {
495 // If lookup found any functions, or if this is a name that can only be
496 // used for a function, then strongly assume this is a function
497 // template-id.
498 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
499 ? AssumedTemplateKind::FoundNothing
500 : AssumedTemplateKind::FoundFunctions;
501 Found.clear();
502 return false;
503 }
504 }
505
506 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
507 // If we did not find any names, and this is not a disambiguation, attempt
508 // to correct any typos.
509 DeclarationName Name = Found.getLookupName();
510 Found.clear();
511 // Simple filter callback that, for keywords, only accepts the C++ *_cast
512 DefaultFilterCCC FilterCCC{};
513 FilterCCC.WantTypeSpecifiers = false;
514 FilterCCC.WantExpressionKeywords = false;
515 FilterCCC.WantRemainingKeywords = false;
516 FilterCCC.WantCXXNamedCasts = true;
517 if (TypoCorrection Corrected = CorrectTypo(
518 Typo: Found.getLookupNameInfo(), LookupKind: Found.getLookupKind(), S, SS: &SS, CCC&: FilterCCC,
519 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
520 if (auto *ND = Corrected.getFoundDecl())
521 Found.addDecl(D: ND);
522 FilterAcceptableTemplateNames(R&: Found);
523 if (Found.isAmbiguous()) {
524 Found.clear();
525 } else if (!Found.empty()) {
526 // Do not erase the typo-corrected result to avoid duplicated
527 // diagnostics.
528 AllowFunctionTemplatesInLookup = true;
529 Found.setLookupName(Corrected.getCorrection());
530 if (LookupCtx) {
531 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
532 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
533 Name.getAsString() == CorrectedStr;
534 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
535 << Name << LookupCtx << DroppedSpecifier
536 << SS.getRange());
537 } else {
538 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
539 }
540 }
541 }
542 }
543
544 NamedDecl *ExampleLookupResult =
545 Found.empty() ? nullptr : Found.getRepresentativeDecl();
546 FilterAcceptableTemplateNames(R&: Found, AllowFunctionTemplates: AllowFunctionTemplatesInLookup);
547 if (Found.empty()) {
548 if (IsDependent) {
549 Found.setNotFoundInCurrentInstantiation();
550 return false;
551 }
552
553 // If a 'template' keyword was used, a lookup that finds only non-template
554 // names is an error.
555 if (ExampleLookupResult && RequiredTemplate) {
556 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
557 << Found.getLookupName() << SS.getRange()
558 << RequiredTemplate.hasTemplateKeyword()
559 << RequiredTemplate.getTemplateKeywordLoc();
560 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
561 diag::note_template_kw_refers_to_non_template)
562 << Found.getLookupName();
563 return true;
564 }
565
566 return false;
567 }
568
569 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
570 !getLangOpts().CPlusPlus11) {
571 // C++03 [basic.lookup.classref]p1:
572 // [...] If the lookup in the class of the object expression finds a
573 // template, the name is also looked up in the context of the entire
574 // postfix-expression and [...]
575 //
576 // Note: C++11 does not perform this second lookup.
577 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
578 LookupOrdinaryName);
579 FoundOuter.setTemplateNameLookup(true);
580 LookupName(R&: FoundOuter, S);
581 // FIXME: We silently accept an ambiguous lookup here, in violation of
582 // [basic.lookup]/1.
583 FilterAcceptableTemplateNames(R&: FoundOuter, /*AllowFunctionTemplates=*/false);
584
585 NamedDecl *OuterTemplate;
586 if (FoundOuter.empty()) {
587 // - if the name is not found, the name found in the class of the
588 // object expression is used, otherwise
589 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
590 !(OuterTemplate =
591 getAsTemplateNameDecl(D: FoundOuter.getFoundDecl()))) {
592 // - if the name is found in the context of the entire
593 // postfix-expression and does not name a class template, the name
594 // found in the class of the object expression is used, otherwise
595 FoundOuter.clear();
596 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
597 // - if the name found is a class template, it must refer to the same
598 // entity as the one found in the class of the object expression,
599 // otherwise the program is ill-formed.
600 if (!Found.isSingleResult() ||
601 getAsTemplateNameDecl(D: Found.getFoundDecl())->getCanonicalDecl() !=
602 OuterTemplate->getCanonicalDecl()) {
603 Diag(Found.getNameLoc(),
604 diag::ext_nested_name_member_ref_lookup_ambiguous)
605 << Found.getLookupName()
606 << ObjectType;
607 Diag(Found.getRepresentativeDecl()->getLocation(),
608 diag::note_ambig_member_ref_object_type)
609 << ObjectType;
610 Diag(FoundOuter.getFoundDecl()->getLocation(),
611 diag::note_ambig_member_ref_scope);
612
613 // Recover by taking the template that we found in the object
614 // expression's type.
615 }
616 }
617 }
618
619 return false;
620}
621
622void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
623 SourceLocation Less,
624 SourceLocation Greater) {
625 if (TemplateName.isInvalid())
626 return;
627
628 DeclarationNameInfo NameInfo;
629 CXXScopeSpec SS;
630 LookupNameKind LookupKind;
631
632 DeclContext *LookupCtx = nullptr;
633 NamedDecl *Found = nullptr;
634 bool MissingTemplateKeyword = false;
635
636 // Figure out what name we looked up.
637 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: TemplateName.get())) {
638 NameInfo = DRE->getNameInfo();
639 SS.Adopt(Other: DRE->getQualifierLoc());
640 LookupKind = LookupOrdinaryName;
641 Found = DRE->getFoundDecl();
642 } else if (auto *ME = dyn_cast<MemberExpr>(Val: TemplateName.get())) {
643 NameInfo = ME->getMemberNameInfo();
644 SS.Adopt(Other: ME->getQualifierLoc());
645 LookupKind = LookupMemberName;
646 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
647 Found = ME->getMemberDecl();
648 } else if (auto *DSDRE =
649 dyn_cast<DependentScopeDeclRefExpr>(Val: TemplateName.get())) {
650 NameInfo = DSDRE->getNameInfo();
651 SS.Adopt(Other: DSDRE->getQualifierLoc());
652 MissingTemplateKeyword = true;
653 } else if (auto *DSME =
654 dyn_cast<CXXDependentScopeMemberExpr>(Val: TemplateName.get())) {
655 NameInfo = DSME->getMemberNameInfo();
656 SS.Adopt(Other: DSME->getQualifierLoc());
657 MissingTemplateKeyword = true;
658 } else {
659 llvm_unreachable("unexpected kind of potential template name");
660 }
661
662 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
663 // was missing.
664 if (MissingTemplateKeyword) {
665 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
666 << NameInfo.getName() << SourceRange(Less, Greater);
667 return;
668 }
669
670 // Try to correct the name by looking for templates and C++ named casts.
671 struct TemplateCandidateFilter : CorrectionCandidateCallback {
672 Sema &S;
673 TemplateCandidateFilter(Sema &S) : S(S) {
674 WantTypeSpecifiers = false;
675 WantExpressionKeywords = false;
676 WantRemainingKeywords = false;
677 WantCXXNamedCasts = true;
678 };
679 bool ValidateCandidate(const TypoCorrection &Candidate) override {
680 if (auto *ND = Candidate.getCorrectionDecl())
681 return S.getAsTemplateNameDecl(D: ND);
682 return Candidate.isKeyword();
683 }
684
685 std::unique_ptr<CorrectionCandidateCallback> clone() override {
686 return std::make_unique<TemplateCandidateFilter>(args&: *this);
687 }
688 };
689
690 DeclarationName Name = NameInfo.getName();
691 TemplateCandidateFilter CCC(*this);
692 if (TypoCorrection Corrected =
693 CorrectTypo(Typo: NameInfo, LookupKind, S, SS: &SS, CCC,
694 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
695 auto *ND = Corrected.getFoundDecl();
696 if (ND)
697 ND = getAsTemplateNameDecl(D: ND);
698 if (ND || Corrected.isKeyword()) {
699 if (LookupCtx) {
700 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
701 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
702 Name.getAsString() == CorrectedStr;
703 diagnoseTypo(Corrected,
704 PDiag(diag::err_non_template_in_member_template_id_suggest)
705 << Name << LookupCtx << DroppedSpecifier
706 << SS.getRange(), false);
707 } else {
708 diagnoseTypo(Corrected,
709 PDiag(diag::err_non_template_in_template_id_suggest)
710 << Name, false);
711 }
712 if (Found)
713 Diag(Found->getLocation(),
714 diag::note_non_template_in_template_id_found);
715 return;
716 }
717 }
718
719 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
720 << Name << SourceRange(Less, Greater);
721 if (Found)
722 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
723}
724
725ExprResult
726Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
727 SourceLocation TemplateKWLoc,
728 const DeclarationNameInfo &NameInfo,
729 bool isAddressOfOperand,
730 const TemplateArgumentListInfo *TemplateArgs) {
731 if (SS.isEmpty()) {
732 // FIXME: This codepath is only used by dependent unqualified names
733 // (e.g. a dependent conversion-function-id, or operator= once we support
734 // it). It doesn't quite do the right thing, and it will silently fail if
735 // getCurrentThisType() returns null.
736 QualType ThisType = getCurrentThisType();
737 if (ThisType.isNull())
738 return ExprError();
739
740 return CXXDependentScopeMemberExpr::Create(
741 Ctx: Context, /*Base=*/nullptr, BaseType: ThisType,
742 /*IsArrow=*/!Context.getLangOpts().HLSL,
743 /*OperatorLoc=*/SourceLocation(),
744 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
745 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
746 }
747 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
748}
749
750ExprResult
751Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
752 SourceLocation TemplateKWLoc,
753 const DeclarationNameInfo &NameInfo,
754 const TemplateArgumentListInfo *TemplateArgs) {
755 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
756 if (!SS.isValid())
757 return CreateRecoveryExpr(
758 Begin: SS.getBeginLoc(),
759 End: TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), SubExprs: {});
760
761 return DependentScopeDeclRefExpr::Create(
762 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
763 TemplateArgs);
764}
765
766bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
767 NamedDecl *Instantiation,
768 bool InstantiatedFromMember,
769 const NamedDecl *Pattern,
770 const NamedDecl *PatternDef,
771 TemplateSpecializationKind TSK,
772 bool Complain, bool *Unreachable) {
773 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
774 isa<VarDecl>(Instantiation));
775
776 bool IsEntityBeingDefined = false;
777 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(Val: PatternDef))
778 IsEntityBeingDefined = TD->isBeingDefined();
779
780 if (PatternDef && !IsEntityBeingDefined) {
781 NamedDecl *SuggestedDef = nullptr;
782 if (!hasReachableDefinition(D: const_cast<NamedDecl *>(PatternDef),
783 Suggested: &SuggestedDef,
784 /*OnlyNeedComplete*/ false)) {
785 if (Unreachable)
786 *Unreachable = true;
787 // If we're allowed to diagnose this and recover, do so.
788 bool Recover = Complain && !isSFINAEContext();
789 if (Complain)
790 diagnoseMissingImport(Loc: PointOfInstantiation, Decl: SuggestedDef,
791 MIK: Sema::MissingImportKind::Definition, Recover);
792 return !Recover;
793 }
794 return false;
795 }
796
797 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
798 return true;
799
800 QualType InstantiationTy;
801 if (TagDecl *TD = dyn_cast<TagDecl>(Val: Instantiation))
802 InstantiationTy = Context.getTypeDeclType(TD);
803 if (PatternDef) {
804 Diag(PointOfInstantiation,
805 diag::err_template_instantiate_within_definition)
806 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
807 << InstantiationTy;
808 // Not much point in noting the template declaration here, since
809 // we're lexically inside it.
810 Instantiation->setInvalidDecl();
811 } else if (InstantiatedFromMember) {
812 if (isa<FunctionDecl>(Val: Instantiation)) {
813 Diag(PointOfInstantiation,
814 diag::err_explicit_instantiation_undefined_member)
815 << /*member function*/ 1 << Instantiation->getDeclName()
816 << Instantiation->getDeclContext();
817 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
818 } else {
819 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
820 Diag(PointOfInstantiation,
821 diag::err_implicit_instantiate_member_undefined)
822 << InstantiationTy;
823 Diag(Pattern->getLocation(), diag::note_member_declared_at);
824 }
825 } else {
826 if (isa<FunctionDecl>(Val: Instantiation)) {
827 Diag(PointOfInstantiation,
828 diag::err_explicit_instantiation_undefined_func_template)
829 << Pattern;
830 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
831 } else if (isa<TagDecl>(Val: Instantiation)) {
832 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
833 << (TSK != TSK_ImplicitInstantiation)
834 << InstantiationTy;
835 NoteTemplateLocation(Decl: *Pattern);
836 } else {
837 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
838 if (isa<VarTemplateSpecializationDecl>(Val: Instantiation)) {
839 Diag(PointOfInstantiation,
840 diag::err_explicit_instantiation_undefined_var_template)
841 << Instantiation;
842 Instantiation->setInvalidDecl();
843 } else
844 Diag(PointOfInstantiation,
845 diag::err_explicit_instantiation_undefined_member)
846 << /*static data member*/ 2 << Instantiation->getDeclName()
847 << Instantiation->getDeclContext();
848 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
849 }
850 }
851
852 // In general, Instantiation isn't marked invalid to get more than one
853 // error for multiple undefined instantiations. But the code that does
854 // explicit declaration -> explicit definition conversion can't handle
855 // invalid declarations, so mark as invalid in that case.
856 if (TSK == TSK_ExplicitInstantiationDeclaration)
857 Instantiation->setInvalidDecl();
858 return true;
859}
860
861void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
862 bool SupportedForCompatibility) {
863 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
864
865 // C++23 [temp.local]p6:
866 // The name of a template-parameter shall not be bound to any following.
867 // declaration whose locus is contained by the scope to which the
868 // template-parameter belongs.
869 //
870 // When MSVC compatibility is enabled, the diagnostic is always a warning
871 // by default. Otherwise, it an error unless SupportedForCompatibility is
872 // true, in which case it is a default-to-error warning.
873 unsigned DiagId =
874 getLangOpts().MSVCCompat
875 ? diag::ext_template_param_shadow
876 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
877 : diag::err_template_param_shadow);
878 const auto *ND = cast<NamedDecl>(Val: PrevDecl);
879 Diag(Loc, DiagId) << ND->getDeclName();
880 NoteTemplateParameterLocation(Decl: *ND);
881}
882
883TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
884 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(Val: D)) {
885 D = Temp->getTemplatedDecl();
886 return Temp;
887 }
888 return nullptr;
889}
890
891ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
892 SourceLocation EllipsisLoc) const {
893 assert(Kind == Template &&
894 "Only template template arguments can be pack expansions here");
895 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
896 "Template template argument pack expansion without packs");
897 ParsedTemplateArgument Result(*this);
898 Result.EllipsisLoc = EllipsisLoc;
899 return Result;
900}
901
902static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
903 const ParsedTemplateArgument &Arg) {
904
905 switch (Arg.getKind()) {
906 case ParsedTemplateArgument::Type: {
907 TypeSourceInfo *DI;
908 QualType T = SemaRef.GetTypeFromParser(Ty: Arg.getAsType(), TInfo: &DI);
909 if (!DI)
910 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc: Arg.getLocation());
911 return TemplateArgumentLoc(TemplateArgument(T), DI);
912 }
913
914 case ParsedTemplateArgument::NonType: {
915 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
916 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
917 }
918
919 case ParsedTemplateArgument::Template: {
920 TemplateName Template = Arg.getAsTemplate().get();
921 TemplateArgument TArg;
922 if (Arg.getEllipsisLoc().isValid())
923 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
924 else
925 TArg = Template;
926 return TemplateArgumentLoc(
927 SemaRef.Context, TArg,
928 Arg.getScopeSpec().getWithLocInContext(Context&: SemaRef.Context),
929 Arg.getLocation(), Arg.getEllipsisLoc());
930 }
931 }
932
933 llvm_unreachable("Unhandled parsed template argument");
934}
935
936void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
937 TemplateArgumentListInfo &TemplateArgs) {
938 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
939 TemplateArgs.addArgument(Loc: translateTemplateArgument(SemaRef&: *this,
940 Arg: TemplateArgsIn[I]));
941}
942
943static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
944 SourceLocation Loc,
945 const IdentifierInfo *Name) {
946 NamedDecl *PrevDecl =
947 SemaRef.LookupSingleName(S, Name, Loc, NameKind: Sema::LookupOrdinaryName,
948 Redecl: RedeclarationKind::ForVisibleRedeclaration);
949 if (PrevDecl && PrevDecl->isTemplateParameter())
950 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
951}
952
953ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
954 TypeSourceInfo *TInfo;
955 QualType T = GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TInfo);
956 if (T.isNull())
957 return ParsedTemplateArgument();
958 assert(TInfo && "template argument with no location");
959
960 // If we might have formed a deduced template specialization type, convert
961 // it to a template template argument.
962 if (getLangOpts().CPlusPlus17) {
963 TypeLoc TL = TInfo->getTypeLoc();
964 SourceLocation EllipsisLoc;
965 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
966 EllipsisLoc = PET.getEllipsisLoc();
967 TL = PET.getPatternLoc();
968 }
969
970 CXXScopeSpec SS;
971 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
972 SS.Adopt(Other: ET.getQualifierLoc());
973 TL = ET.getNamedTypeLoc();
974 }
975
976 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
977 TemplateName Name = DTST.getTypePtr()->getTemplateName();
978 ParsedTemplateArgument Result(SS, TemplateTy::make(P: Name),
979 DTST.getTemplateNameLoc());
980 if (EllipsisLoc.isValid())
981 Result = Result.getTemplatePackExpansion(EllipsisLoc);
982 return Result;
983 }
984 }
985
986 // This is a normal type template argument. Note, if the type template
987 // argument is an injected-class-name for a template, it has a dual nature
988 // and can be used as either a type or a template. We handle that in
989 // convertTypeTemplateArgumentToTemplate.
990 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
991 ParsedType.get().getAsOpaquePtr(),
992 TInfo->getTypeLoc().getBeginLoc());
993}
994
995NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
996 SourceLocation EllipsisLoc,
997 SourceLocation KeyLoc,
998 IdentifierInfo *ParamName,
999 SourceLocation ParamNameLoc,
1000 unsigned Depth, unsigned Position,
1001 SourceLocation EqualLoc,
1002 ParsedType DefaultArg,
1003 bool HasTypeConstraint) {
1004 assert(S->isTemplateParamScope() &&
1005 "Template type parameter not in template parameter scope!");
1006
1007 bool IsParameterPack = EllipsisLoc.isValid();
1008 TemplateTypeParmDecl *Param
1009 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1010 KeyLoc, ParamNameLoc, Depth, Position,
1011 ParamName, Typename, IsParameterPack,
1012 HasTypeConstraint);
1013 Param->setAccess(AS_public);
1014
1015 if (Param->isParameterPack())
1016 if (auto *CSI = getEnclosingLambdaOrBlock())
1017 CSI->LocalPacks.push_back(Param);
1018
1019 if (ParamName) {
1020 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: ParamNameLoc, Name: ParamName);
1021
1022 // Add the template parameter into the current scope.
1023 S->AddDecl(Param);
1024 IdResolver.AddDecl(Param);
1025 }
1026
1027 // C++0x [temp.param]p9:
1028 // A default template-argument may be specified for any kind of
1029 // template-parameter that is not a template parameter pack.
1030 if (DefaultArg && IsParameterPack) {
1031 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1032 DefaultArg = nullptr;
1033 }
1034
1035 // Handle the default argument, if provided.
1036 if (DefaultArg) {
1037 TypeSourceInfo *DefaultTInfo;
1038 GetTypeFromParser(Ty: DefaultArg, TInfo: &DefaultTInfo);
1039
1040 assert(DefaultTInfo && "expected source information for type");
1041
1042 // Check for unexpanded parameter packs.
1043 if (DiagnoseUnexpandedParameterPack(Loc: ParamNameLoc, T: DefaultTInfo,
1044 UPPC: UPPC_DefaultArgument))
1045 return Param;
1046
1047 // Check the template argument itself.
1048 if (CheckTemplateArgument(Arg: DefaultTInfo)) {
1049 Param->setInvalidDecl();
1050 return Param;
1051 }
1052
1053 Param->setDefaultArgument(
1054 C: Context, DefArg: TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1055 }
1056
1057 return Param;
1058}
1059
1060/// Convert the parser's template argument list representation into our form.
1061static TemplateArgumentListInfo
1062makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1063 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1064 TemplateId.RAngleLoc);
1065 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1066 TemplateId.NumArgs);
1067 S.translateTemplateArguments(TemplateArgsIn: TemplateArgsPtr, TemplateArgs);
1068 return TemplateArgs;
1069}
1070
1071bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1072
1073 TemplateName TN = TypeConstr->Template.get();
1074 ConceptDecl *CD = cast<ConceptDecl>(Val: TN.getAsTemplateDecl());
1075
1076 // C++2a [temp.param]p4:
1077 // [...] The concept designated by a type-constraint shall be a type
1078 // concept ([temp.concept]).
1079 if (!CD->isTypeConcept()) {
1080 Diag(TypeConstr->TemplateNameLoc,
1081 diag::err_type_constraint_non_type_concept);
1082 return true;
1083 }
1084
1085 if (CheckConceptUseInDefinition(Concept: CD, Loc: TypeConstr->TemplateNameLoc))
1086 return true;
1087
1088 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1089
1090 if (!WereArgsSpecified &&
1091 CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1092 Diag(TypeConstr->TemplateNameLoc,
1093 diag::err_type_constraint_missing_arguments)
1094 << CD;
1095 return true;
1096 }
1097 return false;
1098}
1099
1100bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1101 TemplateIdAnnotation *TypeConstr,
1102 TemplateTypeParmDecl *ConstrainedParameter,
1103 SourceLocation EllipsisLoc) {
1104 return BuildTypeConstraint(SS, TypeConstraint: TypeConstr, ConstrainedParameter, EllipsisLoc,
1105 AllowUnexpandedPack: false);
1106}
1107
1108bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1109 TemplateIdAnnotation *TypeConstr,
1110 TemplateTypeParmDecl *ConstrainedParameter,
1111 SourceLocation EllipsisLoc,
1112 bool AllowUnexpandedPack) {
1113
1114 if (CheckTypeConstraint(TypeConstr))
1115 return true;
1116
1117 TemplateName TN = TypeConstr->Template.get();
1118 ConceptDecl *CD = cast<ConceptDecl>(Val: TN.getAsTemplateDecl());
1119 UsingShadowDecl *USD = TN.getAsUsingShadowDecl();
1120
1121 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1122 TypeConstr->TemplateNameLoc);
1123
1124 TemplateArgumentListInfo TemplateArgs;
1125 if (TypeConstr->LAngleLoc.isValid()) {
1126 TemplateArgs =
1127 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TypeConstr);
1128
1129 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1130 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1131 if (DiagnoseUnexpandedParameterPack(Arg, UPPC: UPPC_TypeConstraint))
1132 return true;
1133 }
1134 }
1135 }
1136 return AttachTypeConstraint(
1137 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1138 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(Val: USD) : CD,
1139 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1140 ConstrainedParameter, EllipsisLoc);
1141}
1142
1143template <typename ArgumentLocAppender>
1144static ExprResult formImmediatelyDeclaredConstraint(
1145 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1146 ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1147 SourceLocation RAngleLoc, QualType ConstrainedType,
1148 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1149 SourceLocation EllipsisLoc) {
1150
1151 TemplateArgumentListInfo ConstraintArgs;
1152 ConstraintArgs.addArgument(
1153 Loc: S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(ConstrainedType),
1154 /*NTTPType=*/QualType(), Loc: ParamNameLoc));
1155
1156 ConstraintArgs.setRAngleLoc(RAngleLoc);
1157 ConstraintArgs.setLAngleLoc(LAngleLoc);
1158 Appender(ConstraintArgs);
1159
1160 // C++2a [temp.param]p4:
1161 // [...] This constraint-expression E is called the immediately-declared
1162 // constraint of T. [...]
1163 CXXScopeSpec SS;
1164 SS.Adopt(Other: NS);
1165 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1166 SS, /*TemplateKWLoc=*/SourceLocation(), ConceptNameInfo: NameInfo,
1167 /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, NamedConcept,
1168 TemplateArgs: &ConstraintArgs);
1169 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1170 return ImmediatelyDeclaredConstraint;
1171
1172 // C++2a [temp.param]p4:
1173 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1174 //
1175 // We have the following case:
1176 //
1177 // template<typename T> concept C1 = true;
1178 // template<C1... T> struct s1;
1179 //
1180 // The constraint: (C1<T> && ...)
1181 //
1182 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1183 // any unqualified lookups for 'operator&&' here.
1184 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/Callee: nullptr,
1185 /*LParenLoc=*/SourceLocation(),
1186 LHS: ImmediatelyDeclaredConstraint.get(), Operator: BO_LAnd,
1187 EllipsisLoc, /*RHS=*/nullptr,
1188 /*RParenLoc=*/SourceLocation(),
1189 /*NumExpansions=*/std::nullopt);
1190}
1191
1192bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1193 DeclarationNameInfo NameInfo,
1194 ConceptDecl *NamedConcept, NamedDecl *FoundDecl,
1195 const TemplateArgumentListInfo *TemplateArgs,
1196 TemplateTypeParmDecl *ConstrainedParameter,
1197 SourceLocation EllipsisLoc) {
1198 // C++2a [temp.param]p4:
1199 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1200 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1201 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1202 TemplateArgs ? ASTTemplateArgumentListInfo::Create(C: Context,
1203 List: *TemplateArgs) : nullptr;
1204
1205 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1206
1207 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1208 *this, NS, NameInfo, NamedConcept, FoundDecl,
1209 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1210 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1211 ParamAsArgument, ConstrainedParameter->getLocation(),
1212 [&](TemplateArgumentListInfo &ConstraintArgs) {
1213 if (TemplateArgs)
1214 for (const auto &ArgLoc : TemplateArgs->arguments())
1215 ConstraintArgs.addArgument(Loc: ArgLoc);
1216 },
1217 EllipsisLoc);
1218 if (ImmediatelyDeclaredConstraint.isInvalid())
1219 return true;
1220
1221 auto *CL = ConceptReference::Create(C: Context, /*NNS=*/NS,
1222 /*TemplateKWLoc=*/SourceLocation{},
1223 /*ConceptNameInfo=*/NameInfo,
1224 /*FoundDecl=*/FoundDecl,
1225 /*NamedConcept=*/NamedConcept,
1226 /*ArgsWritten=*/ArgsAsWritten);
1227 ConstrainedParameter->setTypeConstraint(
1228 CR: CL, ImmediatelyDeclaredConstraint: ImmediatelyDeclaredConstraint.get(), ArgPackSubstIndex: std::nullopt);
1229 return false;
1230}
1231
1232bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1233 NonTypeTemplateParmDecl *NewConstrainedParm,
1234 NonTypeTemplateParmDecl *OrigConstrainedParm,
1235 SourceLocation EllipsisLoc) {
1236 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1237 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1238 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1239 diag::err_unsupported_placeholder_constraint)
1240 << NewConstrainedParm->getTypeSourceInfo()
1241 ->getTypeLoc()
1242 .getSourceRange();
1243 return true;
1244 }
1245 // FIXME: Concepts: This should be the type of the placeholder, but this is
1246 // unclear in the wording right now.
1247 DeclRefExpr *Ref =
1248 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1249 VK_PRValue, OrigConstrainedParm->getLocation());
1250 if (!Ref)
1251 return true;
1252 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1253 *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
1254 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1255 TL.getRAngleLoc(), BuildDecltypeType(Ref),
1256 OrigConstrainedParm->getLocation(),
1257 [&](TemplateArgumentListInfo &ConstraintArgs) {
1258 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1259 ConstraintArgs.addArgument(Loc: TL.getArgLoc(i: I));
1260 },
1261 EllipsisLoc);
1262 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1263 !ImmediatelyDeclaredConstraint.isUsable())
1264 return true;
1265
1266 NewConstrainedParm->setPlaceholderTypeConstraint(
1267 ImmediatelyDeclaredConstraint.get());
1268 return false;
1269}
1270
1271QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1272 SourceLocation Loc) {
1273 if (TSI->getType()->isUndeducedType()) {
1274 // C++17 [temp.dep.expr]p3:
1275 // An id-expression is type-dependent if it contains
1276 // - an identifier associated by name lookup with a non-type
1277 // template-parameter declared with a type that contains a
1278 // placeholder type (7.1.7.4),
1279 TSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSI);
1280 }
1281
1282 return CheckNonTypeTemplateParameterType(T: TSI->getType(), Loc);
1283}
1284
1285bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1286 if (T->isDependentType())
1287 return false;
1288
1289 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1290 return true;
1291
1292 if (T->isStructuralType())
1293 return false;
1294
1295 // Structural types are required to be object types or lvalue references.
1296 if (T->isRValueReferenceType()) {
1297 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1298 return true;
1299 }
1300
1301 // Don't mention structural types in our diagnostic prior to C++20. Also,
1302 // there's not much more we can say about non-scalar non-class types --
1303 // because we can't see functions or arrays here, those can only be language
1304 // extensions.
1305 if (!getLangOpts().CPlusPlus20 ||
1306 (!T->isScalarType() && !T->isRecordType())) {
1307 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1308 return true;
1309 }
1310
1311 // Structural types are required to be literal types.
1312 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1313 return true;
1314
1315 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1316
1317 // Drill down into the reason why the class is non-structural.
1318 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1319 // All members are required to be public and non-mutable, and can't be of
1320 // rvalue reference type. Check these conditions first to prefer a "local"
1321 // reason over a more distant one.
1322 for (const FieldDecl *FD : RD->fields()) {
1323 if (FD->getAccess() != AS_public) {
1324 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1325 return true;
1326 }
1327 if (FD->isMutable()) {
1328 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1329 return true;
1330 }
1331 if (FD->getType()->isRValueReferenceType()) {
1332 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1333 << T;
1334 return true;
1335 }
1336 }
1337
1338 // All bases are required to be public.
1339 for (const auto &BaseSpec : RD->bases()) {
1340 if (BaseSpec.getAccessSpecifier() != AS_public) {
1341 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1342 << T << 1;
1343 return true;
1344 }
1345 }
1346
1347 // All subobjects are required to be of structural types.
1348 SourceLocation SubLoc;
1349 QualType SubType;
1350 int Kind = -1;
1351
1352 for (const FieldDecl *FD : RD->fields()) {
1353 QualType T = Context.getBaseElementType(FD->getType());
1354 if (!T->isStructuralType()) {
1355 SubLoc = FD->getLocation();
1356 SubType = T;
1357 Kind = 0;
1358 break;
1359 }
1360 }
1361
1362 if (Kind == -1) {
1363 for (const auto &BaseSpec : RD->bases()) {
1364 QualType T = BaseSpec.getType();
1365 if (!T->isStructuralType()) {
1366 SubLoc = BaseSpec.getBaseTypeLoc();
1367 SubType = T;
1368 Kind = 1;
1369 break;
1370 }
1371 }
1372 }
1373
1374 assert(Kind != -1 && "couldn't find reason why type is not structural");
1375 Diag(SubLoc, diag::note_not_structural_subobject)
1376 << T << Kind << SubType;
1377 T = SubType;
1378 RD = T->getAsCXXRecordDecl();
1379 }
1380
1381 return true;
1382}
1383
1384QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1385 SourceLocation Loc) {
1386 // We don't allow variably-modified types as the type of non-type template
1387 // parameters.
1388 if (T->isVariablyModifiedType()) {
1389 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1390 << T;
1391 return QualType();
1392 }
1393
1394 // C++ [temp.param]p4:
1395 //
1396 // A non-type template-parameter shall have one of the following
1397 // (optionally cv-qualified) types:
1398 //
1399 // -- integral or enumeration type,
1400 if (T->isIntegralOrEnumerationType() ||
1401 // -- pointer to object or pointer to function,
1402 T->isPointerType() ||
1403 // -- lvalue reference to object or lvalue reference to function,
1404 T->isLValueReferenceType() ||
1405 // -- pointer to member,
1406 T->isMemberPointerType() ||
1407 // -- std::nullptr_t, or
1408 T->isNullPtrType() ||
1409 // -- a type that contains a placeholder type.
1410 T->isUndeducedType()) {
1411 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1412 // are ignored when determining its type.
1413 return T.getUnqualifiedType();
1414 }
1415
1416 // C++ [temp.param]p8:
1417 //
1418 // A non-type template-parameter of type "array of T" or
1419 // "function returning T" is adjusted to be of type "pointer to
1420 // T" or "pointer to function returning T", respectively.
1421 if (T->isArrayType() || T->isFunctionType())
1422 return Context.getDecayedType(T);
1423
1424 // If T is a dependent type, we can't do the check now, so we
1425 // assume that it is well-formed. Note that stripping off the
1426 // qualifiers here is not really correct if T turns out to be
1427 // an array type, but we'll recompute the type everywhere it's
1428 // used during instantiation, so that should be OK. (Using the
1429 // qualified type is equally wrong.)
1430 if (T->isDependentType())
1431 return T.getUnqualifiedType();
1432
1433 // C++20 [temp.param]p6:
1434 // -- a structural type
1435 if (RequireStructuralType(T, Loc))
1436 return QualType();
1437
1438 if (!getLangOpts().CPlusPlus20) {
1439 // FIXME: Consider allowing structural types as an extension in C++17. (In
1440 // earlier language modes, the template argument evaluation rules are too
1441 // inflexible.)
1442 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1443 return QualType();
1444 }
1445
1446 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1447 return T.getUnqualifiedType();
1448}
1449
1450NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1451 unsigned Depth,
1452 unsigned Position,
1453 SourceLocation EqualLoc,
1454 Expr *Default) {
1455 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1456
1457 // Check that we have valid decl-specifiers specified.
1458 auto CheckValidDeclSpecifiers = [this, &D] {
1459 // C++ [temp.param]
1460 // p1
1461 // template-parameter:
1462 // ...
1463 // parameter-declaration
1464 // p2
1465 // ... A storage class shall not be specified in a template-parameter
1466 // declaration.
1467 // [dcl.typedef]p1:
1468 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1469 // of a parameter-declaration
1470 const DeclSpec &DS = D.getDeclSpec();
1471 auto EmitDiag = [this](SourceLocation Loc) {
1472 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1473 << FixItHint::CreateRemoval(Loc);
1474 };
1475 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1476 EmitDiag(DS.getStorageClassSpecLoc());
1477
1478 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1479 EmitDiag(DS.getThreadStorageClassSpecLoc());
1480
1481 // [dcl.inline]p1:
1482 // The inline specifier can be applied only to the declaration or
1483 // definition of a variable or function.
1484
1485 if (DS.isInlineSpecified())
1486 EmitDiag(DS.getInlineSpecLoc());
1487
1488 // [dcl.constexpr]p1:
1489 // The constexpr specifier shall be applied only to the definition of a
1490 // variable or variable template or the declaration of a function or
1491 // function template.
1492
1493 if (DS.hasConstexprSpecifier())
1494 EmitDiag(DS.getConstexprSpecLoc());
1495
1496 // [dcl.fct.spec]p1:
1497 // Function-specifiers can be used only in function declarations.
1498
1499 if (DS.isVirtualSpecified())
1500 EmitDiag(DS.getVirtualSpecLoc());
1501
1502 if (DS.hasExplicitSpecifier())
1503 EmitDiag(DS.getExplicitSpecLoc());
1504
1505 if (DS.isNoreturnSpecified())
1506 EmitDiag(DS.getNoreturnSpecLoc());
1507 };
1508
1509 CheckValidDeclSpecifiers();
1510
1511 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1512 if (isa<AutoType>(T))
1513 Diag(D.getIdentifierLoc(),
1514 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1515 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1516
1517 assert(S->isTemplateParamScope() &&
1518 "Non-type template parameter not in template parameter scope!");
1519 bool Invalid = false;
1520
1521 QualType T = CheckNonTypeTemplateParameterType(TSI&: TInfo, Loc: D.getIdentifierLoc());
1522 if (T.isNull()) {
1523 T = Context.IntTy; // Recover with an 'int' type.
1524 Invalid = true;
1525 }
1526
1527 CheckFunctionOrTemplateParamDeclarator(S, D);
1528
1529 const IdentifierInfo *ParamName = D.getIdentifier();
1530 bool IsParameterPack = D.hasEllipsis();
1531 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1532 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1533 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1534 TInfo);
1535 Param->setAccess(AS_public);
1536
1537 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1538 if (TL.isConstrained()) {
1539 if (D.getEllipsisLoc().isInvalid() &&
1540 T->containsUnexpandedParameterPack()) {
1541 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1542 for (auto &Loc :
1543 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1544 Invalid |= DiagnoseUnexpandedParameterPack(
1545 Loc, UnexpandedParameterPackContext::UPPC_TypeConstraint);
1546 }
1547 if (!Invalid &&
1548 AttachTypeConstraint(TL, NewConstrainedParm: Param, OrigConstrainedParm: Param, EllipsisLoc: D.getEllipsisLoc()))
1549 Invalid = true;
1550 }
1551
1552 if (Invalid)
1553 Param->setInvalidDecl();
1554
1555 if (Param->isParameterPack())
1556 if (auto *CSI = getEnclosingLambdaOrBlock())
1557 CSI->LocalPacks.push_back(Param);
1558
1559 if (ParamName) {
1560 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: D.getIdentifierLoc(),
1561 Name: ParamName);
1562
1563 // Add the template parameter into the current scope.
1564 S->AddDecl(Param);
1565 IdResolver.AddDecl(Param);
1566 }
1567
1568 // C++0x [temp.param]p9:
1569 // A default template-argument may be specified for any kind of
1570 // template-parameter that is not a template parameter pack.
1571 if (Default && IsParameterPack) {
1572 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1573 Default = nullptr;
1574 }
1575
1576 // Check the well-formedness of the default template argument, if provided.
1577 if (Default) {
1578 // Check for unexpanded parameter packs.
1579 if (DiagnoseUnexpandedParameterPack(E: Default, UPPC: UPPC_DefaultArgument))
1580 return Param;
1581
1582 Param->setDefaultArgument(
1583 C: Context, DefArg: getTrivialTemplateArgumentLoc(
1584 Arg: TemplateArgument(Default, /*IsCanonical=*/false),
1585 NTTPType: QualType(), Loc: SourceLocation()));
1586 }
1587
1588 return Param;
1589}
1590
1591NamedDecl *Sema::ActOnTemplateTemplateParameter(
1592 Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
1593 bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *Name,
1594 SourceLocation NameLoc, unsigned Depth, unsigned Position,
1595 SourceLocation EqualLoc, ParsedTemplateArgument Default) {
1596 assert(S->isTemplateParamScope() &&
1597 "Template template parameter not in template parameter scope!");
1598
1599 bool IsParameterPack = EllipsisLoc.isValid();
1600
1601 bool Invalid = false;
1602 if (CheckTemplateParameterList(
1603 NewParams: Params,
1604 /*OldParams=*/nullptr,
1605 TPC: IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1606 Invalid = true;
1607
1608 // Construct the parameter object.
1609 TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(
1610 Context, Context.getTranslationUnitDecl(),
1611 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1612 Name, Typename, Params);
1613 Param->setAccess(AS_public);
1614
1615 if (Param->isParameterPack())
1616 if (auto *LSI = getEnclosingLambdaOrBlock())
1617 LSI->LocalPacks.push_back(Param);
1618
1619 // If the template template parameter has a name, then link the identifier
1620 // into the scope and lookup mechanisms.
1621 if (Name) {
1622 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: NameLoc, Name);
1623
1624 S->AddDecl(Param);
1625 IdResolver.AddDecl(Param);
1626 }
1627
1628 if (Params->size() == 0) {
1629 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1630 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1631 Invalid = true;
1632 }
1633
1634 if (Invalid)
1635 Param->setInvalidDecl();
1636
1637 // C++0x [temp.param]p9:
1638 // A default template-argument may be specified for any kind of
1639 // template-parameter that is not a template parameter pack.
1640 if (IsParameterPack && !Default.isInvalid()) {
1641 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1642 Default = ParsedTemplateArgument();
1643 }
1644
1645 if (!Default.isInvalid()) {
1646 // Check only that we have a template template argument. We don't want to
1647 // try to check well-formedness now, because our template template parameter
1648 // might have dependent types in its template parameters, which we wouldn't
1649 // be able to match now.
1650 //
1651 // If none of the template template parameter's template arguments mention
1652 // other template parameters, we could actually perform more checking here.
1653 // However, it isn't worth doing.
1654 TemplateArgumentLoc DefaultArg = translateTemplateArgument(SemaRef&: *this, Arg: Default);
1655 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1656 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1657 << DefaultArg.getSourceRange();
1658 return Param;
1659 }
1660
1661 // Check for unexpanded parameter packs.
1662 if (DiagnoseUnexpandedParameterPack(Loc: DefaultArg.getLocation(),
1663 Template: DefaultArg.getArgument().getAsTemplate(),
1664 UPPC: UPPC_DefaultArgument))
1665 return Param;
1666
1667 Param->setDefaultArgument(C: Context, DefArg: DefaultArg);
1668 }
1669
1670 return Param;
1671}
1672
1673namespace {
1674class ConstraintRefersToContainingTemplateChecker
1675 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1676 bool Result = false;
1677 const FunctionDecl *Friend = nullptr;
1678 unsigned TemplateDepth = 0;
1679
1680 // Check a record-decl that we've seen to see if it is a lexical parent of the
1681 // Friend, likely because it was referred to without its template arguments.
1682 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1683 CheckingRD = CheckingRD->getMostRecentDecl();
1684 if (!CheckingRD->isTemplated())
1685 return;
1686
1687 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1688 DC && !DC->isFileContext(); DC = DC->getParent())
1689 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1690 if (CheckingRD == RD->getMostRecentDecl())
1691 Result = true;
1692 }
1693
1694 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1695 if (D->getDepth() < TemplateDepth)
1696 Result = true;
1697
1698 // Necessary because the type of the NTTP might be what refers to the parent
1699 // constriant.
1700 TransformType(D->getType());
1701 }
1702
1703public:
1704 using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>;
1705
1706 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1707 const FunctionDecl *Friend,
1708 unsigned TemplateDepth)
1709 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1710 bool getResult() const { return Result; }
1711
1712 // This should be the only template parm type that we have to deal with.
1713 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1714 // FunctionParmPackExpr are all partially substituted, which cannot happen
1715 // with concepts at this point in translation.
1716 using inherited::TransformTemplateTypeParmType;
1717 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1718 TemplateTypeParmTypeLoc TL, bool) {
1719 if (TL.getDecl()->getDepth() < TemplateDepth)
1720 Result = true;
1721 return inherited::TransformTemplateTypeParmType(
1722 TLB, TL,
1723 /*SuppressObjCLifetime=*/false);
1724 }
1725
1726 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1727 if (!D)
1728 return D;
1729 // FIXME : This is possibly an incomplete list, but it is unclear what other
1730 // Decl kinds could be used to refer to the template parameters. This is a
1731 // best guess so far based on examples currently available, but the
1732 // unreachable should catch future instances/cases.
1733 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
1734 TransformType(TD->getUnderlyingType());
1735 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Val: D))
1736 CheckNonTypeTemplateParmDecl(D: NTTPD);
1737 else if (auto *VD = dyn_cast<ValueDecl>(Val: D))
1738 TransformType(VD->getType());
1739 else if (auto *TD = dyn_cast<TemplateDecl>(Val: D))
1740 TransformTemplateParameterList(TD->getTemplateParameters());
1741 else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1742 CheckIfContainingRecord(CheckingRD: RD);
1743 else if (isa<NamedDecl>(Val: D)) {
1744 // No direct types to visit here I believe.
1745 } else
1746 llvm_unreachable("Don't know how to handle this declaration type yet");
1747 return D;
1748 }
1749};
1750} // namespace
1751
1752bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1753 const FunctionDecl *Friend, unsigned TemplateDepth,
1754 const Expr *Constraint) {
1755 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1756 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1757 TemplateDepth);
1758 Checker.TransformExpr(const_cast<Expr *>(Constraint));
1759 return Checker.getResult();
1760}
1761
1762TemplateParameterList *
1763Sema::ActOnTemplateParameterList(unsigned Depth,
1764 SourceLocation ExportLoc,
1765 SourceLocation TemplateLoc,
1766 SourceLocation LAngleLoc,
1767 ArrayRef<NamedDecl *> Params,
1768 SourceLocation RAngleLoc,
1769 Expr *RequiresClause) {
1770 if (ExportLoc.isValid())
1771 Diag(ExportLoc, diag::warn_template_export_unsupported);
1772
1773 for (NamedDecl *P : Params)
1774 warnOnReservedIdentifier(D: P);
1775
1776 return TemplateParameterList::Create(
1777 C: Context, TemplateLoc, LAngleLoc,
1778 Params: llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1779}
1780
1781static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1782 const CXXScopeSpec &SS) {
1783 if (SS.isSet())
1784 T->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
1785}
1786
1787// Returns the template parameter list with all default template argument
1788// information.
1789TemplateParameterList *Sema::GetTemplateParameterList(TemplateDecl *TD) {
1790 // Make sure we get the template parameter list from the most
1791 // recent declaration, since that is the only one that is guaranteed to
1792 // have all the default template argument information.
1793 Decl *D = TD->getMostRecentDecl();
1794 // C++11 N3337 [temp.param]p12:
1795 // A default template argument shall not be specified in a friend class
1796 // template declaration.
1797 //
1798 // Skip past friend *declarations* because they are not supposed to contain
1799 // default template arguments. Moreover, these declarations may introduce
1800 // template parameters living in different template depths than the
1801 // corresponding template parameters in TD, causing unmatched constraint
1802 // substitution.
1803 //
1804 // FIXME: Diagnose such cases within a class template:
1805 // template <class T>
1806 // struct S {
1807 // template <class = void> friend struct C;
1808 // };
1809 // template struct S<int>;
1810 while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1811 D->getPreviousDecl())
1812 D = D->getPreviousDecl();
1813 return cast<TemplateDecl>(Val: D)->getTemplateParameters();
1814}
1815
1816DeclResult Sema::CheckClassTemplate(
1817 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1818 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1819 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1820 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1821 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1822 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1823 assert(TemplateParams && TemplateParams->size() > 0 &&
1824 "No template parameters");
1825 assert(TUK != TagUseKind::Reference &&
1826 "Can only declare or define class templates");
1827 bool Invalid = false;
1828
1829 // Check that we can declare a template here.
1830 if (CheckTemplateDeclScope(S, TemplateParams))
1831 return true;
1832
1833 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
1834 assert(Kind != TagTypeKind::Enum &&
1835 "can't build template of enumerated type");
1836
1837 // There is no such thing as an unnamed class template.
1838 if (!Name) {
1839 Diag(KWLoc, diag::err_template_unnamed_class);
1840 return true;
1841 }
1842
1843 // Find any previous declaration with this name. For a friend with no
1844 // scope explicitly specified, we only look for tag declarations (per
1845 // C++11 [basic.lookup.elab]p2).
1846 DeclContext *SemanticContext;
1847 LookupResult Previous(*this, Name, NameLoc,
1848 (SS.isEmpty() && TUK == TagUseKind::Friend)
1849 ? LookupTagName
1850 : LookupOrdinaryName,
1851 forRedeclarationInCurContext());
1852 if (SS.isNotEmpty() && !SS.isInvalid()) {
1853 SemanticContext = computeDeclContext(SS, EnteringContext: true);
1854 if (!SemanticContext) {
1855 // FIXME: Horrible, horrible hack! We can't currently represent this
1856 // in the AST, and historically we have just ignored such friend
1857 // class templates, so don't complain here.
1858 Diag(NameLoc, TUK == TagUseKind::Friend
1859 ? diag::warn_template_qualified_friend_ignored
1860 : diag::err_template_qualified_declarator_no_match)
1861 << SS.getScopeRep() << SS.getRange();
1862 return TUK != TagUseKind::Friend;
1863 }
1864
1865 if (RequireCompleteDeclContext(SS, DC: SemanticContext))
1866 return true;
1867
1868 // If we're adding a template to a dependent context, we may need to
1869 // rebuilding some of the types used within the template parameter list,
1870 // now that we know what the current instantiation is.
1871 if (SemanticContext->isDependentContext()) {
1872 ContextRAII SavedContext(*this, SemanticContext);
1873 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
1874 Invalid = true;
1875 }
1876
1877 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1878 diagnoseQualifiedDeclaration(SS, DC: SemanticContext, Name, Loc: NameLoc,
1879 /*TemplateId-*/ TemplateId: nullptr,
1880 /*IsMemberSpecialization*/ false);
1881
1882 LookupQualifiedName(R&: Previous, LookupCtx: SemanticContext);
1883 } else {
1884 SemanticContext = CurContext;
1885
1886 // C++14 [class.mem]p14:
1887 // If T is the name of a class, then each of the following shall have a
1888 // name different from T:
1889 // -- every member template of class T
1890 if (TUK != TagUseKind::Friend &&
1891 DiagnoseClassNameShadow(DC: SemanticContext,
1892 Info: DeclarationNameInfo(Name, NameLoc)))
1893 return true;
1894
1895 LookupName(R&: Previous, S);
1896 }
1897
1898 if (Previous.isAmbiguous())
1899 return true;
1900
1901 // Let the template parameter scope enter the lookup chain of the current
1902 // class template. For example, given
1903 //
1904 // namespace ns {
1905 // template <class> bool Param = false;
1906 // template <class T> struct N;
1907 // }
1908 //
1909 // template <class Param> struct ns::N { void foo(Param); };
1910 //
1911 // When we reference Param inside the function parameter list, our name lookup
1912 // chain for it should be like:
1913 // FunctionScope foo
1914 // -> RecordScope N
1915 // -> TemplateParamScope (where we will find Param)
1916 // -> NamespaceScope ns
1917 //
1918 // See also CppLookupName().
1919 if (S->isTemplateParamScope())
1920 EnterTemplatedContext(S, DC: SemanticContext);
1921
1922 NamedDecl *PrevDecl = nullptr;
1923 if (Previous.begin() != Previous.end())
1924 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1925
1926 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1927 // Maybe we will complain about the shadowed template parameter.
1928 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1929 // Just pretend that we didn't see the previous declaration.
1930 PrevDecl = nullptr;
1931 }
1932
1933 // If there is a previous declaration with the same name, check
1934 // whether this is a valid redeclaration.
1935 ClassTemplateDecl *PrevClassTemplate =
1936 dyn_cast_or_null<ClassTemplateDecl>(Val: PrevDecl);
1937
1938 // We may have found the injected-class-name of a class template,
1939 // class template partial specialization, or class template specialization.
1940 // In these cases, grab the template that is being defined or specialized.
1941 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(Val: PrevDecl) &&
1942 cast<CXXRecordDecl>(Val: PrevDecl)->isInjectedClassName()) {
1943 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1944 PrevClassTemplate
1945 = cast<CXXRecordDecl>(Val: PrevDecl)->getDescribedClassTemplate();
1946 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(Val: PrevDecl)) {
1947 PrevClassTemplate
1948 = cast<ClassTemplateSpecializationDecl>(Val: PrevDecl)
1949 ->getSpecializedTemplate();
1950 }
1951 }
1952
1953 if (TUK == TagUseKind::Friend) {
1954 // C++ [namespace.memdef]p3:
1955 // [...] When looking for a prior declaration of a class or a function
1956 // declared as a friend, and when the name of the friend class or
1957 // function is neither a qualified name nor a template-id, scopes outside
1958 // the innermost enclosing namespace scope are not considered.
1959 if (!SS.isSet()) {
1960 DeclContext *OutermostContext = CurContext;
1961 while (!OutermostContext->isFileContext())
1962 OutermostContext = OutermostContext->getLookupParent();
1963
1964 if (PrevDecl &&
1965 (OutermostContext->Equals(DC: PrevDecl->getDeclContext()) ||
1966 OutermostContext->Encloses(DC: PrevDecl->getDeclContext()))) {
1967 SemanticContext = PrevDecl->getDeclContext();
1968 } else {
1969 // Declarations in outer scopes don't matter. However, the outermost
1970 // context we computed is the semantic context for our new
1971 // declaration.
1972 PrevDecl = PrevClassTemplate = nullptr;
1973 SemanticContext = OutermostContext;
1974
1975 // Check that the chosen semantic context doesn't already contain a
1976 // declaration of this name as a non-tag type.
1977 Previous.clear(Kind: LookupOrdinaryName);
1978 DeclContext *LookupContext = SemanticContext;
1979 while (LookupContext->isTransparentContext())
1980 LookupContext = LookupContext->getLookupParent();
1981 LookupQualifiedName(R&: Previous, LookupCtx: LookupContext);
1982
1983 if (Previous.isAmbiguous())
1984 return true;
1985
1986 if (Previous.begin() != Previous.end())
1987 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1988 }
1989 }
1990 } else if (PrevDecl && !isDeclInScope(D: Previous.getRepresentativeDecl(),
1991 Ctx: SemanticContext, S, AllowInlineNamespace: SS.isValid()))
1992 PrevDecl = PrevClassTemplate = nullptr;
1993
1994 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1995 Val: PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1996 if (SS.isEmpty() &&
1997 !(PrevClassTemplate &&
1998 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1999 SemanticContext->getRedeclContext()))) {
2000 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2001 Diag(Shadow->getTargetDecl()->getLocation(),
2002 diag::note_using_decl_target);
2003 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2004 // Recover by ignoring the old declaration.
2005 PrevDecl = PrevClassTemplate = nullptr;
2006 }
2007 }
2008
2009 if (PrevClassTemplate) {
2010 // Ensure that the template parameter lists are compatible. Skip this check
2011 // for a friend in a dependent context: the template parameter list itself
2012 // could be dependent.
2013 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2014 !TemplateParameterListsAreEqual(
2015 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2016 : CurContext,
2017 CurContext, KWLoc),
2018 TemplateParams, PrevClassTemplate,
2019 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2020 TPL_TemplateMatch))
2021 return true;
2022
2023 // C++ [temp.class]p4:
2024 // In a redeclaration, partial specialization, explicit
2025 // specialization or explicit instantiation of a class template,
2026 // the class-key shall agree in kind with the original class
2027 // template declaration (7.1.5.3).
2028 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2029 if (!isAcceptableTagRedeclaration(
2030 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2031 Diag(KWLoc, diag::err_use_with_wrong_tag)
2032 << Name
2033 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2034 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2035 Kind = PrevRecordDecl->getTagKind();
2036 }
2037
2038 // Check for redefinition of this class template.
2039 if (TUK == TagUseKind::Definition) {
2040 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2041 // If we have a prior definition that is not visible, treat this as
2042 // simply making that previous definition visible.
2043 NamedDecl *Hidden = nullptr;
2044 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2045 SkipBody->ShouldSkip = true;
2046 SkipBody->Previous = Def;
2047 auto *Tmpl = cast<CXXRecordDecl>(Val: Hidden)->getDescribedClassTemplate();
2048 assert(Tmpl && "original definition of a class template is not a "
2049 "class template?");
2050 makeMergedDefinitionVisible(ND: Hidden);
2051 makeMergedDefinitionVisible(Tmpl);
2052 } else {
2053 Diag(NameLoc, diag::err_redefinition) << Name;
2054 Diag(Def->getLocation(), diag::note_previous_definition);
2055 // FIXME: Would it make sense to try to "forget" the previous
2056 // definition, as part of error recovery?
2057 return true;
2058 }
2059 }
2060 }
2061 } else if (PrevDecl) {
2062 // C++ [temp]p5:
2063 // A class template shall not have the same name as any other
2064 // template, class, function, object, enumeration, enumerator,
2065 // namespace, or type in the same scope (3.3), except as specified
2066 // in (14.5.4).
2067 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2068 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2069 return true;
2070 }
2071
2072 // Check the template parameter list of this declaration, possibly
2073 // merging in the template parameter list from the previous class
2074 // template declaration. Skip this check for a friend in a dependent
2075 // context, because the template parameter list might be dependent.
2076 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2077 CheckTemplateParameterList(
2078 NewParams: TemplateParams,
2079 OldParams: PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2080 : nullptr,
2081 TPC: (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2082 SemanticContext->isDependentContext())
2083 ? TPC_ClassTemplateMember
2084 : TUK == TagUseKind::Friend ? TPC_FriendClassTemplate
2085 : TPC_Other,
2086 SkipBody))
2087 Invalid = true;
2088
2089 if (SS.isSet()) {
2090 // If the name of the template was qualified, we must be defining the
2091 // template out-of-line.
2092 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2093 Diag(NameLoc, TUK == TagUseKind::Friend
2094 ? diag::err_friend_decl_does_not_match
2095 : diag::err_member_decl_does_not_match)
2096 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2097 Invalid = true;
2098 }
2099 }
2100
2101 // If this is a templated friend in a dependent context we should not put it
2102 // on the redecl chain. In some cases, the templated friend can be the most
2103 // recent declaration tricking the template instantiator to make substitutions
2104 // there.
2105 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2106 bool ShouldAddRedecl =
2107 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2108
2109 CXXRecordDecl *NewClass =
2110 CXXRecordDecl::Create(C: Context, TK: Kind, DC: SemanticContext, StartLoc: KWLoc, IdLoc: NameLoc, Id: Name,
2111 PrevDecl: PrevClassTemplate && ShouldAddRedecl ?
2112 PrevClassTemplate->getTemplatedDecl() : nullptr,
2113 /*DelayTypeCreation=*/true);
2114 SetNestedNameSpecifier(*this, NewClass, SS);
2115 if (NumOuterTemplateParamLists > 0)
2116 NewClass->setTemplateParameterListsInfo(
2117 Context,
2118 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2119
2120 // Add alignment attributes if necessary; these attributes are checked when
2121 // the ASTContext lays out the structure.
2122 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2123 if (LangOpts.HLSL)
2124 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2125 AddAlignmentAttributesForRecord(NewClass);
2126 AddMsStructLayoutForRecord(NewClass);
2127 }
2128
2129 ClassTemplateDecl *NewTemplate
2130 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2131 DeclarationName(Name), TemplateParams,
2132 NewClass);
2133
2134 if (ShouldAddRedecl)
2135 NewTemplate->setPreviousDecl(PrevClassTemplate);
2136
2137 NewClass->setDescribedClassTemplate(NewTemplate);
2138
2139 if (ModulePrivateLoc.isValid())
2140 NewTemplate->setModulePrivate();
2141
2142 // Build the type for the class template declaration now.
2143 QualType T = NewTemplate->getInjectedClassNameSpecialization();
2144 T = Context.getInjectedClassNameType(Decl: NewClass, TST: T);
2145 assert(T->isDependentType() && "Class template type is not dependent?");
2146 (void)T;
2147
2148 // If we are providing an explicit specialization of a member that is a
2149 // class template, make a note of that.
2150 if (PrevClassTemplate &&
2151 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2152 PrevClassTemplate->setMemberSpecialization();
2153
2154 // Set the access specifier.
2155 if (!Invalid && TUK != TagUseKind::Friend &&
2156 NewTemplate->getDeclContext()->isRecord())
2157 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2158
2159 // Set the lexical context of these templates
2160 NewClass->setLexicalDeclContext(CurContext);
2161 NewTemplate->setLexicalDeclContext(CurContext);
2162
2163 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2164 NewClass->startDefinition();
2165
2166 ProcessDeclAttributeList(S, NewClass, Attr);
2167
2168 if (PrevClassTemplate)
2169 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2170
2171 AddPushedVisibilityAttribute(NewClass);
2172 inferGslOwnerPointerAttribute(Record: NewClass);
2173 inferNullableClassAttribute(CRD: NewClass);
2174
2175 if (TUK != TagUseKind::Friend) {
2176 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2177 Scope *Outer = S;
2178 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2179 Outer = Outer->getParent();
2180 PushOnScopeChains(NewTemplate, Outer);
2181 } else {
2182 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2183 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2184 NewClass->setAccess(PrevClassTemplate->getAccess());
2185 }
2186
2187 NewTemplate->setObjectOfFriendDecl();
2188
2189 // Friend templates are visible in fairly strange ways.
2190 if (!CurContext->isDependentContext()) {
2191 DeclContext *DC = SemanticContext->getRedeclContext();
2192 DC->makeDeclVisibleInContext(NewTemplate);
2193 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2194 PushOnScopeChains(NewTemplate, EnclosingScope,
2195 /* AddToContext = */ false);
2196 }
2197
2198 FriendDecl *Friend = FriendDecl::Create(
2199 C&: Context, DC: CurContext, L: NewClass->getLocation(), Friend_: NewTemplate, FriendL: FriendLoc);
2200 Friend->setAccess(AS_public);
2201 CurContext->addDecl(Friend);
2202 }
2203
2204 if (PrevClassTemplate)
2205 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2206
2207 if (Invalid) {
2208 NewTemplate->setInvalidDecl();
2209 NewClass->setInvalidDecl();
2210 }
2211
2212 ActOnDocumentableDecl(NewTemplate);
2213
2214 if (SkipBody && SkipBody->ShouldSkip)
2215 return SkipBody->Previous;
2216
2217 return NewTemplate;
2218}
2219
2220/// Diagnose the presence of a default template argument on a
2221/// template parameter, which is ill-formed in certain contexts.
2222///
2223/// \returns true if the default template argument should be dropped.
2224static bool DiagnoseDefaultTemplateArgument(Sema &S,
2225 Sema::TemplateParamListContext TPC,
2226 SourceLocation ParamLoc,
2227 SourceRange DefArgRange) {
2228 switch (TPC) {
2229 case Sema::TPC_Other:
2230 case Sema::TPC_TemplateTemplateParameterPack:
2231 return false;
2232
2233 case Sema::TPC_FunctionTemplate:
2234 case Sema::TPC_FriendFunctionTemplateDefinition:
2235 // C++ [temp.param]p9:
2236 // A default template-argument shall not be specified in a
2237 // function template declaration or a function template
2238 // definition [...]
2239 // If a friend function template declaration specifies a default
2240 // template-argument, that declaration shall be a definition and shall be
2241 // the only declaration of the function template in the translation unit.
2242 // (C++98/03 doesn't have this wording; see DR226).
2243 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2244 << DefArgRange;
2245 return false;
2246
2247 case Sema::TPC_ClassTemplateMember:
2248 // C++0x [temp.param]p9:
2249 // A default template-argument shall not be specified in the
2250 // template-parameter-lists of the definition of a member of a
2251 // class template that appears outside of the member's class.
2252 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2253 << DefArgRange;
2254 return true;
2255
2256 case Sema::TPC_FriendClassTemplate:
2257 case Sema::TPC_FriendFunctionTemplate:
2258 // C++ [temp.param]p9:
2259 // A default template-argument shall not be specified in a
2260 // friend template declaration.
2261 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2262 << DefArgRange;
2263 return true;
2264
2265 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2266 // for friend function templates if there is only a single
2267 // declaration (and it is a definition). Strange!
2268 }
2269
2270 llvm_unreachable("Invalid TemplateParamListContext!");
2271}
2272
2273/// Check for unexpanded parameter packs within the template parameters
2274/// of a template template parameter, recursively.
2275static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2276 TemplateTemplateParmDecl *TTP) {
2277 // A template template parameter which is a parameter pack is also a pack
2278 // expansion.
2279 if (TTP->isParameterPack())
2280 return false;
2281
2282 TemplateParameterList *Params = TTP->getTemplateParameters();
2283 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2284 NamedDecl *P = Params->getParam(Idx: I);
2285 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: P)) {
2286 if (!TTP->isParameterPack())
2287 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2288 if (TC->hasExplicitTemplateArgs())
2289 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2290 if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2291 Sema::UPPC_TypeConstraint))
2292 return true;
2293 continue;
2294 }
2295
2296 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) {
2297 if (!NTTP->isParameterPack() &&
2298 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2299 NTTP->getTypeSourceInfo(),
2300 Sema::UPPC_NonTypeTemplateParameterType))
2301 return true;
2302
2303 continue;
2304 }
2305
2306 if (TemplateTemplateParmDecl *InnerTTP
2307 = dyn_cast<TemplateTemplateParmDecl>(Val: P))
2308 if (DiagnoseUnexpandedParameterPacks(S, TTP: InnerTTP))
2309 return true;
2310 }
2311
2312 return false;
2313}
2314
2315bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2316 TemplateParameterList *OldParams,
2317 TemplateParamListContext TPC,
2318 SkipBodyInfo *SkipBody) {
2319 bool Invalid = false;
2320
2321 // C++ [temp.param]p10:
2322 // The set of default template-arguments available for use with a
2323 // template declaration or definition is obtained by merging the
2324 // default arguments from the definition (if in scope) and all
2325 // declarations in scope in the same way default function
2326 // arguments are (8.3.6).
2327 bool SawDefaultArgument = false;
2328 SourceLocation PreviousDefaultArgLoc;
2329
2330 // Dummy initialization to avoid warnings.
2331 TemplateParameterList::iterator OldParam = NewParams->end();
2332 if (OldParams)
2333 OldParam = OldParams->begin();
2334
2335 bool RemoveDefaultArguments = false;
2336 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2337 NewParamEnd = NewParams->end();
2338 NewParam != NewParamEnd; ++NewParam) {
2339 // Whether we've seen a duplicate default argument in the same translation
2340 // unit.
2341 bool RedundantDefaultArg = false;
2342 // Whether we've found inconsis inconsitent default arguments in different
2343 // translation unit.
2344 bool InconsistentDefaultArg = false;
2345 // The name of the module which contains the inconsistent default argument.
2346 std::string PrevModuleName;
2347
2348 SourceLocation OldDefaultLoc;
2349 SourceLocation NewDefaultLoc;
2350
2351 // Variable used to diagnose missing default arguments
2352 bool MissingDefaultArg = false;
2353
2354 // Variable used to diagnose non-final parameter packs
2355 bool SawParameterPack = false;
2356
2357 if (TemplateTypeParmDecl *NewTypeParm
2358 = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam)) {
2359 // Check the presence of a default argument here.
2360 if (NewTypeParm->hasDefaultArgument() &&
2361 DiagnoseDefaultTemplateArgument(
2362 *this, TPC, NewTypeParm->getLocation(),
2363 NewTypeParm->getDefaultArgument().getSourceRange()))
2364 NewTypeParm->removeDefaultArgument();
2365
2366 // Merge default arguments for template type parameters.
2367 TemplateTypeParmDecl *OldTypeParm
2368 = OldParams? cast<TemplateTypeParmDecl>(Val: *OldParam) : nullptr;
2369 if (NewTypeParm->isParameterPack()) {
2370 assert(!NewTypeParm->hasDefaultArgument() &&
2371 "Parameter packs can't have a default argument!");
2372 SawParameterPack = true;
2373 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2374 NewTypeParm->hasDefaultArgument() &&
2375 (!SkipBody || !SkipBody->ShouldSkip)) {
2376 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2377 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2378 SawDefaultArgument = true;
2379
2380 if (!OldTypeParm->getOwningModule())
2381 RedundantDefaultArg = true;
2382 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2383 NewTypeParm)) {
2384 InconsistentDefaultArg = true;
2385 PrevModuleName =
2386 OldTypeParm->getImportedOwningModule()->getFullModuleName();
2387 }
2388 PreviousDefaultArgLoc = NewDefaultLoc;
2389 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2390 // Merge the default argument from the old declaration to the
2391 // new declaration.
2392 NewTypeParm->setInheritedDefaultArgument(C: Context, Prev: OldTypeParm);
2393 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2394 } else if (NewTypeParm->hasDefaultArgument()) {
2395 SawDefaultArgument = true;
2396 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2397 } else if (SawDefaultArgument)
2398 MissingDefaultArg = true;
2399 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2400 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam)) {
2401 // Check for unexpanded parameter packs, except in a template template
2402 // parameter pack, as in those any unexpanded packs should be expanded
2403 // along with the parameter itself.
2404 if (TPC != TPC_TemplateTemplateParameterPack &&
2405 !NewNonTypeParm->isParameterPack() &&
2406 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2407 NewNonTypeParm->getTypeSourceInfo(),
2408 UPPC_NonTypeTemplateParameterType)) {
2409 Invalid = true;
2410 continue;
2411 }
2412
2413 // Check the presence of a default argument here.
2414 if (NewNonTypeParm->hasDefaultArgument() &&
2415 DiagnoseDefaultTemplateArgument(
2416 *this, TPC, NewNonTypeParm->getLocation(),
2417 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2418 NewNonTypeParm->removeDefaultArgument();
2419 }
2420
2421 // Merge default arguments for non-type template parameters
2422 NonTypeTemplateParmDecl *OldNonTypeParm
2423 = OldParams? cast<NonTypeTemplateParmDecl>(Val: *OldParam) : nullptr;
2424 if (NewNonTypeParm->isParameterPack()) {
2425 assert(!NewNonTypeParm->hasDefaultArgument() &&
2426 "Parameter packs can't have a default argument!");
2427 if (!NewNonTypeParm->isPackExpansion())
2428 SawParameterPack = true;
2429 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2430 NewNonTypeParm->hasDefaultArgument() &&
2431 (!SkipBody || !SkipBody->ShouldSkip)) {
2432 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2433 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2434 SawDefaultArgument = true;
2435 if (!OldNonTypeParm->getOwningModule())
2436 RedundantDefaultArg = true;
2437 else if (!getASTContext().isSameDefaultTemplateArgument(
2438 OldNonTypeParm, NewNonTypeParm)) {
2439 InconsistentDefaultArg = true;
2440 PrevModuleName =
2441 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2442 }
2443 PreviousDefaultArgLoc = NewDefaultLoc;
2444 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2445 // Merge the default argument from the old declaration to the
2446 // new declaration.
2447 NewNonTypeParm->setInheritedDefaultArgument(C: Context, Parm: OldNonTypeParm);
2448 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2449 } else if (NewNonTypeParm->hasDefaultArgument()) {
2450 SawDefaultArgument = true;
2451 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2452 } else if (SawDefaultArgument)
2453 MissingDefaultArg = true;
2454 } else {
2455 TemplateTemplateParmDecl *NewTemplateParm
2456 = cast<TemplateTemplateParmDecl>(Val: *NewParam);
2457
2458 // Check for unexpanded parameter packs, recursively.
2459 if (::DiagnoseUnexpandedParameterPacks(S&: *this, TTP: NewTemplateParm)) {
2460 Invalid = true;
2461 continue;
2462 }
2463
2464 // Check the presence of a default argument here.
2465 if (NewTemplateParm->hasDefaultArgument() &&
2466 DiagnoseDefaultTemplateArgument(*this, TPC,
2467 NewTemplateParm->getLocation(),
2468 NewTemplateParm->getDefaultArgument().getSourceRange()))
2469 NewTemplateParm->removeDefaultArgument();
2470
2471 // Merge default arguments for template template parameters
2472 TemplateTemplateParmDecl *OldTemplateParm
2473 = OldParams? cast<TemplateTemplateParmDecl>(Val: *OldParam) : nullptr;
2474 if (NewTemplateParm->isParameterPack()) {
2475 assert(!NewTemplateParm->hasDefaultArgument() &&
2476 "Parameter packs can't have a default argument!");
2477 if (!NewTemplateParm->isPackExpansion())
2478 SawParameterPack = true;
2479 } else if (OldTemplateParm &&
2480 hasVisibleDefaultArgument(OldTemplateParm) &&
2481 NewTemplateParm->hasDefaultArgument() &&
2482 (!SkipBody || !SkipBody->ShouldSkip)) {
2483 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2484 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2485 SawDefaultArgument = true;
2486 if (!OldTemplateParm->getOwningModule())
2487 RedundantDefaultArg = true;
2488 else if (!getASTContext().isSameDefaultTemplateArgument(
2489 OldTemplateParm, NewTemplateParm)) {
2490 InconsistentDefaultArg = true;
2491 PrevModuleName =
2492 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2493 }
2494 PreviousDefaultArgLoc = NewDefaultLoc;
2495 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2496 // Merge the default argument from the old declaration to the
2497 // new declaration.
2498 NewTemplateParm->setInheritedDefaultArgument(C: Context, Prev: OldTemplateParm);
2499 PreviousDefaultArgLoc
2500 = OldTemplateParm->getDefaultArgument().getLocation();
2501 } else if (NewTemplateParm->hasDefaultArgument()) {
2502 SawDefaultArgument = true;
2503 PreviousDefaultArgLoc
2504 = NewTemplateParm->getDefaultArgument().getLocation();
2505 } else if (SawDefaultArgument)
2506 MissingDefaultArg = true;
2507 }
2508
2509 // C++11 [temp.param]p11:
2510 // If a template parameter of a primary class template or alias template
2511 // is a template parameter pack, it shall be the last template parameter.
2512 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2513 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2514 Diag((*NewParam)->getLocation(),
2515 diag::err_template_param_pack_must_be_last_template_parameter);
2516 Invalid = true;
2517 }
2518
2519 // [basic.def.odr]/13:
2520 // There can be more than one definition of a
2521 // ...
2522 // default template argument
2523 // ...
2524 // in a program provided that each definition appears in a different
2525 // translation unit and the definitions satisfy the [same-meaning
2526 // criteria of the ODR].
2527 //
2528 // Simply, the design of modules allows the definition of template default
2529 // argument to be repeated across translation unit. Note that the ODR is
2530 // checked elsewhere. But it is still not allowed to repeat template default
2531 // argument in the same translation unit.
2532 if (RedundantDefaultArg) {
2533 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2534 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2535 Invalid = true;
2536 } else if (InconsistentDefaultArg) {
2537 // We could only diagnose about the case that the OldParam is imported.
2538 // The case NewParam is imported should be handled in ASTReader.
2539 Diag(NewDefaultLoc,
2540 diag::err_template_param_default_arg_inconsistent_redefinition);
2541 Diag(OldDefaultLoc,
2542 diag::note_template_param_prev_default_arg_in_other_module)
2543 << PrevModuleName;
2544 Invalid = true;
2545 } else if (MissingDefaultArg &&
2546 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2547 TPC == TPC_FriendClassTemplate)) {
2548 // C++ 23[temp.param]p14:
2549 // If a template-parameter of a class template, variable template, or
2550 // alias template has a default template argument, each subsequent
2551 // template-parameter shall either have a default template argument
2552 // supplied or be a template parameter pack.
2553 Diag((*NewParam)->getLocation(),
2554 diag::err_template_param_default_arg_missing);
2555 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2556 Invalid = true;
2557 RemoveDefaultArguments = true;
2558 }
2559
2560 // If we have an old template parameter list that we're merging
2561 // in, move on to the next parameter.
2562 if (OldParams)
2563 ++OldParam;
2564 }
2565
2566 // We were missing some default arguments at the end of the list, so remove
2567 // all of the default arguments.
2568 if (RemoveDefaultArguments) {
2569 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2570 NewParamEnd = NewParams->end();
2571 NewParam != NewParamEnd; ++NewParam) {
2572 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam))
2573 TTP->removeDefaultArgument();
2574 else if (NonTypeTemplateParmDecl *NTTP
2575 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam))
2576 NTTP->removeDefaultArgument();
2577 else
2578 cast<TemplateTemplateParmDecl>(Val: *NewParam)->removeDefaultArgument();
2579 }
2580 }
2581
2582 return Invalid;
2583}
2584
2585namespace {
2586
2587/// A class which looks for a use of a certain level of template
2588/// parameter.
2589struct DependencyChecker : DynamicRecursiveASTVisitor {
2590 unsigned Depth;
2591
2592 // Whether we're looking for a use of a template parameter that makes the
2593 // overall construct type-dependent / a dependent type. This is strictly
2594 // best-effort for now; we may fail to match at all for a dependent type
2595 // in some cases if this is set.
2596 bool IgnoreNonTypeDependent;
2597
2598 bool Match;
2599 SourceLocation MatchLoc;
2600
2601 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2602 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2603 Match(false) {}
2604
2605 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2606 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2607 NamedDecl *ND = Params->getParam(Idx: 0);
2608 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(Val: ND)) {
2609 Depth = PD->getDepth();
2610 } else if (NonTypeTemplateParmDecl *PD =
2611 dyn_cast<NonTypeTemplateParmDecl>(Val: ND)) {
2612 Depth = PD->getDepth();
2613 } else {
2614 Depth = cast<TemplateTemplateParmDecl>(Val: ND)->getDepth();
2615 }
2616 }
2617
2618 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2619 if (ParmDepth >= Depth) {
2620 Match = true;
2621 MatchLoc = Loc;
2622 return true;
2623 }
2624 return false;
2625 }
2626
2627 bool TraverseStmt(Stmt *S) override {
2628 // Prune out non-type-dependent expressions if requested. This can
2629 // sometimes result in us failing to find a template parameter reference
2630 // (if a value-dependent expression creates a dependent type), but this
2631 // mode is best-effort only.
2632 if (auto *E = dyn_cast_or_null<Expr>(Val: S))
2633 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2634 return true;
2635 return DynamicRecursiveASTVisitor::TraverseStmt(S);
2636 }
2637
2638 bool TraverseTypeLoc(TypeLoc TL) override {
2639 if (IgnoreNonTypeDependent && !TL.isNull() &&
2640 !TL.getType()->isDependentType())
2641 return true;
2642 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL);
2643 }
2644
2645 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2646 return !Matches(ParmDepth: TL.getTypePtr()->getDepth(), Loc: TL.getNameLoc());
2647 }
2648
2649 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2650 // For a best-effort search, keep looking until we find a location.
2651 return IgnoreNonTypeDependent || !Matches(ParmDepth: T->getDepth());
2652 }
2653
2654 bool TraverseTemplateName(TemplateName N) override {
2655 if (TemplateTemplateParmDecl *PD =
2656 dyn_cast_or_null<TemplateTemplateParmDecl>(Val: N.getAsTemplateDecl()))
2657 if (Matches(ParmDepth: PD->getDepth()))
2658 return false;
2659 return DynamicRecursiveASTVisitor::TraverseTemplateName(N);
2660 }
2661
2662 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2663 if (NonTypeTemplateParmDecl *PD =
2664 dyn_cast<NonTypeTemplateParmDecl>(Val: E->getDecl()))
2665 if (Matches(ParmDepth: PD->getDepth(), Loc: E->getExprLoc()))
2666 return false;
2667 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2668 }
2669
2670 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2671 return TraverseType(T->getReplacementType());
2672 }
2673
2674 bool VisitSubstTemplateTypeParmPackType(
2675 SubstTemplateTypeParmPackType *T) override {
2676 return TraverseTemplateArgument(T->getArgumentPack());
2677 }
2678
2679 bool TraverseInjectedClassNameType(InjectedClassNameType *T) override {
2680 return TraverseType(T->getInjectedSpecializationType());
2681 }
2682};
2683} // end anonymous namespace
2684
2685/// Determines whether a given type depends on the given parameter
2686/// list.
2687static bool
2688DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2689 if (!Params->size())
2690 return false;
2691
2692 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2693 Checker.TraverseType(T);
2694 return Checker.Match;
2695}
2696
2697// Find the source range corresponding to the named type in the given
2698// nested-name-specifier, if any.
2699static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2700 QualType T,
2701 const CXXScopeSpec &SS) {
2702 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2703 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2704 if (const Type *CurType = NNS->getAsType()) {
2705 if (Context.hasSameUnqualifiedType(T1: T, T2: QualType(CurType, 0)))
2706 return NNSLoc.getTypeLoc().getSourceRange();
2707 } else
2708 break;
2709
2710 NNSLoc = NNSLoc.getPrefix();
2711 }
2712
2713 return SourceRange();
2714}
2715
2716TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2717 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2718 TemplateIdAnnotation *TemplateId,
2719 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2720 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2721 IsMemberSpecialization = false;
2722 Invalid = false;
2723
2724 // The sequence of nested types to which we will match up the template
2725 // parameter lists. We first build this list by starting with the type named
2726 // by the nested-name-specifier and walking out until we run out of types.
2727 SmallVector<QualType, 4> NestedTypes;
2728 QualType T;
2729 if (SS.getScopeRep()) {
2730 if (CXXRecordDecl *Record
2731 = dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: true)))
2732 T = Context.getTypeDeclType(Record);
2733 else
2734 T = QualType(SS.getScopeRep()->getAsType(), 0);
2735 }
2736
2737 // If we found an explicit specialization that prevents us from needing
2738 // 'template<>' headers, this will be set to the location of that
2739 // explicit specialization.
2740 SourceLocation ExplicitSpecLoc;
2741
2742 while (!T.isNull()) {
2743 NestedTypes.push_back(Elt: T);
2744
2745 // Retrieve the parent of a record type.
2746 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2747 // If this type is an explicit specialization, we're done.
2748 if (ClassTemplateSpecializationDecl *Spec
2749 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
2750 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Spec) &&
2751 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2752 ExplicitSpecLoc = Spec->getLocation();
2753 break;
2754 }
2755 } else if (Record->getTemplateSpecializationKind()
2756 == TSK_ExplicitSpecialization) {
2757 ExplicitSpecLoc = Record->getLocation();
2758 break;
2759 }
2760
2761 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2762 T = Context.getTypeDeclType(Decl: Parent);
2763 else
2764 T = QualType();
2765 continue;
2766 }
2767
2768 if (const TemplateSpecializationType *TST
2769 = T->getAs<TemplateSpecializationType>()) {
2770 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2771 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2772 T = Context.getTypeDeclType(Decl: Parent);
2773 else
2774 T = QualType();
2775 continue;
2776 }
2777 }
2778
2779 // Look one step prior in a dependent template specialization type.
2780 if (const DependentTemplateSpecializationType *DependentTST
2781 = T->getAs<DependentTemplateSpecializationType>()) {
2782 if (NestedNameSpecifier *NNS =
2783 DependentTST->getDependentTemplateName().getQualifier())
2784 T = QualType(NNS->getAsType(), 0);
2785 else
2786 T = QualType();
2787 continue;
2788 }
2789
2790 // Look one step prior in a dependent name type.
2791 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2792 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2793 T = QualType(NNS->getAsType(), 0);
2794 else
2795 T = QualType();
2796 continue;
2797 }
2798
2799 // Retrieve the parent of an enumeration type.
2800 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2801 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2802 // check here.
2803 EnumDecl *Enum = EnumT->getDecl();
2804
2805 // Get to the parent type.
2806 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2807 T = Context.getTypeDeclType(Decl: Parent);
2808 else
2809 T = QualType();
2810 continue;
2811 }
2812
2813 T = QualType();
2814 }
2815 // Reverse the nested types list, since we want to traverse from the outermost
2816 // to the innermost while checking template-parameter-lists.
2817 std::reverse(first: NestedTypes.begin(), last: NestedTypes.end());
2818
2819 // C++0x [temp.expl.spec]p17:
2820 // A member or a member template may be nested within many
2821 // enclosing class templates. In an explicit specialization for
2822 // such a member, the member declaration shall be preceded by a
2823 // template<> for each enclosing class template that is
2824 // explicitly specialized.
2825 bool SawNonEmptyTemplateParameterList = false;
2826
2827 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2828 if (SawNonEmptyTemplateParameterList) {
2829 if (!SuppressDiagnostic)
2830 Diag(DeclLoc, diag::err_specialize_member_of_template)
2831 << !Recovery << Range;
2832 Invalid = true;
2833 IsMemberSpecialization = false;
2834 return true;
2835 }
2836
2837 return false;
2838 };
2839
2840 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2841 // Check that we can have an explicit specialization here.
2842 if (CheckExplicitSpecialization(Range, true))
2843 return true;
2844
2845 // We don't have a template header, but we should.
2846 SourceLocation ExpectedTemplateLoc;
2847 if (!ParamLists.empty())
2848 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2849 else
2850 ExpectedTemplateLoc = DeclStartLoc;
2851
2852 if (!SuppressDiagnostic)
2853 Diag(DeclLoc, diag::err_template_spec_needs_header)
2854 << Range
2855 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2856 return false;
2857 };
2858
2859 unsigned ParamIdx = 0;
2860 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2861 ++TypeIdx) {
2862 T = NestedTypes[TypeIdx];
2863
2864 // Whether we expect a 'template<>' header.
2865 bool NeedEmptyTemplateHeader = false;
2866
2867 // Whether we expect a template header with parameters.
2868 bool NeedNonemptyTemplateHeader = false;
2869
2870 // For a dependent type, the set of template parameters that we
2871 // expect to see.
2872 TemplateParameterList *ExpectedTemplateParams = nullptr;
2873
2874 // C++0x [temp.expl.spec]p15:
2875 // A member or a member template may be nested within many enclosing
2876 // class templates. In an explicit specialization for such a member, the
2877 // member declaration shall be preceded by a template<> for each
2878 // enclosing class template that is explicitly specialized.
2879 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2880 if (ClassTemplatePartialSpecializationDecl *Partial
2881 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Record)) {
2882 ExpectedTemplateParams = Partial->getTemplateParameters();
2883 NeedNonemptyTemplateHeader = true;
2884 } else if (Record->isDependentType()) {
2885 if (Record->getDescribedClassTemplate()) {
2886 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2887 ->getTemplateParameters();
2888 NeedNonemptyTemplateHeader = true;
2889 }
2890 } else if (ClassTemplateSpecializationDecl *Spec
2891 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
2892 // C++0x [temp.expl.spec]p4:
2893 // Members of an explicitly specialized class template are defined
2894 // in the same manner as members of normal classes, and not using
2895 // the template<> syntax.
2896 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2897 NeedEmptyTemplateHeader = true;
2898 else
2899 continue;
2900 } else if (Record->getTemplateSpecializationKind()) {
2901 if (Record->getTemplateSpecializationKind()
2902 != TSK_ExplicitSpecialization &&
2903 TypeIdx == NumTypes - 1)
2904 IsMemberSpecialization = true;
2905
2906 continue;
2907 }
2908 } else if (const TemplateSpecializationType *TST
2909 = T->getAs<TemplateSpecializationType>()) {
2910 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2911 ExpectedTemplateParams = Template->getTemplateParameters();
2912 NeedNonemptyTemplateHeader = true;
2913 }
2914 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2915 // FIXME: We actually could/should check the template arguments here
2916 // against the corresponding template parameter list.
2917 NeedNonemptyTemplateHeader = false;
2918 }
2919
2920 // C++ [temp.expl.spec]p16:
2921 // In an explicit specialization declaration for a member of a class
2922 // template or a member template that appears in namespace scope, the
2923 // member template and some of its enclosing class templates may remain
2924 // unspecialized, except that the declaration shall not explicitly
2925 // specialize a class member template if its enclosing class templates
2926 // are not explicitly specialized as well.
2927 if (ParamIdx < ParamLists.size()) {
2928 if (ParamLists[ParamIdx]->size() == 0) {
2929 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2930 false))
2931 return nullptr;
2932 } else
2933 SawNonEmptyTemplateParameterList = true;
2934 }
2935
2936 if (NeedEmptyTemplateHeader) {
2937 // If we're on the last of the types, and we need a 'template<>' header
2938 // here, then it's a member specialization.
2939 if (TypeIdx == NumTypes - 1)
2940 IsMemberSpecialization = true;
2941
2942 if (ParamIdx < ParamLists.size()) {
2943 if (ParamLists[ParamIdx]->size() > 0) {
2944 // The header has template parameters when it shouldn't. Complain.
2945 if (!SuppressDiagnostic)
2946 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2947 diag::err_template_param_list_matches_nontemplate)
2948 << T
2949 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2950 ParamLists[ParamIdx]->getRAngleLoc())
2951 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2952 Invalid = true;
2953 return nullptr;
2954 }
2955
2956 // Consume this template header.
2957 ++ParamIdx;
2958 continue;
2959 }
2960
2961 if (!IsFriend)
2962 if (DiagnoseMissingExplicitSpecialization(
2963 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2964 return nullptr;
2965
2966 continue;
2967 }
2968
2969 if (NeedNonemptyTemplateHeader) {
2970 // In friend declarations we can have template-ids which don't
2971 // depend on the corresponding template parameter lists. But
2972 // assume that empty parameter lists are supposed to match this
2973 // template-id.
2974 if (IsFriend && T->isDependentType()) {
2975 if (ParamIdx < ParamLists.size() &&
2976 DependsOnTemplateParameters(T, Params: ParamLists[ParamIdx]))
2977 ExpectedTemplateParams = nullptr;
2978 else
2979 continue;
2980 }
2981
2982 if (ParamIdx < ParamLists.size()) {
2983 // Check the template parameter list, if we can.
2984 if (ExpectedTemplateParams &&
2985 !TemplateParameterListsAreEqual(New: ParamLists[ParamIdx],
2986 Old: ExpectedTemplateParams,
2987 Complain: !SuppressDiagnostic, Kind: TPL_TemplateMatch))
2988 Invalid = true;
2989
2990 if (!Invalid &&
2991 CheckTemplateParameterList(NewParams: ParamLists[ParamIdx], OldParams: nullptr,
2992 TPC: TPC_ClassTemplateMember))
2993 Invalid = true;
2994
2995 ++ParamIdx;
2996 continue;
2997 }
2998
2999 if (!SuppressDiagnostic)
3000 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3001 << T
3002 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3003 Invalid = true;
3004 continue;
3005 }
3006 }
3007
3008 // If there were at least as many template-ids as there were template
3009 // parameter lists, then there are no template parameter lists remaining for
3010 // the declaration itself.
3011 if (ParamIdx >= ParamLists.size()) {
3012 if (TemplateId && !IsFriend) {
3013 // We don't have a template header for the declaration itself, but we
3014 // should.
3015 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3016 TemplateId->RAngleLoc));
3017
3018 // Fabricate an empty template parameter list for the invented header.
3019 return TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(),
3020 LAngleLoc: SourceLocation(), Params: {},
3021 RAngleLoc: SourceLocation(), RequiresClause: nullptr);
3022 }
3023
3024 return nullptr;
3025 }
3026
3027 // If there were too many template parameter lists, complain about that now.
3028 if (ParamIdx < ParamLists.size() - 1) {
3029 bool HasAnyExplicitSpecHeader = false;
3030 bool AllExplicitSpecHeaders = true;
3031 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3032 if (ParamLists[I]->size() == 0)
3033 HasAnyExplicitSpecHeader = true;
3034 else
3035 AllExplicitSpecHeaders = false;
3036 }
3037
3038 if (!SuppressDiagnostic)
3039 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3040 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3041 : diag::err_template_spec_extra_headers)
3042 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3043 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3044
3045 // If there was a specialization somewhere, such that 'template<>' is
3046 // not required, and there were any 'template<>' headers, note where the
3047 // specialization occurred.
3048 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3049 !SuppressDiagnostic)
3050 Diag(ExplicitSpecLoc,
3051 diag::note_explicit_template_spec_does_not_need_header)
3052 << NestedTypes.back();
3053
3054 // We have a template parameter list with no corresponding scope, which
3055 // means that the resulting template declaration can't be instantiated
3056 // properly (we'll end up with dependent nodes when we shouldn't).
3057 if (!AllExplicitSpecHeaders)
3058 Invalid = true;
3059 }
3060
3061 // C++ [temp.expl.spec]p16:
3062 // In an explicit specialization declaration for a member of a class
3063 // template or a member template that ap- pears in namespace scope, the
3064 // member template and some of its enclosing class templates may remain
3065 // unspecialized, except that the declaration shall not explicitly
3066 // specialize a class member template if its en- closing class templates
3067 // are not explicitly specialized as well.
3068 if (ParamLists.back()->size() == 0 &&
3069 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3070 false))
3071 return nullptr;
3072
3073 // Return the last template parameter list, which corresponds to the
3074 // entity being declared.
3075 return ParamLists.back();
3076}
3077
3078void Sema::NoteAllFoundTemplates(TemplateName Name) {
3079 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3080 Diag(Template->getLocation(), diag::note_template_declared_here)
3081 << (isa<FunctionTemplateDecl>(Template)
3082 ? 0
3083 : isa<ClassTemplateDecl>(Template)
3084 ? 1
3085 : isa<VarTemplateDecl>(Template)
3086 ? 2
3087 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3088 << Template->getDeclName();
3089 return;
3090 }
3091
3092 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3093 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3094 IEnd = OST->end();
3095 I != IEnd; ++I)
3096 Diag((*I)->getLocation(), diag::note_template_declared_here)
3097 << 0 << (*I)->getDeclName();
3098
3099 return;
3100 }
3101}
3102
3103static QualType builtinCommonTypeImpl(Sema &S, TemplateName BaseTemplate,
3104 SourceLocation TemplateLoc,
3105 ArrayRef<TemplateArgument> Ts) {
3106 auto lookUpCommonType = [&](TemplateArgument T1,
3107 TemplateArgument T2) -> QualType {
3108 // Don't bother looking for other specializations if both types are
3109 // builtins - users aren't allowed to specialize for them
3110 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3111 return builtinCommonTypeImpl(S, BaseTemplate, TemplateLoc, Ts: {T1, T2});
3112
3113 TemplateArgumentListInfo Args;
3114 Args.addArgument(Loc: TemplateArgumentLoc(
3115 T1, S.Context.getTrivialTypeSourceInfo(T: T1.getAsType())));
3116 Args.addArgument(Loc: TemplateArgumentLoc(
3117 T2, S.Context.getTrivialTypeSourceInfo(T: T2.getAsType())));
3118
3119 EnterExpressionEvaluationContext UnevaluatedContext(
3120 S, Sema::ExpressionEvaluationContext::Unevaluated);
3121 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3122 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3123
3124 QualType BaseTemplateInst =
3125 S.CheckTemplateIdType(Template: BaseTemplate, TemplateLoc, TemplateArgs&: Args);
3126
3127 if (SFINAE.hasErrorOccurred())
3128 return QualType();
3129
3130 return BaseTemplateInst;
3131 };
3132
3133 // Note A: For the common_type trait applied to a template parameter pack T of
3134 // types, the member type shall be either defined or not present as follows:
3135 switch (Ts.size()) {
3136
3137 // If sizeof...(T) is zero, there shall be no member type.
3138 case 0:
3139 return QualType();
3140
3141 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3142 // pack T. The member typedef-name type shall denote the same type, if any, as
3143 // common_type_t<T0, T0>; otherwise there shall be no member type.
3144 case 1:
3145 return lookUpCommonType(Ts[0], Ts[0]);
3146
3147 // If sizeof...(T) is two, let the first and second types constituting T be
3148 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3149 // as decay_t<T1> and decay_t<T2>, respectively.
3150 case 2: {
3151 QualType T1 = Ts[0].getAsType();
3152 QualType T2 = Ts[1].getAsType();
3153 QualType D1 = S.BuiltinDecay(BaseType: T1, Loc: {});
3154 QualType D2 = S.BuiltinDecay(BaseType: T2, Loc: {});
3155
3156 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3157 // the same type, if any, as common_type_t<D1, D2>.
3158 if (!S.Context.hasSameType(T1, T2: D1) || !S.Context.hasSameType(T1: T2, T2: D2))
3159 return lookUpCommonType(D1, D2);
3160
3161 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3162 // denotes a valid type, let C denote that type.
3163 {
3164 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3165 EnterExpressionEvaluationContext UnevaluatedContext(
3166 S, Sema::ExpressionEvaluationContext::Unevaluated);
3167 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3168 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3169
3170 // false
3171 OpaqueValueExpr CondExpr(SourceLocation(), S.Context.BoolTy,
3172 VK_PRValue);
3173 ExprResult Cond = &CondExpr;
3174
3175 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3176 if (ConstRefQual) {
3177 D1.addConst();
3178 D2.addConst();
3179 }
3180
3181 // declval<D1>()
3182 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3183 ExprResult LHS = &LHSExpr;
3184
3185 // declval<D2>()
3186 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3187 ExprResult RHS = &RHSExpr;
3188
3189 ExprValueKind VK = VK_PRValue;
3190 ExprObjectKind OK = OK_Ordinary;
3191
3192 // decltype(false ? declval<D1>() : declval<D2>())
3193 QualType Result =
3194 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc: TemplateLoc);
3195
3196 if (Result.isNull() || SFINAE.hasErrorOccurred())
3197 return QualType();
3198
3199 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3200 return S.BuiltinDecay(BaseType: Result, Loc: TemplateLoc);
3201 };
3202
3203 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3204 return Res;
3205
3206 // Let:
3207 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3208 // COND-RES(X, Y) be
3209 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3210
3211 // C++20 only
3212 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3213 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3214 if (!S.Context.getLangOpts().CPlusPlus20)
3215 return QualType();
3216 return CheckConditionalOperands(true);
3217 }
3218 }
3219
3220 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3221 // denote the first, second, and (pack of) remaining types constituting T. Let
3222 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3223 // a type C, the member typedef-name type shall denote the same type, if any,
3224 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3225 default: {
3226 QualType Result = Ts.front().getAsType();
3227 for (auto T : llvm::drop_begin(RangeOrContainer&: Ts)) {
3228 Result = lookUpCommonType(Result, T.getAsType());
3229 if (Result.isNull())
3230 return QualType();
3231 }
3232 return Result;
3233 }
3234 }
3235}
3236
3237static bool isInVkNamespace(const RecordType *RT) {
3238 DeclContext *DC = RT->getDecl()->getDeclContext();
3239 if (!DC)
3240 return false;
3241
3242 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: DC);
3243 if (!ND)
3244 return false;
3245
3246 return ND->getQualifiedNameAsString() == "hlsl::vk";
3247}
3248
3249static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3250 QualType OperandArg,
3251 SourceLocation Loc) {
3252 if (auto *RT = OperandArg->getAs<RecordType>()) {
3253 bool Literal = false;
3254 SourceLocation LiteralLoc;
3255 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3256 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3257 assert(SpecDecl);
3258
3259 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3260 QualType ConstantType = LiteralArgs[0].getAsType();
3261 RT = ConstantType->getAs<RecordType>();
3262 Literal = true;
3263 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3264 }
3265
3266 if (RT && isInVkNamespace(RT) &&
3267 RT->getDecl()->getName() == "integral_constant") {
3268 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3269 assert(SpecDecl);
3270
3271 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3272
3273 QualType ConstantType = ConstantArgs[0].getAsType();
3274 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3275
3276 if (Literal)
3277 return SpirvOperand::createLiteral(Val: Value);
3278 return SpirvOperand::createConstant(ResultType: ConstantType, Val: Value);
3279 } else if (Literal) {
3280 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3281 return SpirvOperand();
3282 }
3283 }
3284 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3285 diag::err_call_incomplete_argument))
3286 return SpirvOperand();
3287 return SpirvOperand::createType(T: OperandArg);
3288}
3289
3290static QualType
3291checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3292 ArrayRef<TemplateArgument> Converted,
3293 SourceLocation TemplateLoc,
3294 TemplateArgumentListInfo &TemplateArgs) {
3295 ASTContext &Context = SemaRef.getASTContext();
3296
3297 switch (BTD->getBuiltinTemplateKind()) {
3298 case BTK__make_integer_seq: {
3299 // Specializations of __make_integer_seq<S, T, N> are treated like
3300 // S<T, 0, ..., N-1>.
3301
3302 QualType OrigType = Converted[1].getAsType();
3303 // C++14 [inteseq.intseq]p1:
3304 // T shall be an integer type.
3305 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Ctx: Context)) {
3306 SemaRef.Diag(TemplateArgs[1].getLocation(),
3307 diag::err_integer_sequence_integral_element_type);
3308 return QualType();
3309 }
3310
3311 TemplateArgument NumArgsArg = Converted[2];
3312 if (NumArgsArg.isDependent())
3313 return QualType();
3314
3315 TemplateArgumentListInfo SyntheticTemplateArgs;
3316 // The type argument, wrapped in substitution sugar, gets reused as the
3317 // first template argument in the synthetic template argument list.
3318 SyntheticTemplateArgs.addArgument(
3319 Loc: TemplateArgumentLoc(TemplateArgument(OrigType),
3320 SemaRef.Context.getTrivialTypeSourceInfo(
3321 T: OrigType, Loc: TemplateArgs[1].getLocation())));
3322
3323 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3324 // Expand N into 0 ... N-1.
3325 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3326 I < NumArgs; ++I) {
3327 TemplateArgument TA(Context, I, OrigType);
3328 SyntheticTemplateArgs.addArgument(Loc: SemaRef.getTrivialTemplateArgumentLoc(
3329 Arg: TA, NTTPType: OrigType, Loc: TemplateArgs[2].getLocation()));
3330 }
3331 } else {
3332 // C++14 [inteseq.make]p1:
3333 // If N is negative the program is ill-formed.
3334 SemaRef.Diag(TemplateArgs[2].getLocation(),
3335 diag::err_integer_sequence_negative_length);
3336 return QualType();
3337 }
3338
3339 // The first template argument will be reused as the template decl that
3340 // our synthetic template arguments will be applied to.
3341 return SemaRef.CheckTemplateIdType(Template: Converted[0].getAsTemplate(),
3342 TemplateLoc, TemplateArgs&: SyntheticTemplateArgs);
3343 }
3344
3345 case BTK__type_pack_element: {
3346 // Specializations of
3347 // __type_pack_element<Index, T_1, ..., T_N>
3348 // are treated like T_Index.
3349 assert(Converted.size() == 2 &&
3350 "__type_pack_element should be given an index and a parameter pack");
3351
3352 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3353 if (IndexArg.isDependent() || Ts.isDependent())
3354 return QualType();
3355
3356 llvm::APSInt Index = IndexArg.getAsIntegral();
3357 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3358 "type std::size_t, and hence be non-negative");
3359 // If the Index is out of bounds, the program is ill-formed.
3360 if (Index >= Ts.pack_size()) {
3361 SemaRef.Diag(TemplateArgs[0].getLocation(),
3362 diag::err_type_pack_element_out_of_bounds);
3363 return QualType();
3364 }
3365
3366 // We simply return the type at index `Index`.
3367 int64_t N = Index.getExtValue();
3368 return Ts.getPackAsArray()[N].getAsType();
3369 }
3370
3371 case BTK__builtin_common_type: {
3372 assert(Converted.size() == 4);
3373 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3374 return QualType();
3375
3376 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3377 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3378 if (auto CT = builtinCommonTypeImpl(S&: SemaRef, BaseTemplate, TemplateLoc, Ts);
3379 !CT.isNull()) {
3380 TemplateArgumentListInfo TAs;
3381 TAs.addArgument(Loc: TemplateArgumentLoc(
3382 TemplateArgument(CT), SemaRef.Context.getTrivialTypeSourceInfo(
3383 T: CT, Loc: TemplateArgs[1].getLocation())));
3384 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3385 return SemaRef.CheckTemplateIdType(Template: HasTypeMember, TemplateLoc, TemplateArgs&: TAs);
3386 }
3387 QualType HasNoTypeMember = Converted[2].getAsType();
3388 return HasNoTypeMember;
3389 }
3390
3391 case BTK__hlsl_spirv_type: {
3392 assert(Converted.size() == 4);
3393
3394 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3395 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3396 }
3397
3398 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3399 return QualType();
3400
3401 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3402 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3403 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3404
3405 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3406
3407 llvm::SmallVector<SpirvOperand> Operands;
3408
3409 for (auto &OperandTA : OperandArgs) {
3410 QualType OperandArg = OperandTA.getAsType();
3411 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3412 Loc: TemplateArgs[3].getLocation());
3413 if (!Operand.isValid())
3414 return QualType();
3415 Operands.push_back(Elt: Operand);
3416 }
3417
3418 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3419 }
3420 }
3421 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3422}
3423
3424/// Determine whether this alias template is "enable_if_t".
3425/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3426static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3427 return AliasTemplate->getName() == "enable_if_t" ||
3428 AliasTemplate->getName() == "__enable_if_t";
3429}
3430
3431/// Collect all of the separable terms in the given condition, which
3432/// might be a conjunction.
3433///
3434/// FIXME: The right answer is to convert the logical expression into
3435/// disjunctive normal form, so we can find the first failed term
3436/// within each possible clause.
3437static void collectConjunctionTerms(Expr *Clause,
3438 SmallVectorImpl<Expr *> &Terms) {
3439 if (auto BinOp = dyn_cast<BinaryOperator>(Val: Clause->IgnoreParenImpCasts())) {
3440 if (BinOp->getOpcode() == BO_LAnd) {
3441 collectConjunctionTerms(Clause: BinOp->getLHS(), Terms);
3442 collectConjunctionTerms(Clause: BinOp->getRHS(), Terms);
3443 return;
3444 }
3445 }
3446
3447 Terms.push_back(Elt: Clause);
3448}
3449
3450// The ranges-v3 library uses an odd pattern of a top-level "||" with
3451// a left-hand side that is value-dependent but never true. Identify
3452// the idiom and ignore that term.
3453static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3454 // Top-level '||'.
3455 auto *BinOp = dyn_cast<BinaryOperator>(Val: Cond->IgnoreParenImpCasts());
3456 if (!BinOp) return Cond;
3457
3458 if (BinOp->getOpcode() != BO_LOr) return Cond;
3459
3460 // With an inner '==' that has a literal on the right-hand side.
3461 Expr *LHS = BinOp->getLHS();
3462 auto *InnerBinOp = dyn_cast<BinaryOperator>(Val: LHS->IgnoreParenImpCasts());
3463 if (!InnerBinOp) return Cond;
3464
3465 if (InnerBinOp->getOpcode() != BO_EQ ||
3466 !isa<IntegerLiteral>(Val: InnerBinOp->getRHS()))
3467 return Cond;
3468
3469 // If the inner binary operation came from a macro expansion named
3470 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3471 // of the '||', which is the real, user-provided condition.
3472 SourceLocation Loc = InnerBinOp->getExprLoc();
3473 if (!Loc.isMacroID()) return Cond;
3474
3475 StringRef MacroName = PP.getImmediateMacroName(Loc);
3476 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3477 return BinOp->getRHS();
3478
3479 return Cond;
3480}
3481
3482namespace {
3483
3484// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3485// within failing boolean expression, such as substituting template parameters
3486// for actual types.
3487class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3488public:
3489 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3490 : Policy(P) {}
3491
3492 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3493 const auto *DR = dyn_cast<DeclRefExpr>(Val: E);
3494 if (DR && DR->getQualifier()) {
3495 // If this is a qualified name, expand the template arguments in nested
3496 // qualifiers.
3497 DR->getQualifier()->print(OS, Policy, ResolveTemplateArguments: true);
3498 // Then print the decl itself.
3499 const ValueDecl *VD = DR->getDecl();
3500 OS << VD->getName();
3501 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) {
3502 // This is a template variable, print the expanded template arguments.
3503 printTemplateArgumentList(
3504 OS, IV->getTemplateArgs().asArray(), Policy,
3505 IV->getSpecializedTemplate()->getTemplateParameters());
3506 }
3507 return true;
3508 }
3509 return false;
3510 }
3511
3512private:
3513 const PrintingPolicy Policy;
3514};
3515
3516} // end anonymous namespace
3517
3518std::pair<Expr *, std::string>
3519Sema::findFailedBooleanCondition(Expr *Cond) {
3520 Cond = lookThroughRangesV3Condition(PP, Cond);
3521
3522 // Separate out all of the terms in a conjunction.
3523 SmallVector<Expr *, 4> Terms;
3524 collectConjunctionTerms(Clause: Cond, Terms);
3525
3526 // Determine which term failed.
3527 Expr *FailedCond = nullptr;
3528 for (Expr *Term : Terms) {
3529 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3530
3531 // Literals are uninteresting.
3532 if (isa<CXXBoolLiteralExpr>(Val: TermAsWritten) ||
3533 isa<IntegerLiteral>(Val: TermAsWritten))
3534 continue;
3535
3536 // The initialization of the parameter from the argument is
3537 // a constant-evaluated context.
3538 EnterExpressionEvaluationContext ConstantEvaluated(
3539 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3540
3541 bool Succeeded;
3542 if (Term->EvaluateAsBooleanCondition(Result&: Succeeded, Ctx: Context) &&
3543 !Succeeded) {
3544 FailedCond = TermAsWritten;
3545 break;
3546 }
3547 }
3548 if (!FailedCond)
3549 FailedCond = Cond->IgnoreParenImpCasts();
3550
3551 std::string Description;
3552 {
3553 llvm::raw_string_ostream Out(Description);
3554 PrintingPolicy Policy = getPrintingPolicy();
3555 Policy.PrintAsCanonical = true;
3556 FailedBooleanConditionPrinterHelper Helper(Policy);
3557 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3558 }
3559 return { FailedCond, Description };
3560}
3561
3562QualType Sema::CheckTemplateIdType(TemplateName Name,
3563 SourceLocation TemplateLoc,
3564 TemplateArgumentListInfo &TemplateArgs) {
3565 // FIXME: 'getUnderlying' loses SubstTemplateTemplateParm nodes from alias
3566 // template substitutions.
3567 if (DependentTemplateName *DTN =
3568 Name.getUnderlying().getAsDependentTemplateName();
3569 DTN && DTN->getName().getIdentifier())
3570 // When building a template-id where the template-name is dependent,
3571 // assume the template is a type template. Either our assumption is
3572 // correct, or the code is ill-formed and will be diagnosed when the
3573 // dependent name is substituted.
3574 return Context.getDependentTemplateSpecializationType(
3575 Keyword: ElaboratedTypeKeyword::None, Name: *DTN, Args: TemplateArgs.arguments());
3576
3577 if (Name.getAsAssumedTemplateName() &&
3578 resolveAssumedTemplateNameAsType(/*Scope=*/S: nullptr, Name, NameLoc: TemplateLoc))
3579 return QualType();
3580
3581 TemplateDecl *Template;
3582 DefaultArguments DefaultArgs;
3583 if (const SubstTemplateTemplateParmPackStorage *S =
3584 Name.getAsSubstTemplateTemplateParmPack()) {
3585 Template = S->getParameterPack();
3586 } else {
3587 std::tie(args&: Template, args&: DefaultArgs) = Name.getTemplateDeclAndDefaultArgs();
3588 if (!Template || isa<FunctionTemplateDecl>(Val: Template) ||
3589 isa<VarTemplateDecl>(Val: Template) || isa<ConceptDecl>(Val: Template)) {
3590 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name;
3591 NoteAllFoundTemplates(Name);
3592 return QualType();
3593 }
3594 }
3595
3596 // Check that the template argument list is well-formed for this
3597 // template.
3598 CheckTemplateArgumentInfo CTAI;
3599 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3600 DefaultArgs, /*PartialTemplateArgs=*/false,
3601 CTAI,
3602 /*UpdateArgsWithConversions=*/true))
3603 return QualType();
3604
3605 QualType CanonType;
3606
3607 if (isa<TemplateTemplateParmDecl>(Val: Template)) {
3608 // We might have a substituted template template parameter pack. If so,
3609 // build a template specialization type for it.
3610 } else if (TypeAliasTemplateDecl *AliasTemplate =
3611 dyn_cast<TypeAliasTemplateDecl>(Val: Template)) {
3612
3613 // Find the canonical type for this type alias template specialization.
3614 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3615 if (Pattern->isInvalidDecl())
3616 return QualType();
3617
3618 // Only substitute for the innermost template argument list.
3619 MultiLevelTemplateArgumentList TemplateArgLists;
3620 TemplateArgLists.addOuterTemplateArguments(Template, CTAI.SugaredConverted,
3621 /*Final=*/true);
3622 TemplateArgLists.addOuterRetainedLevels(
3623 Num: AliasTemplate->getTemplateParameters()->getDepth());
3624
3625 LocalInstantiationScope Scope(*this);
3626 InstantiatingTemplate Inst(
3627 *this, /*PointOfInstantiation=*/TemplateLoc,
3628 /*Entity=*/AliasTemplate,
3629 /*TemplateArgs=*/TemplateArgLists.getInnermost());
3630
3631 // Diagnose uses of this alias.
3632 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3633
3634 if (Inst.isInvalid())
3635 return QualType();
3636
3637 std::optional<ContextRAII> SavedContext;
3638 if (!AliasTemplate->getDeclContext()->isFileContext())
3639 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3640
3641 CanonType =
3642 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3643 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3644 if (CanonType.isNull()) {
3645 // If this was enable_if and we failed to find the nested type
3646 // within enable_if in a SFINAE context, dig out the specific
3647 // enable_if condition that failed and present that instead.
3648 if (isEnableIfAliasTemplate(AliasTemplate)) {
3649 if (auto DeductionInfo = isSFINAEContext()) {
3650 if (*DeductionInfo &&
3651 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3652 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3653 diag::err_typename_nested_not_found_enable_if &&
3654 TemplateArgs[0].getArgument().getKind()
3655 == TemplateArgument::Expression) {
3656 Expr *FailedCond;
3657 std::string FailedDescription;
3658 std::tie(args&: FailedCond, args&: FailedDescription) =
3659 findFailedBooleanCondition(Cond: TemplateArgs[0].getSourceExpression());
3660
3661 // Remove the old SFINAE diagnostic.
3662 PartialDiagnosticAt OldDiag =
3663 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3664 (*DeductionInfo)->takeSFINAEDiagnostic(PD&: OldDiag);
3665
3666 // Add a new SFINAE diagnostic specifying which condition
3667 // failed.
3668 (*DeductionInfo)->addSFINAEDiagnostic(
3669 OldDiag.first,
3670 PDiag(diag::err_typename_nested_not_found_requirement)
3671 << FailedDescription
3672 << FailedCond->getSourceRange());
3673 }
3674 }
3675 }
3676
3677 return QualType();
3678 }
3679 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Val: Template)) {
3680 CanonType = checkBuiltinTemplateIdType(SemaRef&: *this, BTD, Converted: CTAI.SugaredConverted,
3681 TemplateLoc, TemplateArgs);
3682 } else if (Name.isDependent() ||
3683 TemplateSpecializationType::anyDependentTemplateArguments(
3684 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
3685 // This class template specialization is a dependent
3686 // type. Therefore, its canonical type is another class template
3687 // specialization type that contains all of the converted
3688 // arguments in canonical form. This ensures that, e.g., A<T> and
3689 // A<T, T> have identical types when A is declared as:
3690 //
3691 // template<typename T, typename U = T> struct A;
3692 CanonType = Context.getCanonicalTemplateSpecializationType(
3693 T: Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3694 CanonicalArgs: CTAI.CanonicalConverted);
3695 assert(CanonType->isCanonicalUnqualified());
3696
3697 // This might work out to be a current instantiation, in which
3698 // case the canonical type needs to be the InjectedClassNameType.
3699 //
3700 // TODO: in theory this could be a simple hashtable lookup; most
3701 // changes to CurContext don't change the set of current
3702 // instantiations.
3703 if (isa<ClassTemplateDecl>(Val: Template)) {
3704 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3705 // If we get out to a namespace, we're done.
3706 if (Ctx->isFileContext()) break;
3707
3708 // If this isn't a record, keep looking.
3709 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Ctx);
3710 if (!Record) continue;
3711
3712 // Look for one of the two cases with InjectedClassNameTypes
3713 // and check whether it's the same template.
3714 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Record) &&
3715 !Record->getDescribedClassTemplate())
3716 continue;
3717
3718 // Fetch the injected class name type and check whether its
3719 // injected type is equal to the type we just built.
3720 QualType ICNT = Context.getTypeDeclType(Record);
3721 QualType Injected = cast<InjectedClassNameType>(Val&: ICNT)
3722 ->getInjectedSpecializationType();
3723
3724 if (CanonType != Injected->getCanonicalTypeInternal())
3725 continue;
3726
3727 // If so, the canonical type of this TST is the injected
3728 // class name type of the record we just found.
3729 assert(ICNT.isCanonical());
3730 CanonType = ICNT;
3731 break;
3732 }
3733 }
3734 } else if (ClassTemplateDecl *ClassTemplate =
3735 dyn_cast<ClassTemplateDecl>(Val: Template)) {
3736 // Find the class template specialization declaration that
3737 // corresponds to these arguments.
3738 void *InsertPos = nullptr;
3739 ClassTemplateSpecializationDecl *Decl =
3740 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
3741 if (!Decl) {
3742 // This is the first time we have referenced this class template
3743 // specialization. Create the canonical declaration and add it to
3744 // the set of specializations.
3745 Decl = ClassTemplateSpecializationDecl::Create(
3746 Context, TK: ClassTemplate->getTemplatedDecl()->getTagKind(),
3747 DC: ClassTemplate->getDeclContext(),
3748 StartLoc: ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3749 IdLoc: ClassTemplate->getLocation(), SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted,
3750 StrictPackMatch: CTAI.StrictPackMatch, PrevDecl: nullptr);
3751 ClassTemplate->AddSpecialization(D: Decl, InsertPos);
3752 if (ClassTemplate->isOutOfLine())
3753 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3754 }
3755
3756 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3757 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3758 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3759 if (!Inst.isInvalid()) {
3760 MultiLevelTemplateArgumentList TemplateArgLists(Template,
3761 CTAI.CanonicalConverted,
3762 /*Final=*/false);
3763 InstantiateAttrsForDecl(TemplateArgLists,
3764 ClassTemplate->getTemplatedDecl(), Decl);
3765 }
3766 }
3767
3768 // Diagnose uses of this specialization.
3769 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3770
3771 CanonType = Context.getTypeDeclType(Decl);
3772 assert(isa<RecordType>(CanonType) &&
3773 "type of non-dependent specialization is not a RecordType");
3774 } else {
3775 llvm_unreachable("Unhandled template kind");
3776 }
3777
3778 // Build the fully-sugared type for this class template
3779 // specialization, which refers back to the class template
3780 // specialization we created or found.
3781 return Context.getTemplateSpecializationType(
3782 T: Name, SpecifiedArgs: TemplateArgs.arguments(), CanonicalArgs: CTAI.CanonicalConverted, Canon: CanonType);
3783}
3784
3785void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3786 TemplateNameKind &TNK,
3787 SourceLocation NameLoc,
3788 IdentifierInfo *&II) {
3789 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3790
3791 TemplateName Name = ParsedName.get();
3792 auto *ATN = Name.getAsAssumedTemplateName();
3793 assert(ATN && "not an assumed template name");
3794 II = ATN->getDeclName().getAsIdentifierInfo();
3795
3796 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3797 // Resolved to a type template name.
3798 ParsedName = TemplateTy::make(P: Name);
3799 TNK = TNK_Type_template;
3800 }
3801}
3802
3803bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3804 SourceLocation NameLoc,
3805 bool Diagnose) {
3806 // We assumed this undeclared identifier to be an (ADL-only) function
3807 // template name, but it was used in a context where a type was required.
3808 // Try to typo-correct it now.
3809 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3810 assert(ATN && "not an assumed template name");
3811
3812 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3813 struct CandidateCallback : CorrectionCandidateCallback {
3814 bool ValidateCandidate(const TypoCorrection &TC) override {
3815 return TC.getCorrectionDecl() &&
3816 getAsTypeTemplateDecl(TC.getCorrectionDecl());
3817 }
3818 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3819 return std::make_unique<CandidateCallback>(args&: *this);
3820 }
3821 } FilterCCC;
3822
3823 TypoCorrection Corrected =
3824 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: nullptr,
3825 CCC&: FilterCCC, Mode: CorrectTypoKind::ErrorRecovery);
3826 if (Corrected && Corrected.getFoundDecl()) {
3827 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3828 << ATN->getDeclName());
3829 Name = Context.getQualifiedTemplateName(
3830 /*NNS=*/nullptr, /*TemplateKeyword=*/false,
3831 Template: TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()));
3832 return false;
3833 }
3834
3835 if (Diagnose)
3836 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3837 return true;
3838}
3839
3840TypeResult Sema::ActOnTemplateIdType(
3841 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3842 TemplateTy TemplateD, const IdentifierInfo *TemplateII,
3843 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3844 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3845 bool IsCtorOrDtorName, bool IsClassName,
3846 ImplicitTypenameContext AllowImplicitTypename) {
3847 if (SS.isInvalid())
3848 return true;
3849
3850 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3851 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3852
3853 // C++ [temp.res]p3:
3854 // A qualified-id that refers to a type and in which the
3855 // nested-name-specifier depends on a template-parameter (14.6.2)
3856 // shall be prefixed by the keyword typename to indicate that the
3857 // qualified-id denotes a type, forming an
3858 // elaborated-type-specifier (7.1.5.3).
3859 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3860 // C++2a relaxes some of those restrictions in [temp.res]p5.
3861 NestedNameSpecifier *NNS =
3862 NestedNameSpecifier::Create(Context, Prefix: SS.getScopeRep(), II: TemplateII);
3863 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3864 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
3865 << NNS;
3866 if (!getLangOpts().CPlusPlus20)
3867 DB << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "typename ");
3868 } else
3869 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
3870
3871 // FIXME: This is not quite correct recovery as we don't transform SS
3872 // into the corresponding dependent form (and we don't diagnose missing
3873 // 'template' keywords within SS as a result).
3874 return ActOnTypenameType(S: nullptr, TypenameLoc: SourceLocation(), SS, TemplateLoc: TemplateKWLoc,
3875 TemplateName: TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3876 TemplateArgs: TemplateArgsIn, RAngleLoc);
3877 }
3878
3879 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3880 // it's not actually allowed to be used as a type in most cases. Because
3881 // we annotate it before we know whether it's valid, we have to check for
3882 // this case here.
3883 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
3884 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3885 Diag(TemplateIILoc,
3886 TemplateKWLoc.isInvalid()
3887 ? diag::err_out_of_line_qualified_id_type_names_constructor
3888 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3889 << TemplateII << 0 /*injected-class-name used as template name*/
3890 << 1 /*if any keyword was present, it was 'template'*/;
3891 }
3892 }
3893
3894 TemplateName Template = TemplateD.get();
3895 if (Template.getAsAssumedTemplateName() &&
3896 resolveAssumedTemplateNameAsType(S, Name&: Template, NameLoc: TemplateIILoc))
3897 return true;
3898
3899 // Translate the parser's template argument list in our AST format.
3900 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3901 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3902
3903 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3904 assert(SS.getScopeRep() == DTN->getQualifier());
3905 QualType T = Context.getDependentTemplateSpecializationType(
3906 Keyword: ElaboratedTypeKeyword::None, Name: *DTN, Args: TemplateArgs.arguments());
3907 // Build type-source information.
3908 TypeLocBuilder TLB;
3909 DependentTemplateSpecializationTypeLoc SpecTL
3910 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3911 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3912 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3913 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3914 SpecTL.setTemplateNameLoc(TemplateIILoc);
3915 SpecTL.setLAngleLoc(LAngleLoc);
3916 SpecTL.setRAngleLoc(RAngleLoc);
3917 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3918 SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo());
3919 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
3920 }
3921
3922 QualType SpecTy = CheckTemplateIdType(Name: Template, TemplateLoc: TemplateIILoc, TemplateArgs);
3923 if (SpecTy.isNull())
3924 return true;
3925
3926 // Build type-source information.
3927 TypeLocBuilder TLB;
3928 TemplateSpecializationTypeLoc SpecTL =
3929 TLB.push<TemplateSpecializationTypeLoc>(T: SpecTy);
3930 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3931 SpecTL.setTemplateNameLoc(TemplateIILoc);
3932 SpecTL.setLAngleLoc(LAngleLoc);
3933 SpecTL.setRAngleLoc(RAngleLoc);
3934 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3935 SpecTL.setArgLocInfo(i, AI: TemplateArgs[i].getLocInfo());
3936
3937 // Create an elaborated-type-specifier containing the nested-name-specifier.
3938 QualType ElTy =
3939 getElaboratedType(Keyword: ElaboratedTypeKeyword::None,
3940 SS: !IsCtorOrDtorName ? SS : CXXScopeSpec(), T: SpecTy);
3941 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(T: ElTy);
3942 ElabTL.setElaboratedKeywordLoc(SourceLocation());
3943 if (!ElabTL.isEmpty())
3944 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3945 return CreateParsedType(T: ElTy, TInfo: TLB.getTypeSourceInfo(Context, T: ElTy));
3946}
3947
3948TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3949 TypeSpecifierType TagSpec,
3950 SourceLocation TagLoc,
3951 CXXScopeSpec &SS,
3952 SourceLocation TemplateKWLoc,
3953 TemplateTy TemplateD,
3954 SourceLocation TemplateLoc,
3955 SourceLocation LAngleLoc,
3956 ASTTemplateArgsPtr TemplateArgsIn,
3957 SourceLocation RAngleLoc) {
3958 if (SS.isInvalid())
3959 return TypeResult(true);
3960
3961 TemplateName Template = TemplateD.get();
3962
3963 // Translate the parser's template argument list in our AST format.
3964 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3965 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3966
3967 // Determine the tag kind
3968 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
3969 ElaboratedTypeKeyword Keyword
3970 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
3971
3972 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3973 assert(SS.getScopeRep() == DTN->getQualifier());
3974 QualType T = Context.getDependentTemplateSpecializationType(
3975 Keyword, Name: *DTN, Args: TemplateArgs.arguments());
3976
3977 // Build type-source information.
3978 TypeLocBuilder TLB;
3979 DependentTemplateSpecializationTypeLoc SpecTL
3980 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3981 SpecTL.setElaboratedKeywordLoc(TagLoc);
3982 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3983 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3984 SpecTL.setTemplateNameLoc(TemplateLoc);
3985 SpecTL.setLAngleLoc(LAngleLoc);
3986 SpecTL.setRAngleLoc(RAngleLoc);
3987 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3988 SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo());
3989 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
3990 }
3991
3992 if (TypeAliasTemplateDecl *TAT =
3993 dyn_cast_or_null<TypeAliasTemplateDecl>(Val: Template.getAsTemplateDecl())) {
3994 // C++0x [dcl.type.elab]p2:
3995 // If the identifier resolves to a typedef-name or the simple-template-id
3996 // resolves to an alias template specialization, the
3997 // elaborated-type-specifier is ill-formed.
3998 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3999 << TAT << NonTagKind::TypeAliasTemplate << TagKind;
4000 Diag(TAT->getLocation(), diag::note_declared_at);
4001 }
4002
4003 QualType Result = CheckTemplateIdType(Name: Template, TemplateLoc, TemplateArgs);
4004 if (Result.isNull())
4005 return TypeResult(true);
4006
4007 // Check the tag kind
4008 if (const RecordType *RT = Result->getAs<RecordType>()) {
4009 RecordDecl *D = RT->getDecl();
4010
4011 IdentifierInfo *Id = D->getIdentifier();
4012 assert(Id && "templated class must have an identifier");
4013
4014 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TagUseKind::Definition,
4015 TagLoc, Id)) {
4016 Diag(TagLoc, diag::err_use_with_wrong_tag)
4017 << Result
4018 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
4019 Diag(D->getLocation(), diag::note_previous_use);
4020 }
4021 }
4022
4023 // Provide source-location information for the template specialization.
4024 TypeLocBuilder TLB;
4025 TemplateSpecializationTypeLoc SpecTL
4026 = TLB.push<TemplateSpecializationTypeLoc>(T: Result);
4027 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4028 SpecTL.setTemplateNameLoc(TemplateLoc);
4029 SpecTL.setLAngleLoc(LAngleLoc);
4030 SpecTL.setRAngleLoc(RAngleLoc);
4031 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4032 SpecTL.setArgLocInfo(i, AI: TemplateArgs[i].getLocInfo());
4033
4034 // Construct an elaborated type containing the nested-name-specifier (if any)
4035 // and tag keyword.
4036 Result = Context.getElaboratedType(Keyword, NNS: SS.getScopeRep(), NamedType: Result);
4037 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(T: Result);
4038 ElabTL.setElaboratedKeywordLoc(TagLoc);
4039 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4040 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
4041}
4042
4043static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4044 NamedDecl *PrevDecl,
4045 SourceLocation Loc,
4046 bool IsPartialSpecialization);
4047
4048static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4049
4050static bool isTemplateArgumentTemplateParameter(
4051 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
4052 switch (Arg.getKind()) {
4053 case TemplateArgument::Null:
4054 case TemplateArgument::NullPtr:
4055 case TemplateArgument::Integral:
4056 case TemplateArgument::Declaration:
4057 case TemplateArgument::StructuralValue:
4058 case TemplateArgument::Pack:
4059 case TemplateArgument::TemplateExpansion:
4060 return false;
4061
4062 case TemplateArgument::Type: {
4063 QualType Type = Arg.getAsType();
4064 const TemplateTypeParmType *TPT =
4065 Arg.getAsType()->getAs<TemplateTypeParmType>();
4066 return TPT && !Type.hasQualifiers() &&
4067 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4068 }
4069
4070 case TemplateArgument::Expression: {
4071 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg.getAsExpr());
4072 if (!DRE || !DRE->getDecl())
4073 return false;
4074 const NonTypeTemplateParmDecl *NTTP =
4075 dyn_cast<NonTypeTemplateParmDecl>(Val: DRE->getDecl());
4076 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4077 }
4078
4079 case TemplateArgument::Template:
4080 const TemplateTemplateParmDecl *TTP =
4081 dyn_cast_or_null<TemplateTemplateParmDecl>(
4082 Val: Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4083 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4084 }
4085 llvm_unreachable("unexpected kind of template argument");
4086}
4087
4088static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4089 ArrayRef<TemplateArgument> Args) {
4090 if (Params->size() != Args.size())
4091 return false;
4092
4093 unsigned Depth = Params->getDepth();
4094
4095 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4096 TemplateArgument Arg = Args[I];
4097
4098 // If the parameter is a pack expansion, the argument must be a pack
4099 // whose only element is a pack expansion.
4100 if (Params->getParam(Idx: I)->isParameterPack()) {
4101 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4102 !Arg.pack_begin()->isPackExpansion())
4103 return false;
4104 Arg = Arg.pack_begin()->getPackExpansionPattern();
4105 }
4106
4107 if (!isTemplateArgumentTemplateParameter(Arg, Depth, Index: I))
4108 return false;
4109 }
4110
4111 return true;
4112}
4113
4114template<typename PartialSpecDecl>
4115static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4116 if (Partial->getDeclContext()->isDependentContext())
4117 return;
4118
4119 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4120 // for non-substitution-failure issues?
4121 TemplateDeductionInfo Info(Partial->getLocation());
4122 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4123 return;
4124
4125 auto *Template = Partial->getSpecializedTemplate();
4126 S.Diag(Partial->getLocation(),
4127 diag::ext_partial_spec_not_more_specialized_than_primary)
4128 << isa<VarTemplateDecl>(Template);
4129
4130 if (Info.hasSFINAEDiagnostic()) {
4131 PartialDiagnosticAt Diag = {SourceLocation(),
4132 PartialDiagnostic::NullDiagnostic()};
4133 Info.takeSFINAEDiagnostic(PD&: Diag);
4134 SmallString<128> SFINAEArgString;
4135 Diag.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
4136 S.Diag(Diag.first,
4137 diag::note_partial_spec_not_more_specialized_than_primary)
4138 << SFINAEArgString;
4139 }
4140
4141 S.NoteTemplateLocation(Decl: *Template);
4142 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4143 Template->getAssociatedConstraints(TemplateAC);
4144 Partial->getAssociatedConstraints(PartialAC);
4145 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Partial, AC1: PartialAC, D2: Template,
4146 AC2: TemplateAC);
4147}
4148
4149static void
4150noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4151 const llvm::SmallBitVector &DeducibleParams) {
4152 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4153 if (!DeducibleParams[I]) {
4154 NamedDecl *Param = TemplateParams->getParam(Idx: I);
4155 if (Param->getDeclName())
4156 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4157 << Param->getDeclName();
4158 else
4159 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4160 << "(anonymous)";
4161 }
4162 }
4163}
4164
4165
4166template<typename PartialSpecDecl>
4167static void checkTemplatePartialSpecialization(Sema &S,
4168 PartialSpecDecl *Partial) {
4169 // C++1z [temp.class.spec]p8: (DR1495)
4170 // - The specialization shall be more specialized than the primary
4171 // template (14.5.5.2).
4172 checkMoreSpecializedThanPrimary(S, Partial);
4173
4174 // C++ [temp.class.spec]p8: (DR1315)
4175 // - Each template-parameter shall appear at least once in the
4176 // template-id outside a non-deduced context.
4177 // C++1z [temp.class.spec.match]p3 (P0127R2)
4178 // If the template arguments of a partial specialization cannot be
4179 // deduced because of the structure of its template-parameter-list
4180 // and the template-id, the program is ill-formed.
4181 auto *TemplateParams = Partial->getTemplateParameters();
4182 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4183 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4184 TemplateParams->getDepth(), DeducibleParams);
4185
4186 if (!DeducibleParams.all()) {
4187 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4188 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4189 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4190 << (NumNonDeducible > 1)
4191 << SourceRange(Partial->getLocation(),
4192 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4193 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4194 }
4195}
4196
4197void Sema::CheckTemplatePartialSpecialization(
4198 ClassTemplatePartialSpecializationDecl *Partial) {
4199 checkTemplatePartialSpecialization(S&: *this, Partial);
4200}
4201
4202void Sema::CheckTemplatePartialSpecialization(
4203 VarTemplatePartialSpecializationDecl *Partial) {
4204 checkTemplatePartialSpecialization(S&: *this, Partial);
4205}
4206
4207void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4208 // C++1z [temp.param]p11:
4209 // A template parameter of a deduction guide template that does not have a
4210 // default-argument shall be deducible from the parameter-type-list of the
4211 // deduction guide template.
4212 auto *TemplateParams = TD->getTemplateParameters();
4213 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4214 MarkDeducedTemplateParameters(FunctionTemplate: TD, Deduced&: DeducibleParams);
4215 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4216 // A parameter pack is deducible (to an empty pack).
4217 auto *Param = TemplateParams->getParam(I);
4218 if (Param->isParameterPack() || hasVisibleDefaultArgument(D: Param))
4219 DeducibleParams[I] = true;
4220 }
4221
4222 if (!DeducibleParams.all()) {
4223 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4224 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4225 << (NumNonDeducible > 1);
4226 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4227 }
4228}
4229
4230DeclResult Sema::ActOnVarTemplateSpecialization(
4231 Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous,
4232 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4233 StorageClass SC, bool IsPartialSpecialization) {
4234 // D must be variable template id.
4235 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4236 "Variable template specialization is declared with a template id.");
4237
4238 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4239 TemplateArgumentListInfo TemplateArgs =
4240 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TemplateId);
4241 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4242 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4243 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4244
4245 TemplateName Name = TemplateId->Template.get();
4246
4247 // The template-id must name a variable template.
4248 VarTemplateDecl *VarTemplate =
4249 dyn_cast_or_null<VarTemplateDecl>(Val: Name.getAsTemplateDecl());
4250 if (!VarTemplate) {
4251 NamedDecl *FnTemplate;
4252 if (auto *OTS = Name.getAsOverloadedTemplate())
4253 FnTemplate = *OTS->begin();
4254 else
4255 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Val: Name.getAsTemplateDecl());
4256 if (FnTemplate)
4257 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4258 << FnTemplate->getDeclName();
4259 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4260 << IsPartialSpecialization;
4261 }
4262
4263 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4264 auto Message = DSA->getMessage();
4265 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4266 << VarTemplate << !Message.empty() << Message;
4267 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4268 }
4269
4270 // Check for unexpanded parameter packs in any of the template arguments.
4271 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4272 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
4273 UPPC: IsPartialSpecialization
4274 ? UPPC_PartialSpecialization
4275 : UPPC_ExplicitSpecialization))
4276 return true;
4277
4278 // Check that the template argument list is well-formed for this
4279 // template.
4280 CheckTemplateArgumentInfo CTAI;
4281 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4282 /*DefaultArgs=*/{},
4283 /*PartialTemplateArgs=*/false, CTAI,
4284 /*UpdateArgsWithConversions=*/true))
4285 return true;
4286
4287 // Find the variable template (partial) specialization declaration that
4288 // corresponds to these arguments.
4289 if (IsPartialSpecialization) {
4290 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4291 TemplateArgs.size(),
4292 CTAI.CanonicalConverted))
4293 return true;
4294
4295 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4296 // we also do them during instantiation.
4297 if (!Name.isDependent() &&
4298 !TemplateSpecializationType::anyDependentTemplateArguments(
4299 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4300 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4301 << VarTemplate->getDeclName();
4302 IsPartialSpecialization = false;
4303 }
4304
4305 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4306 CTAI.CanonicalConverted) &&
4307 (!Context.getLangOpts().CPlusPlus20 ||
4308 !TemplateParams->hasAssociatedConstraints())) {
4309 // C++ [temp.class.spec]p9b3:
4310 //
4311 // -- The argument list of the specialization shall not be identical
4312 // to the implicit argument list of the primary template.
4313 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4314 << /*variable template*/ 1
4315 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4316 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4317 // FIXME: Recover from this by treating the declaration as a
4318 // redeclaration of the primary template.
4319 return true;
4320 }
4321 }
4322
4323 void *InsertPos = nullptr;
4324 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4325
4326 if (IsPartialSpecialization)
4327 PrevDecl = VarTemplate->findPartialSpecialization(
4328 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
4329 else
4330 PrevDecl =
4331 VarTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
4332
4333 VarTemplateSpecializationDecl *Specialization = nullptr;
4334
4335 // Check whether we can declare a variable template specialization in
4336 // the current scope.
4337 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4338 TemplateNameLoc,
4339 IsPartialSpecialization))
4340 return true;
4341
4342 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4343 // Since the only prior variable template specialization with these
4344 // arguments was referenced but not declared, reuse that
4345 // declaration node as our own, updating its source location and
4346 // the list of outer template parameters to reflect our new declaration.
4347 Specialization = PrevDecl;
4348 Specialization->setLocation(TemplateNameLoc);
4349 PrevDecl = nullptr;
4350 } else if (IsPartialSpecialization) {
4351 // Create a new class template partial specialization declaration node.
4352 VarTemplatePartialSpecializationDecl *PrevPartial =
4353 cast_or_null<VarTemplatePartialSpecializationDecl>(Val: PrevDecl);
4354 VarTemplatePartialSpecializationDecl *Partial =
4355 VarTemplatePartialSpecializationDecl::Create(
4356 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc,
4357 IdLoc: TemplateNameLoc, Params: TemplateParams, SpecializedTemplate: VarTemplate, T: DI->getType(), TInfo: DI, S: SC,
4358 Args: CTAI.CanonicalConverted);
4359 Partial->setTemplateArgsAsWritten(TemplateArgs);
4360
4361 if (!PrevPartial)
4362 VarTemplate->AddPartialSpecialization(D: Partial, InsertPos);
4363 Specialization = Partial;
4364
4365 // If we are providing an explicit specialization of a member variable
4366 // template specialization, make a note of that.
4367 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4368 PrevPartial->setMemberSpecialization();
4369
4370 CheckTemplatePartialSpecialization(Partial);
4371 } else {
4372 // Create a new class template specialization declaration node for
4373 // this explicit specialization or friend declaration.
4374 Specialization = VarTemplateSpecializationDecl::Create(
4375 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc, IdLoc: TemplateNameLoc,
4376 SpecializedTemplate: VarTemplate, T: DI->getType(), TInfo: DI, S: SC, Args: CTAI.CanonicalConverted);
4377 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4378
4379 if (!PrevDecl)
4380 VarTemplate->AddSpecialization(D: Specialization, InsertPos);
4381 }
4382
4383 // C++ [temp.expl.spec]p6:
4384 // If a template, a member template or the member of a class template is
4385 // explicitly specialized then that specialization shall be declared
4386 // before the first use of that specialization that would cause an implicit
4387 // instantiation to take place, in every translation unit in which such a
4388 // use occurs; no diagnostic is required.
4389 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4390 bool Okay = false;
4391 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4392 // Is there any previous explicit specialization declaration?
4393 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
4394 Okay = true;
4395 break;
4396 }
4397 }
4398
4399 if (!Okay) {
4400 SourceRange Range(TemplateNameLoc, RAngleLoc);
4401 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4402 << Name << Range;
4403
4404 Diag(PrevDecl->getPointOfInstantiation(),
4405 diag::note_instantiation_required_here)
4406 << (PrevDecl->getTemplateSpecializationKind() !=
4407 TSK_ImplicitInstantiation);
4408 return true;
4409 }
4410 }
4411
4412 Specialization->setLexicalDeclContext(CurContext);
4413
4414 // Add the specialization into its lexical context, so that it can
4415 // be seen when iterating through the list of declarations in that
4416 // context. However, specializations are not found by name lookup.
4417 CurContext->addDecl(Specialization);
4418
4419 // Note that this is an explicit specialization.
4420 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4421
4422 Previous.clear();
4423 if (PrevDecl)
4424 Previous.addDecl(PrevDecl);
4425 else if (Specialization->isStaticDataMember() &&
4426 Specialization->isOutOfLine())
4427 Specialization->setAccess(VarTemplate->getAccess());
4428
4429 return Specialization;
4430}
4431
4432namespace {
4433/// A partial specialization whose template arguments have matched
4434/// a given template-id.
4435struct PartialSpecMatchResult {
4436 VarTemplatePartialSpecializationDecl *Partial;
4437 TemplateArgumentList *Args;
4438};
4439
4440// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4441// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4442static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4443 if (Var->getName() != "format_kind" ||
4444 !Var->getDeclContext()->isStdNamespace())
4445 return false;
4446
4447 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4448 // release in which users can access std::format_kind.
4449 // We can use 20250520 as the final date, see the following commits.
4450 // GCC releases/gcc-15 branch:
4451 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4452 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4453 // GCC master branch:
4454 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4455 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4456 return PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2025'05'20);
4457}
4458} // end anonymous namespace
4459
4460DeclResult
4461Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4462 SourceLocation TemplateNameLoc,
4463 const TemplateArgumentListInfo &TemplateArgs) {
4464 assert(Template && "A variable template id without template?");
4465
4466 // Check that the template argument list is well-formed for this template.
4467 CheckTemplateArgumentInfo CTAI;
4468 if (CheckTemplateArgumentList(
4469 Template, TemplateNameLoc,
4470 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4471 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4472 /*UpdateArgsWithConversions=*/true))
4473 return true;
4474
4475 // Produce a placeholder value if the specialization is dependent.
4476 if (Template->getDeclContext()->isDependentContext() ||
4477 TemplateSpecializationType::anyDependentTemplateArguments(
4478 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4479 if (ParsingInitForAutoVars.empty())
4480 return DeclResult();
4481
4482 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4483 const TemplateArgument &Arg2) {
4484 return Context.isSameTemplateArgument(Arg1, Arg2);
4485 };
4486
4487 if (VarDecl *Var = Template->getTemplatedDecl();
4488 ParsingInitForAutoVars.count(Var) &&
4489 // See comments on this function definition
4490 !IsLibstdcxxStdFormatKind(PP, Var) &&
4491 llvm::equal(
4492 CTAI.CanonicalConverted,
4493 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4494 IsSameTemplateArg)) {
4495 Diag(TemplateNameLoc,
4496 diag::err_auto_variable_cannot_appear_in_own_initializer)
4497 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4498 return true;
4499 }
4500
4501 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4502 Template->getPartialSpecializations(PS&: PartialSpecs);
4503 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4504 if (ParsingInitForAutoVars.count(Partial) &&
4505 llvm::equal(CTAI.CanonicalConverted,
4506 Partial->getTemplateArgs().asArray(),
4507 IsSameTemplateArg)) {
4508 Diag(TemplateNameLoc,
4509 diag::err_auto_variable_cannot_appear_in_own_initializer)
4510 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4511 << Partial->getType();
4512 return true;
4513 }
4514
4515 return DeclResult();
4516 }
4517
4518 // Find the variable template specialization declaration that
4519 // corresponds to these arguments.
4520 void *InsertPos = nullptr;
4521 if (VarTemplateSpecializationDecl *Spec =
4522 Template->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos)) {
4523 checkSpecializationReachability(TemplateNameLoc, Spec);
4524 if (Spec->getType()->isUndeducedType()) {
4525 if (ParsingInitForAutoVars.count(Spec))
4526 Diag(TemplateNameLoc,
4527 diag::err_auto_variable_cannot_appear_in_own_initializer)
4528 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4529 << Spec->getType();
4530 else
4531 // We are substituting the initializer of this variable template
4532 // specialization.
4533 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4534 << Spec << Spec->getType();
4535
4536 return true;
4537 }
4538 // If we already have a variable template specialization, return it.
4539 return Spec;
4540 }
4541
4542 // This is the first time we have referenced this variable template
4543 // specialization. Create the canonical declaration and add it to
4544 // the set of specializations, based on the closest partial specialization
4545 // that it represents. That is,
4546 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4547 const TemplateArgumentList *PartialSpecArgs = nullptr;
4548 bool AmbiguousPartialSpec = false;
4549 typedef PartialSpecMatchResult MatchResult;
4550 SmallVector<MatchResult, 4> Matched;
4551 SourceLocation PointOfInstantiation = TemplateNameLoc;
4552 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4553 /*ForTakingAddress=*/false);
4554
4555 // 1. Attempt to find the closest partial specialization that this
4556 // specializes, if any.
4557 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4558 // Perhaps better after unification of DeduceTemplateArguments() and
4559 // getMoreSpecializedPartialSpecialization().
4560 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4561 Template->getPartialSpecializations(PS&: PartialSpecs);
4562
4563 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4564 // C++ [temp.spec.partial.member]p2:
4565 // If the primary member template is explicitly specialized for a given
4566 // (implicit) specialization of the enclosing class template, the partial
4567 // specializations of the member template are ignored for this
4568 // specialization of the enclosing class template. If a partial
4569 // specialization of the member template is explicitly specialized for a
4570 // given (implicit) specialization of the enclosing class template, the
4571 // primary member template and its other partial specializations are still
4572 // considered for this specialization of the enclosing class template.
4573 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4574 !Partial->getMostRecentDecl()->isMemberSpecialization())
4575 continue;
4576
4577 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4578
4579 if (TemplateDeductionResult Result =
4580 DeduceTemplateArguments(Partial, TemplateArgs: CTAI.SugaredConverted, Info);
4581 Result != TemplateDeductionResult::Success) {
4582 // Store the failed-deduction information for use in diagnostics, later.
4583 // TODO: Actually use the failed-deduction info?
4584 FailedCandidates.addCandidate().set(
4585 Found: DeclAccessPair::make(Template, AS_public), Spec: Partial,
4586 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
4587 (void)Result;
4588 } else {
4589 Matched.push_back(Elt: PartialSpecMatchResult());
4590 Matched.back().Partial = Partial;
4591 Matched.back().Args = Info.takeSugared();
4592 }
4593 }
4594
4595 if (Matched.size() >= 1) {
4596 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4597 if (Matched.size() == 1) {
4598 // -- If exactly one matching specialization is found, the
4599 // instantiation is generated from that specialization.
4600 // We don't need to do anything for this.
4601 } else {
4602 // -- If more than one matching specialization is found, the
4603 // partial order rules (14.5.4.2) are used to determine
4604 // whether one of the specializations is more specialized
4605 // than the others. If none of the specializations is more
4606 // specialized than all of the other matching
4607 // specializations, then the use of the variable template is
4608 // ambiguous and the program is ill-formed.
4609 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4610 PEnd = Matched.end();
4611 P != PEnd; ++P) {
4612 if (getMoreSpecializedPartialSpecialization(PS1: P->Partial, PS2: Best->Partial,
4613 Loc: PointOfInstantiation) ==
4614 P->Partial)
4615 Best = P;
4616 }
4617
4618 // Determine if the best partial specialization is more specialized than
4619 // the others.
4620 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4621 PEnd = Matched.end();
4622 P != PEnd; ++P) {
4623 if (P != Best && getMoreSpecializedPartialSpecialization(
4624 PS1: P->Partial, PS2: Best->Partial,
4625 Loc: PointOfInstantiation) != Best->Partial) {
4626 AmbiguousPartialSpec = true;
4627 break;
4628 }
4629 }
4630 }
4631
4632 // Instantiate using the best variable template partial specialization.
4633 InstantiationPattern = Best->Partial;
4634 PartialSpecArgs = Best->Args;
4635 } else {
4636 // -- If no match is found, the instantiation is generated
4637 // from the primary template.
4638 // InstantiationPattern = Template->getTemplatedDecl();
4639 }
4640
4641 // 2. Create the canonical declaration.
4642 // Note that we do not instantiate a definition until we see an odr-use
4643 // in DoMarkVarDeclReferenced().
4644 // FIXME: LateAttrs et al.?
4645 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4646 VarTemplate: Template, FromVar: InstantiationPattern, PartialSpecArgs, TemplateArgsInfo: TemplateArgs,
4647 Converted&: CTAI.CanonicalConverted, PointOfInstantiation: TemplateNameLoc /*, LateAttrs, StartingScope*/);
4648 if (!Decl)
4649 return true;
4650
4651 if (AmbiguousPartialSpec) {
4652 // Partial ordering did not produce a clear winner. Complain.
4653 Decl->setInvalidDecl();
4654 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4655 << Decl;
4656
4657 // Print the matching partial specializations.
4658 for (MatchResult P : Matched)
4659 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4660 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4661 *P.Args);
4662 return true;
4663 }
4664
4665 if (VarTemplatePartialSpecializationDecl *D =
4666 dyn_cast<VarTemplatePartialSpecializationDecl>(Val: InstantiationPattern))
4667 Decl->setInstantiationOf(PartialSpec: D, TemplateArgs: PartialSpecArgs);
4668
4669 checkSpecializationReachability(TemplateNameLoc, Decl);
4670
4671 assert(Decl && "No variable template specialization?");
4672 return Decl;
4673}
4674
4675ExprResult Sema::CheckVarTemplateId(
4676 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4677 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4678 const TemplateArgumentListInfo *TemplateArgs) {
4679
4680 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, TemplateNameLoc: NameInfo.getLoc(),
4681 TemplateArgs: *TemplateArgs);
4682 if (Decl.isInvalid())
4683 return ExprError();
4684
4685 if (!Decl.get())
4686 return ExprResult();
4687
4688 VarDecl *Var = cast<VarDecl>(Val: Decl.get());
4689 if (!Var->getTemplateSpecializationKind())
4690 Var->setTemplateSpecializationKind(TSK: TSK_ImplicitInstantiation,
4691 PointOfInstantiation: NameInfo.getLoc());
4692
4693 // Build an ordinary singleton decl ref.
4694 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4695}
4696
4697void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4698 SourceLocation Loc) {
4699 Diag(Loc, diag::err_template_missing_args)
4700 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4701 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4702 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4703 }
4704}
4705
4706void Sema::diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
4707 bool TemplateKeyword,
4708 TemplateDecl *TD,
4709 SourceLocation Loc) {
4710 TemplateName Name = Context.getQualifiedTemplateName(
4711 NNS: SS.getScopeRep(), TemplateKeyword, Template: TemplateName(TD));
4712 diagnoseMissingTemplateArguments(Name, Loc);
4713}
4714
4715ExprResult
4716Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4717 SourceLocation TemplateKWLoc,
4718 const DeclarationNameInfo &ConceptNameInfo,
4719 NamedDecl *FoundDecl,
4720 ConceptDecl *NamedConcept,
4721 const TemplateArgumentListInfo *TemplateArgs) {
4722 assert(NamedConcept && "A concept template id without a template?");
4723
4724 if (NamedConcept->isInvalidDecl())
4725 return ExprError();
4726
4727 CheckTemplateArgumentInfo CTAI;
4728 if (CheckTemplateArgumentList(
4729 NamedConcept, ConceptNameInfo.getLoc(),
4730 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4731 /*DefaultArgs=*/{},
4732 /*PartialTemplateArgs=*/false, CTAI,
4733 /*UpdateArgsWithConversions=*/false))
4734 return ExprError();
4735
4736 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4737
4738 auto *CSD = ImplicitConceptSpecializationDecl::Create(
4739 C: Context, DC: NamedConcept->getDeclContext(), SL: NamedConcept->getLocation(),
4740 ConvertedArgs: CTAI.CanonicalConverted);
4741 ConstraintSatisfaction Satisfaction;
4742 bool AreArgsDependent =
4743 TemplateSpecializationType::anyDependentTemplateArguments(
4744 *TemplateArgs, Converted: CTAI.CanonicalConverted);
4745 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.CanonicalConverted,
4746 /*Final=*/false);
4747 LocalInstantiationScope Scope(*this);
4748
4749 EnterExpressionEvaluationContext EECtx{
4750 *this, ExpressionEvaluationContext::Unevaluated, CSD};
4751
4752 ContextRAII CurContext(*this, CSD->getDeclContext(),
4753 /*NewThisContext=*/false);
4754 if (!AreArgsDependent &&
4755 CheckConstraintSatisfaction(
4756 NamedConcept, AssociatedConstraint(NamedConcept->getConstraintExpr()),
4757 MLTAL,
4758 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4759 TemplateArgs->getRAngleLoc()),
4760 Satisfaction))
4761 return ExprError();
4762 auto *CL = ConceptReference::Create(
4763 C: Context,
4764 NNS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4765 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4766 ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: *TemplateArgs));
4767 return ConceptSpecializationExpr::Create(
4768 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4769}
4770
4771ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4772 SourceLocation TemplateKWLoc,
4773 LookupResult &R,
4774 bool RequiresADL,
4775 const TemplateArgumentListInfo *TemplateArgs) {
4776 // FIXME: Can we do any checking at this point? I guess we could check the
4777 // template arguments that we have against the template name, if the template
4778 // name refers to a single template. That's not a terribly common case,
4779 // though.
4780 // foo<int> could identify a single function unambiguously
4781 // This approach does NOT work, since f<int>(1);
4782 // gets resolved prior to resorting to overload resolution
4783 // i.e., template<class T> void f(double);
4784 // vs template<class T, class U> void f(U);
4785
4786 // These should be filtered out by our callers.
4787 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4788
4789 // Non-function templates require a template argument list.
4790 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4791 if (!TemplateArgs && !isa<FunctionTemplateDecl>(Val: TD)) {
4792 diagnoseMissingTemplateArguments(
4793 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, Loc: R.getNameLoc());
4794 return ExprError();
4795 }
4796 }
4797 bool KnownDependent = false;
4798 // In C++1y, check variable template ids.
4799 if (R.getAsSingle<VarTemplateDecl>()) {
4800 ExprResult Res = CheckVarTemplateId(
4801 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<VarTemplateDecl>(),
4802 FoundD: R.getRepresentativeDecl(), TemplateLoc: TemplateKWLoc, TemplateArgs);
4803 if (Res.isInvalid() || Res.isUsable())
4804 return Res;
4805 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4806 KnownDependent = true;
4807 }
4808
4809 if (R.getAsSingle<ConceptDecl>()) {
4810 return CheckConceptTemplateId(SS, TemplateKWLoc, ConceptNameInfo: R.getLookupNameInfo(),
4811 FoundDecl: R.getRepresentativeDecl(),
4812 NamedConcept: R.getAsSingle<ConceptDecl>(), TemplateArgs);
4813 }
4814
4815 // We don't want lookup warnings at this point.
4816 R.suppressDiagnostics();
4817
4818 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
4819 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
4820 TemplateKWLoc, NameInfo: R.getLookupNameInfo(), RequiresADL, Args: TemplateArgs,
4821 Begin: R.begin(), End: R.end(), KnownDependent,
4822 /*KnownInstantiationDependent=*/false);
4823
4824 // Model the templates with UnresolvedTemplateTy. The expression should then
4825 // either be transformed in an instantiation or be diagnosed in
4826 // CheckPlaceholderExpr.
4827 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4828 !R.getFoundDecl()->getAsFunction())
4829 ULE->setType(Context.UnresolvedTemplateTy);
4830
4831 return ULE;
4832}
4833
4834ExprResult Sema::BuildQualifiedTemplateIdExpr(
4835 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4836 const DeclarationNameInfo &NameInfo,
4837 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4838 assert(TemplateArgs || TemplateKWLoc.isValid());
4839
4840 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4841 if (LookupTemplateName(Found&: R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4842 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc))
4843 return ExprError();
4844
4845 if (R.isAmbiguous())
4846 return ExprError();
4847
4848 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
4849 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4850
4851 if (R.empty()) {
4852 DeclContext *DC = computeDeclContext(SS);
4853 Diag(NameInfo.getLoc(), diag::err_no_member)
4854 << NameInfo.getName() << DC << SS.getRange();
4855 return ExprError();
4856 }
4857
4858 // If necessary, build an implicit class member access.
4859 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
4860 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
4861 /*S=*/nullptr);
4862
4863 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/RequiresADL: false, TemplateArgs);
4864}
4865
4866TemplateNameKind Sema::ActOnTemplateName(Scope *S,
4867 CXXScopeSpec &SS,
4868 SourceLocation TemplateKWLoc,
4869 const UnqualifiedId &Name,
4870 ParsedType ObjectType,
4871 bool EnteringContext,
4872 TemplateTy &Result,
4873 bool AllowInjectedClassName) {
4874 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4875 Diag(TemplateKWLoc,
4876 getLangOpts().CPlusPlus11 ?
4877 diag::warn_cxx98_compat_template_outside_of_template :
4878 diag::ext_template_outside_of_template)
4879 << FixItHint::CreateRemoval(TemplateKWLoc);
4880
4881 if (SS.isInvalid())
4882 return TNK_Non_template;
4883
4884 // Figure out where isTemplateName is going to look.
4885 DeclContext *LookupCtx = nullptr;
4886 if (SS.isNotEmpty())
4887 LookupCtx = computeDeclContext(SS, EnteringContext);
4888 else if (ObjectType)
4889 LookupCtx = computeDeclContext(T: GetTypeFromParser(Ty: ObjectType));
4890
4891 // C++0x [temp.names]p5:
4892 // If a name prefixed by the keyword template is not the name of
4893 // a template, the program is ill-formed. [Note: the keyword
4894 // template may not be applied to non-template members of class
4895 // templates. -end note ] [ Note: as is the case with the
4896 // typename prefix, the template prefix is allowed in cases
4897 // where it is not strictly necessary; i.e., when the
4898 // nested-name-specifier or the expression on the left of the ->
4899 // or . is not dependent on a template-parameter, or the use
4900 // does not appear in the scope of a template. -end note]
4901 //
4902 // Note: C++03 was more strict here, because it banned the use of
4903 // the "template" keyword prior to a template-name that was not a
4904 // dependent name. C++ DR468 relaxed this requirement (the
4905 // "template" keyword is now permitted). We follow the C++0x
4906 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4907 bool MemberOfUnknownSpecialization;
4908 TemplateNameKind TNK = isTemplateName(S, SS, hasTemplateKeyword: TemplateKWLoc.isValid(), Name,
4909 ObjectTypePtr: ObjectType, EnteringContext, TemplateResult&: Result,
4910 MemberOfUnknownSpecialization);
4911 if (TNK != TNK_Non_template) {
4912 // We resolved this to a (non-dependent) template name. Return it.
4913 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
4914 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
4915 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4916 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4917 // C++14 [class.qual]p2:
4918 // In a lookup in which function names are not ignored and the
4919 // nested-name-specifier nominates a class C, if the name specified
4920 // [...] is the injected-class-name of C, [...] the name is instead
4921 // considered to name the constructor
4922 //
4923 // We don't get here if naming the constructor would be valid, so we
4924 // just reject immediately and recover by treating the
4925 // injected-class-name as naming the template.
4926 Diag(Name.getBeginLoc(),
4927 diag::ext_out_of_line_qualified_id_type_names_constructor)
4928 << Name.Identifier
4929 << 0 /*injected-class-name used as template name*/
4930 << TemplateKWLoc.isValid();
4931 }
4932 return TNK;
4933 }
4934
4935 if (!MemberOfUnknownSpecialization) {
4936 // Didn't find a template name, and the lookup wasn't dependent.
4937 // Do the lookup again to determine if this is a "nothing found" case or
4938 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4939 // need to do this.
4940 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4941 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4942 LookupOrdinaryName);
4943 // Tell LookupTemplateName that we require a template so that it diagnoses
4944 // cases where it finds a non-template.
4945 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4946 ? RequiredTemplateKind(TemplateKWLoc)
4947 : TemplateNameIsRequired;
4948 if (!LookupTemplateName(Found&: R, S, SS, ObjectType: ObjectType.get(), EnteringContext, RequiredTemplate: RTK,
4949 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
4950 !R.isAmbiguous()) {
4951 if (LookupCtx)
4952 Diag(Name.getBeginLoc(), diag::err_no_member)
4953 << DNI.getName() << LookupCtx << SS.getRange();
4954 else
4955 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
4956 << DNI.getName() << SS.getRange();
4957 }
4958 return TNK_Non_template;
4959 }
4960
4961 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4962
4963 switch (Name.getKind()) {
4964 case UnqualifiedIdKind::IK_Identifier:
4965 Result = TemplateTy::make(P: Context.getDependentTemplateName(
4966 Name: {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
4967 return TNK_Dependent_template_name;
4968
4969 case UnqualifiedIdKind::IK_OperatorFunctionId:
4970 Result = TemplateTy::make(P: Context.getDependentTemplateName(
4971 Name: {Qualifier, Name.OperatorFunctionId.Operator,
4972 TemplateKWLoc.isValid()}));
4973 return TNK_Function_template;
4974
4975 case UnqualifiedIdKind::IK_LiteralOperatorId:
4976 // This is a kind of template name, but can never occur in a dependent
4977 // scope (literal operators can only be declared at namespace scope).
4978 break;
4979
4980 default:
4981 break;
4982 }
4983
4984 // This name cannot possibly name a dependent template. Diagnose this now
4985 // rather than building a dependent template name that can never be valid.
4986 Diag(Name.getBeginLoc(),
4987 diag::err_template_kw_refers_to_dependent_non_template)
4988 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4989 << TemplateKWLoc.isValid() << TemplateKWLoc;
4990 return TNK_Non_template;
4991}
4992
4993bool Sema::CheckTemplateTypeArgument(
4994 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
4995 SmallVectorImpl<TemplateArgument> &SugaredConverted,
4996 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
4997 const TemplateArgument &Arg = AL.getArgument();
4998 QualType ArgType;
4999 TypeSourceInfo *TSI = nullptr;
5000
5001 // Check template type parameter.
5002 switch(Arg.getKind()) {
5003 case TemplateArgument::Type:
5004 // C++ [temp.arg.type]p1:
5005 // A template-argument for a template-parameter which is a
5006 // type shall be a type-id.
5007 ArgType = Arg.getAsType();
5008 TSI = AL.getTypeSourceInfo();
5009 break;
5010 case TemplateArgument::Template:
5011 case TemplateArgument::TemplateExpansion: {
5012 // We have a template type parameter but the template argument
5013 // is a template without any arguments.
5014 SourceRange SR = AL.getSourceRange();
5015 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5016 diagnoseMissingTemplateArguments(Name, Loc: SR.getEnd());
5017 return true;
5018 }
5019 case TemplateArgument::Expression: {
5020 // We have a template type parameter but the template argument is an
5021 // expression; see if maybe it is missing the "typename" keyword.
5022 CXXScopeSpec SS;
5023 DeclarationNameInfo NameInfo;
5024
5025 if (DependentScopeDeclRefExpr *ArgExpr =
5026 dyn_cast<DependentScopeDeclRefExpr>(Val: Arg.getAsExpr())) {
5027 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5028 NameInfo = ArgExpr->getNameInfo();
5029 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5030 dyn_cast<CXXDependentScopeMemberExpr>(Val: Arg.getAsExpr())) {
5031 if (ArgExpr->isImplicitAccess()) {
5032 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5033 NameInfo = ArgExpr->getMemberNameInfo();
5034 }
5035 }
5036
5037 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5038 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5039 LookupParsedName(R&: Result, S: CurScope, SS: &SS, /*ObjectType=*/QualType());
5040
5041 if (Result.getAsSingle<TypeDecl>() ||
5042 Result.wasNotFoundInCurrentInstantiation()) {
5043 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5044 // Suggest that the user add 'typename' before the NNS.
5045 SourceLocation Loc = AL.getSourceRange().getBegin();
5046 Diag(Loc, getLangOpts().MSVCCompat
5047 ? diag::ext_ms_template_type_arg_missing_typename
5048 : diag::err_template_arg_must_be_type_suggest)
5049 << FixItHint::CreateInsertion(Loc, "typename ");
5050 NoteTemplateParameterLocation(*Param);
5051
5052 // Recover by synthesizing a type using the location information that we
5053 // already have.
5054 ArgType = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
5055 NNS: SS.getScopeRep(), Name: II);
5056 TypeLocBuilder TLB;
5057 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: ArgType);
5058 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5059 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5060 TL.setNameLoc(NameInfo.getLoc());
5061 TSI = TLB.getTypeSourceInfo(Context, T: ArgType);
5062
5063 // Overwrite our input TemplateArgumentLoc so that we can recover
5064 // properly.
5065 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5066 TemplateArgumentLocInfo(TSI));
5067
5068 break;
5069 }
5070 }
5071 // fallthrough
5072 [[fallthrough]];
5073 }
5074 default: {
5075 // We allow instantiating a template with template argument packs when
5076 // building deduction guides.
5077 if (Arg.getKind() == TemplateArgument::Pack &&
5078 CodeSynthesisContexts.back().Kind ==
5079 Sema::CodeSynthesisContext::BuildingDeductionGuides) {
5080 SugaredConverted.push_back(Elt: Arg);
5081 CanonicalConverted.push_back(Elt: Arg);
5082 return false;
5083 }
5084 // We have a template type parameter but the template argument
5085 // is not a type.
5086 SourceRange SR = AL.getSourceRange();
5087 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5088 NoteTemplateParameterLocation(*Param);
5089
5090 return true;
5091 }
5092 }
5093
5094 if (CheckTemplateArgument(Arg: TSI))
5095 return true;
5096
5097 // Objective-C ARC:
5098 // If an explicitly-specified template argument type is a lifetime type
5099 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5100 if (getLangOpts().ObjCAutoRefCount &&
5101 ArgType->isObjCLifetimeType() &&
5102 !ArgType.getObjCLifetime()) {
5103 Qualifiers Qs;
5104 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5105 ArgType = Context.getQualifiedType(T: ArgType, Qs);
5106 }
5107
5108 SugaredConverted.push_back(Elt: TemplateArgument(ArgType));
5109 CanonicalConverted.push_back(
5110 Elt: TemplateArgument(Context.getCanonicalType(T: ArgType)));
5111 return false;
5112}
5113
5114/// Substitute template arguments into the default template argument for
5115/// the given template type parameter.
5116///
5117/// \param SemaRef the semantic analysis object for which we are performing
5118/// the substitution.
5119///
5120/// \param Template the template that we are synthesizing template arguments
5121/// for.
5122///
5123/// \param TemplateLoc the location of the template name that started the
5124/// template-id we are checking.
5125///
5126/// \param RAngleLoc the location of the right angle bracket ('>') that
5127/// terminates the template-id.
5128///
5129/// \param Param the template template parameter whose default we are
5130/// substituting into.
5131///
5132/// \param Converted the list of template arguments provided for template
5133/// parameters that precede \p Param in the template parameter list.
5134///
5135/// \param Output the resulting substituted template argument.
5136///
5137/// \returns true if an error occurred.
5138static bool SubstDefaultTemplateArgument(
5139 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5140 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5141 ArrayRef<TemplateArgument> SugaredConverted,
5142 ArrayRef<TemplateArgument> CanonicalConverted,
5143 TemplateArgumentLoc &Output) {
5144 Output = Param->getDefaultArgument();
5145
5146 // If the argument type is dependent, instantiate it now based
5147 // on the previously-computed template arguments.
5148 if (Output.getArgument().isInstantiationDependent()) {
5149 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5150 SugaredConverted,
5151 SourceRange(TemplateLoc, RAngleLoc));
5152 if (Inst.isInvalid())
5153 return true;
5154
5155 // Only substitute for the innermost template argument list.
5156 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5157 /*Final=*/true);
5158 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5159 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5160
5161 bool ForLambdaCallOperator = false;
5162 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5163 ForLambdaCallOperator = Rec->isLambda();
5164 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5165 !ForLambdaCallOperator);
5166
5167 if (SemaRef.SubstTemplateArgument(Input: Output, TemplateArgs: TemplateArgLists, Output,
5168 Loc: Param->getDefaultArgumentLoc(),
5169 Entity: Param->getDeclName()))
5170 return true;
5171 }
5172
5173 return false;
5174}
5175
5176/// Substitute template arguments into the default template argument for
5177/// the given non-type template parameter.
5178///
5179/// \param SemaRef the semantic analysis object for which we are performing
5180/// the substitution.
5181///
5182/// \param Template the template that we are synthesizing template arguments
5183/// for.
5184///
5185/// \param TemplateLoc the location of the template name that started the
5186/// template-id we are checking.
5187///
5188/// \param RAngleLoc the location of the right angle bracket ('>') that
5189/// terminates the template-id.
5190///
5191/// \param Param the non-type template parameter whose default we are
5192/// substituting into.
5193///
5194/// \param Converted the list of template arguments provided for template
5195/// parameters that precede \p Param in the template parameter list.
5196///
5197/// \returns the substituted template argument, or NULL if an error occurred.
5198static bool SubstDefaultTemplateArgument(
5199 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5200 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5201 ArrayRef<TemplateArgument> SugaredConverted,
5202 ArrayRef<TemplateArgument> CanonicalConverted,
5203 TemplateArgumentLoc &Output) {
5204 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5205 SugaredConverted,
5206 SourceRange(TemplateLoc, RAngleLoc));
5207 if (Inst.isInvalid())
5208 return true;
5209
5210 // Only substitute for the innermost template argument list.
5211 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5212 /*Final=*/true);
5213 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5214 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5215
5216 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5217 EnterExpressionEvaluationContext ConstantEvaluated(
5218 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5219 return SemaRef.SubstTemplateArgument(Input: Param->getDefaultArgument(),
5220 TemplateArgs: TemplateArgLists, Output);
5221}
5222
5223/// Substitute template arguments into the default template argument for
5224/// the given template template parameter.
5225///
5226/// \param SemaRef the semantic analysis object for which we are performing
5227/// the substitution.
5228///
5229/// \param Template the template that we are synthesizing template arguments
5230/// for.
5231///
5232/// \param TemplateLoc the location of the template name that started the
5233/// template-id we are checking.
5234///
5235/// \param RAngleLoc the location of the right angle bracket ('>') that
5236/// terminates the template-id.
5237///
5238/// \param Param the template template parameter whose default we are
5239/// substituting into.
5240///
5241/// \param Converted the list of template arguments provided for template
5242/// parameters that precede \p Param in the template parameter list.
5243///
5244/// \param QualifierLoc Will be set to the nested-name-specifier (with
5245/// source-location information) that precedes the template name.
5246///
5247/// \returns the substituted template argument, or NULL if an error occurred.
5248static TemplateName SubstDefaultTemplateArgument(
5249 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5250 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
5251 ArrayRef<TemplateArgument> SugaredConverted,
5252 ArrayRef<TemplateArgument> CanonicalConverted,
5253 NestedNameSpecifierLoc &QualifierLoc) {
5254 Sema::InstantiatingTemplate Inst(
5255 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5256 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5257 if (Inst.isInvalid())
5258 return TemplateName();
5259
5260 // Only substitute for the innermost template argument list.
5261 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5262 /*Final=*/true);
5263 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5264 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5265
5266 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5267 // Substitute into the nested-name-specifier first,
5268 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5269 if (QualifierLoc) {
5270 QualifierLoc =
5271 SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc, TemplateArgs: TemplateArgLists);
5272 if (!QualifierLoc)
5273 return TemplateName();
5274 }
5275
5276 return SemaRef.SubstTemplateName(
5277 QualifierLoc,
5278 Name: Param->getDefaultArgument().getArgument().getAsTemplate(),
5279 Loc: Param->getDefaultArgument().getTemplateNameLoc(),
5280 TemplateArgs: TemplateArgLists);
5281}
5282
5283TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5284 TemplateDecl *Template, SourceLocation TemplateLoc,
5285 SourceLocation RAngleLoc, Decl *Param,
5286 ArrayRef<TemplateArgument> SugaredConverted,
5287 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5288 HasDefaultArg = false;
5289
5290 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
5291 if (!hasReachableDefaultArgument(TypeParm))
5292 return TemplateArgumentLoc();
5293
5294 HasDefaultArg = true;
5295 TemplateArgumentLoc Output;
5296 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc, RAngleLoc,
5297 Param: TypeParm, SugaredConverted,
5298 CanonicalConverted, Output))
5299 return TemplateArgumentLoc();
5300 return Output;
5301 }
5302
5303 if (NonTypeTemplateParmDecl *NonTypeParm
5304 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5305 if (!hasReachableDefaultArgument(NonTypeParm))
5306 return TemplateArgumentLoc();
5307
5308 HasDefaultArg = true;
5309 TemplateArgumentLoc Output;
5310 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc, RAngleLoc,
5311 Param: NonTypeParm, SugaredConverted,
5312 CanonicalConverted, Output))
5313 return TemplateArgumentLoc();
5314 return Output;
5315 }
5316
5317 TemplateTemplateParmDecl *TempTempParm
5318 = cast<TemplateTemplateParmDecl>(Val: Param);
5319 if (!hasReachableDefaultArgument(TempTempParm))
5320 return TemplateArgumentLoc();
5321
5322 HasDefaultArg = true;
5323 NestedNameSpecifierLoc QualifierLoc;
5324 TemplateName TName = SubstDefaultTemplateArgument(
5325 SemaRef&: *this, Template, TemplateLoc, RAngleLoc, Param: TempTempParm, SugaredConverted,
5326 CanonicalConverted, QualifierLoc);
5327 if (TName.isNull())
5328 return TemplateArgumentLoc();
5329
5330 return TemplateArgumentLoc(
5331 Context, TemplateArgument(TName),
5332 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
5333 TempTempParm->getDefaultArgument().getTemplateNameLoc());
5334}
5335
5336/// Convert a template-argument that we parsed as a type into a template, if
5337/// possible. C++ permits injected-class-names to perform dual service as
5338/// template template arguments and as template type arguments.
5339static TemplateArgumentLoc
5340convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5341 // Extract and step over any surrounding nested-name-specifier.
5342 NestedNameSpecifierLoc QualLoc;
5343 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5344 if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
5345 return TemplateArgumentLoc();
5346
5347 QualLoc = ETLoc.getQualifierLoc();
5348 TLoc = ETLoc.getNamedTypeLoc();
5349 }
5350 // If this type was written as an injected-class-name, it can be used as a
5351 // template template argument.
5352 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5353 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5354 QualLoc, InjLoc.getNameLoc());
5355
5356 // If this type was written as an injected-class-name, it may have been
5357 // converted to a RecordType during instantiation. If the RecordType is
5358 // *not* wrapped in a TemplateSpecializationType and denotes a class
5359 // template specialization, it must have come from an injected-class-name.
5360 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5361 if (auto *CTSD =
5362 dyn_cast<ClassTemplateSpecializationDecl>(Val: RecLoc.getDecl()))
5363 return TemplateArgumentLoc(Context,
5364 TemplateName(CTSD->getSpecializedTemplate()),
5365 QualLoc, RecLoc.getNameLoc());
5366
5367 return TemplateArgumentLoc();
5368}
5369
5370bool Sema::CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &ArgLoc,
5371 NamedDecl *Template,
5372 SourceLocation TemplateLoc,
5373 SourceLocation RAngleLoc,
5374 unsigned ArgumentPackIndex,
5375 CheckTemplateArgumentInfo &CTAI,
5376 CheckTemplateArgumentKind CTAK) {
5377 // Check template type parameters.
5378 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param))
5379 return CheckTemplateTypeArgument(Param: TTP, AL&: ArgLoc, SugaredConverted&: CTAI.SugaredConverted,
5380 CanonicalConverted&: CTAI.CanonicalConverted);
5381
5382 const TemplateArgument &Arg = ArgLoc.getArgument();
5383 // Check non-type template parameters.
5384 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5385 // Do substitution on the type of the non-type template parameter
5386 // with the template arguments we've seen thus far. But if the
5387 // template has a dependent context then we cannot substitute yet.
5388 QualType NTTPType = NTTP->getType();
5389 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5390 NTTPType = NTTP->getExpansionType(I: ArgumentPackIndex);
5391
5392 if (NTTPType->isInstantiationDependentType() &&
5393 !isa<TemplateTemplateParmDecl>(Val: Template) &&
5394 !Template->getDeclContext()->isDependentContext()) {
5395 // Do substitution on the type of the non-type template parameter.
5396 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5397 CTAI.SugaredConverted,
5398 SourceRange(TemplateLoc, RAngleLoc));
5399 if (Inst.isInvalid())
5400 return true;
5401
5402 MultiLevelTemplateArgumentList MLTAL(Template, CTAI.SugaredConverted,
5403 /*Final=*/true);
5404 // If the parameter is a pack expansion, expand this slice of the pack.
5405 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5406 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5407 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5408 NTTP->getDeclName());
5409 } else {
5410 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5411 NTTP->getDeclName());
5412 }
5413
5414 // If that worked, check the non-type template parameter type
5415 // for validity.
5416 if (!NTTPType.isNull())
5417 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5418 NTTP->getLocation());
5419 if (NTTPType.isNull())
5420 return true;
5421 }
5422
5423 auto checkExpr = [&](Expr *E) -> Expr * {
5424 TemplateArgument SugaredResult, CanonicalResult;
5425 unsigned CurSFINAEErrors = NumSFINAEErrors;
5426 ExprResult Res = CheckTemplateArgument(
5427 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E, SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5428 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5429 // If the current template argument causes an error, give up now.
5430 if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors)
5431 return nullptr;
5432 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5433 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5434 return Res.get();
5435 };
5436
5437 switch (Arg.getKind()) {
5438 case TemplateArgument::Null:
5439 llvm_unreachable("Should never see a NULL template argument here");
5440
5441 case TemplateArgument::Expression: {
5442 Expr *E = Arg.getAsExpr();
5443 Expr *R = checkExpr(E);
5444 if (!R)
5445 return true;
5446 // If the resulting expression is new, then use it in place of the
5447 // old expression in the template argument.
5448 if (R != E) {
5449 TemplateArgument TA(R, /*IsCanonical=*/false);
5450 ArgLoc = TemplateArgumentLoc(TA, R);
5451 }
5452 break;
5453 }
5454
5455 // As for the converted NTTP kinds, they still might need another
5456 // conversion, as the new corresponding parameter might be different.
5457 // Ideally, we would always perform substitution starting with sugared types
5458 // and never need these, as we would still have expressions. Since these are
5459 // needed so rarely, it's probably a better tradeoff to just convert them
5460 // back to expressions.
5461 case TemplateArgument::Integral:
5462 case TemplateArgument::Declaration:
5463 case TemplateArgument::NullPtr:
5464 case TemplateArgument::StructuralValue: {
5465 // FIXME: StructuralValue is untested here.
5466 ExprResult R =
5467 BuildExpressionFromNonTypeTemplateArgument(Arg, Loc: SourceLocation());
5468 assert(R.isUsable());
5469 if (!checkExpr(R.get()))
5470 return true;
5471 break;
5472 }
5473
5474 case TemplateArgument::Template:
5475 case TemplateArgument::TemplateExpansion:
5476 // We were given a template template argument. It may not be ill-formed;
5477 // see below.
5478 if (DependentTemplateName *DTN = Arg.getAsTemplateOrTemplatePattern()
5479 .getAsDependentTemplateName()) {
5480 // We have a template argument such as \c T::template X, which we
5481 // parsed as a template template argument. However, since we now
5482 // know that we need a non-type template argument, convert this
5483 // template name into an expression.
5484
5485 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5486 ArgLoc.getTemplateNameLoc());
5487
5488 CXXScopeSpec SS;
5489 SS.Adopt(Other: ArgLoc.getTemplateQualifierLoc());
5490 // FIXME: the template-template arg was a DependentTemplateName,
5491 // so it was provided with a template keyword. However, its source
5492 // location is not stored in the template argument structure.
5493 SourceLocation TemplateKWLoc;
5494 ExprResult E = DependentScopeDeclRefExpr::Create(
5495 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5496 TemplateArgs: nullptr);
5497
5498 // If we parsed the template argument as a pack expansion, create a
5499 // pack expansion expression.
5500 if (Arg.getKind() == TemplateArgument::TemplateExpansion) {
5501 E = ActOnPackExpansion(Pattern: E.get(), EllipsisLoc: ArgLoc.getTemplateEllipsisLoc());
5502 if (E.isInvalid())
5503 return true;
5504 }
5505
5506 TemplateArgument SugaredResult, CanonicalResult;
5507 E = CheckTemplateArgument(
5508 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E.get(), SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5509 /*StrictCheck=*/CTAI.PartialOrdering, CTAK: CTAK_Specified);
5510 if (E.isInvalid())
5511 return true;
5512
5513 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5514 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5515 break;
5516 }
5517
5518 // We have a template argument that actually does refer to a class
5519 // template, alias template, or template template parameter, and
5520 // therefore cannot be a non-type template argument.
5521 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5522 << ArgLoc.getSourceRange();
5523 NoteTemplateParameterLocation(Decl: *Param);
5524
5525 return true;
5526
5527 case TemplateArgument::Type: {
5528 // We have a non-type template parameter but the template
5529 // argument is a type.
5530
5531 // C++ [temp.arg]p2:
5532 // In a template-argument, an ambiguity between a type-id and
5533 // an expression is resolved to a type-id, regardless of the
5534 // form of the corresponding template-parameter.
5535 //
5536 // We warn specifically about this case, since it can be rather
5537 // confusing for users.
5538 QualType T = Arg.getAsType();
5539 SourceRange SR = ArgLoc.getSourceRange();
5540 if (T->isFunctionType())
5541 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5542 else
5543 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5544 NoteTemplateParameterLocation(Decl: *Param);
5545 return true;
5546 }
5547
5548 case TemplateArgument::Pack:
5549 llvm_unreachable("Caller must expand template argument packs");
5550 }
5551
5552 return false;
5553 }
5554
5555
5556 // Check template template parameters.
5557 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Val: Param);
5558
5559 TemplateParameterList *Params = TempParm->getTemplateParameters();
5560 if (TempParm->isExpandedParameterPack())
5561 Params = TempParm->getExpansionTemplateParameters(I: ArgumentPackIndex);
5562
5563 // Substitute into the template parameter list of the template
5564 // template parameter, since previously-supplied template arguments
5565 // may appear within the template template parameter.
5566 //
5567 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5568 {
5569 // Set up a template instantiation context.
5570 LocalInstantiationScope Scope(*this);
5571 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5572 CTAI.SugaredConverted,
5573 SourceRange(TemplateLoc, RAngleLoc));
5574 if (Inst.isInvalid())
5575 return true;
5576
5577 Params = SubstTemplateParams(
5578 Params, Owner: CurContext,
5579 TemplateArgs: MultiLevelTemplateArgumentList(Template, CTAI.SugaredConverted,
5580 /*Final=*/true),
5581 /*EvaluateConstraints=*/false);
5582 if (!Params)
5583 return true;
5584 }
5585
5586 // C++1z [temp.local]p1: (DR1004)
5587 // When [the injected-class-name] is used [...] as a template-argument for
5588 // a template template-parameter [...] it refers to the class template
5589 // itself.
5590 if (Arg.getKind() == TemplateArgument::Type) {
5591 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5592 Context, TLoc: ArgLoc.getTypeSourceInfo()->getTypeLoc());
5593 if (!ConvertedArg.getArgument().isNull())
5594 ArgLoc = ConvertedArg;
5595 }
5596
5597 switch (Arg.getKind()) {
5598 case TemplateArgument::Null:
5599 llvm_unreachable("Should never see a NULL template argument here");
5600
5601 case TemplateArgument::Template:
5602 case TemplateArgument::TemplateExpansion:
5603 if (CheckTemplateTemplateArgument(Param: TempParm, Params, Arg&: ArgLoc,
5604 PartialOrdering: CTAI.PartialOrdering,
5605 StrictPackMatch: &CTAI.StrictPackMatch))
5606 return true;
5607
5608 CTAI.SugaredConverted.push_back(Elt: Arg);
5609 CTAI.CanonicalConverted.push_back(
5610 Elt: Context.getCanonicalTemplateArgument(Arg));
5611 break;
5612
5613 case TemplateArgument::Expression:
5614 case TemplateArgument::Type:
5615 // We have a template template parameter but the template
5616 // argument does not refer to a template.
5617 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5618 << getLangOpts().CPlusPlus11;
5619 return true;
5620
5621 case TemplateArgument::Declaration:
5622 case TemplateArgument::Integral:
5623 case TemplateArgument::StructuralValue:
5624 case TemplateArgument::NullPtr:
5625 llvm_unreachable("non-type argument with template template parameter");
5626
5627 case TemplateArgument::Pack:
5628 llvm_unreachable("Caller must expand template argument packs");
5629 }
5630
5631 return false;
5632}
5633
5634/// Diagnose a missing template argument.
5635template<typename TemplateParmDecl>
5636static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5637 TemplateDecl *TD,
5638 const TemplateParmDecl *D,
5639 TemplateArgumentListInfo &Args) {
5640 // Dig out the most recent declaration of the template parameter; there may be
5641 // declarations of the template that are more recent than TD.
5642 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5643 ->getTemplateParameters()
5644 ->getParam(D->getIndex()));
5645
5646 // If there's a default argument that's not reachable, diagnose that we're
5647 // missing a module import.
5648 llvm::SmallVector<Module*, 8> Modules;
5649 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, Modules: &Modules)) {
5650 S.diagnoseMissingImport(Loc, cast<NamedDecl>(Val: TD),
5651 D->getDefaultArgumentLoc(), Modules,
5652 Sema::MissingImportKind::DefaultArgument,
5653 /*Recover*/true);
5654 return true;
5655 }
5656
5657 // FIXME: If there's a more recent default argument that *is* visible,
5658 // diagnose that it was declared too late.
5659
5660 TemplateParameterList *Params = TD->getTemplateParameters();
5661
5662 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5663 << /*not enough args*/0
5664 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5665 << TD;
5666 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5667 return true;
5668}
5669
5670/// Check that the given template argument list is well-formed
5671/// for specializing the given template.
5672bool Sema::CheckTemplateArgumentList(
5673 TemplateDecl *Template, SourceLocation TemplateLoc,
5674 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5675 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5676 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5677
5678 if (ConstraintsNotSatisfied)
5679 *ConstraintsNotSatisfied = false;
5680
5681 // Make a copy of the template arguments for processing. Only make the
5682 // changes at the end when successful in matching the arguments to the
5683 // template.
5684 TemplateArgumentListInfo NewArgs = TemplateArgs;
5685
5686 TemplateParameterList *Params = GetTemplateParameterList(TD: Template);
5687
5688 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5689
5690 // C++23 [temp.arg.general]p1:
5691 // [...] The type and form of each template-argument specified in
5692 // a template-id shall match the type and form specified for the
5693 // corresponding parameter declared by the template in its
5694 // template-parameter-list.
5695 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Val: Template);
5696 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5697 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5698 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5699 LocalInstantiationScope InstScope(*this, true);
5700 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5701 ParamEnd = Params->end(),
5702 Param = ParamBegin;
5703 Param != ParamEnd;
5704 /* increment in loop */) {
5705 if (size_t ParamIdx = Param - ParamBegin;
5706 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5707 // All written arguments should have been consumed by this point.
5708 assert(ArgIdx == NumArgs && "bad default argument deduction");
5709 if (ParamIdx == DefaultArgs.StartPos) {
5710 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5711 // Default arguments from a DeducedTemplateName are already converted.
5712 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5713 CTAI.SugaredConverted.push_back(Elt: DefArg);
5714 CTAI.CanonicalConverted.push_back(
5715 Elt: Context.getCanonicalTemplateArgument(Arg: DefArg));
5716 ++Param;
5717 }
5718 continue;
5719 }
5720 }
5721
5722 // If we have an expanded parameter pack, make sure we don't have too
5723 // many arguments.
5724 if (UnsignedOrNone Expansions = getExpandedPackSize(Param: *Param)) {
5725 if (*Expansions == SugaredArgumentPack.size()) {
5726 // We're done with this parameter pack. Pack up its arguments and add
5727 // them to the list.
5728 CTAI.SugaredConverted.push_back(
5729 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
5730 SugaredArgumentPack.clear();
5731
5732 CTAI.CanonicalConverted.push_back(
5733 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
5734 CanonicalArgumentPack.clear();
5735
5736 // This argument is assigned to the next parameter.
5737 ++Param;
5738 continue;
5739 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5740 // Not enough arguments for this parameter pack.
5741 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5742 << /*not enough args*/0
5743 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5744 << Template;
5745 NoteTemplateLocation(*Template, Params->getSourceRange());
5746 return true;
5747 }
5748 }
5749
5750 if (ArgIdx < NumArgs) {
5751 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5752 bool NonPackParameter =
5753 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(Param: *Param);
5754 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5755
5756 if (ArgIsExpansion && CTAI.MatchingTTP) {
5757 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5758 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5759 ++Param) {
5760 TemplateArgument &Arg = Args[Param - First];
5761 Arg = ArgLoc.getArgument();
5762 if (!(*Param)->isTemplateParameterPack() ||
5763 getExpandedPackSize(Param: *Param))
5764 Arg = Arg.getPackExpansionPattern();
5765 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5766 SaveAndRestore _1(CTAI.PartialOrdering, false);
5767 SaveAndRestore _2(CTAI.MatchingTTP, true);
5768 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5769 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5770 CTAK_Specified))
5771 return true;
5772 Arg = NewArgLoc.getArgument();
5773 CTAI.CanonicalConverted.back().setIsDefaulted(
5774 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg, Param: *Param,
5775 Args: CTAI.CanonicalConverted,
5776 Depth: Params->getDepth()));
5777 }
5778 ArgLoc =
5779 TemplateArgumentLoc(TemplateArgument::CreatePackCopy(Context, Args),
5780 ArgLoc.getLocInfo());
5781 } else {
5782 SaveAndRestore _1(CTAI.PartialOrdering, false);
5783 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
5784 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5785 CTAK_Specified))
5786 return true;
5787 CTAI.CanonicalConverted.back().setIsDefaulted(
5788 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg: ArgLoc.getArgument(),
5789 Param: *Param, Args: CTAI.CanonicalConverted,
5790 Depth: Params->getDepth()));
5791 if (ArgIsExpansion && NonPackParameter) {
5792 // CWG1430/CWG2686: we have a pack expansion as an argument to an
5793 // alias template or concept, and it's not part of a parameter pack.
5794 // This can't be canonicalized, so reject it now.
5795 if (isa<TypeAliasTemplateDecl, ConceptDecl>(Val: Template)) {
5796 Diag(ArgLoc.getLocation(),
5797 diag::err_template_expansion_into_fixed_list)
5798 << (isa<ConceptDecl>(Template) ? 1 : 0)
5799 << ArgLoc.getSourceRange();
5800 NoteTemplateParameterLocation(Decl: **Param);
5801 return true;
5802 }
5803 }
5804 }
5805
5806 // We're now done with this argument.
5807 ++ArgIdx;
5808
5809 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
5810 // Directly convert the remaining arguments, because we don't know what
5811 // parameters they'll match up with.
5812
5813 if (!SugaredArgumentPack.empty()) {
5814 // If we were part way through filling in an expanded parameter pack,
5815 // fall back to just producing individual arguments.
5816 CTAI.SugaredConverted.insert(I: CTAI.SugaredConverted.end(),
5817 From: SugaredArgumentPack.begin(),
5818 To: SugaredArgumentPack.end());
5819 SugaredArgumentPack.clear();
5820
5821 CTAI.CanonicalConverted.insert(I: CTAI.CanonicalConverted.end(),
5822 From: CanonicalArgumentPack.begin(),
5823 To: CanonicalArgumentPack.end());
5824 CanonicalArgumentPack.clear();
5825 }
5826
5827 while (ArgIdx < NumArgs) {
5828 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5829 CTAI.SugaredConverted.push_back(Elt: Arg);
5830 CTAI.CanonicalConverted.push_back(
5831 Elt: Context.getCanonicalTemplateArgument(Arg));
5832 ++ArgIdx;
5833 }
5834
5835 return false;
5836 }
5837
5838 if ((*Param)->isTemplateParameterPack()) {
5839 // The template parameter was a template parameter pack, so take the
5840 // deduced argument and place it on the argument pack. Note that we
5841 // stay on the same template parameter so that we can deduce more
5842 // arguments.
5843 SugaredArgumentPack.push_back(Elt: CTAI.SugaredConverted.pop_back_val());
5844 CanonicalArgumentPack.push_back(Elt: CTAI.CanonicalConverted.pop_back_val());
5845 } else {
5846 // Move to the next template parameter.
5847 ++Param;
5848 }
5849 continue;
5850 }
5851
5852 // If we're checking a partial template argument list, we're done.
5853 if (PartialTemplateArgs) {
5854 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
5855 CTAI.SugaredConverted.push_back(
5856 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
5857 CTAI.CanonicalConverted.push_back(
5858 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
5859 }
5860 return false;
5861 }
5862
5863 // If we have a template parameter pack with no more corresponding
5864 // arguments, just break out now and we'll fill in the argument pack below.
5865 if ((*Param)->isTemplateParameterPack()) {
5866 assert(!getExpandedPackSize(*Param) &&
5867 "Should have dealt with this already");
5868
5869 // A non-expanded parameter pack before the end of the parameter list
5870 // only occurs for an ill-formed template parameter list, unless we've
5871 // got a partial argument list for a function template, so just bail out.
5872 if (Param + 1 != ParamEnd) {
5873 assert(
5874 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
5875 "Concept templates must have parameter packs at the end.");
5876 return true;
5877 }
5878
5879 CTAI.SugaredConverted.push_back(
5880 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
5881 SugaredArgumentPack.clear();
5882
5883 CTAI.CanonicalConverted.push_back(
5884 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
5885 CanonicalArgumentPack.clear();
5886
5887 ++Param;
5888 continue;
5889 }
5890
5891 // Check whether we have a default argument.
5892 bool HasDefaultArg;
5893
5894 // Retrieve the default template argument from the template
5895 // parameter. For each kind of template parameter, we substitute the
5896 // template arguments provided thus far and any "outer" template arguments
5897 // (when the template parameter was part of a nested template) into
5898 // the default argument.
5899 TemplateArgumentLoc Arg = SubstDefaultTemplateArgumentIfAvailable(
5900 Template, TemplateLoc, RAngleLoc, *Param, CTAI.SugaredConverted,
5901 CTAI.CanonicalConverted, HasDefaultArg);
5902
5903 if (Arg.getArgument().isNull()) {
5904 if (!HasDefaultArg) {
5905 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *Param))
5906 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: TTP,
5907 Args&: NewArgs);
5908 if (NonTypeTemplateParmDecl *NTTP =
5909 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param))
5910 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: NTTP,
5911 Args&: NewArgs);
5912 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template,
5913 D: cast<TemplateTemplateParmDecl>(Val: *Param),
5914 Args&: NewArgs);
5915 }
5916 return true;
5917 }
5918
5919 // Introduce an instantiation record that describes where we are using
5920 // the default template argument. We're not actually instantiating a
5921 // template here, we just create this object to put a note into the
5922 // context stack.
5923 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
5924 CTAI.SugaredConverted,
5925 SourceRange(TemplateLoc, RAngleLoc));
5926 if (Inst.isInvalid())
5927 return true;
5928
5929 SaveAndRestore _1(CTAI.PartialOrdering, false);
5930 SaveAndRestore _2(CTAI.MatchingTTP, false);
5931 SaveAndRestore _3(CTAI.StrictPackMatch, {});
5932 // Check the default template argument.
5933 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
5934 CTAI, CTAK_Specified))
5935 return true;
5936
5937 CTAI.SugaredConverted.back().setIsDefaulted(true);
5938 CTAI.CanonicalConverted.back().setIsDefaulted(true);
5939
5940 // Core issue 150 (assumed resolution): if this is a template template
5941 // parameter, keep track of the default template arguments from the
5942 // template definition.
5943 if (isTemplateTemplateParameter)
5944 NewArgs.addArgument(Loc: Arg);
5945
5946 // Move to the next template parameter and argument.
5947 ++Param;
5948 ++ArgIdx;
5949 }
5950
5951 // If we're performing a partial argument substitution, allow any trailing
5952 // pack expansions; they might be empty. This can happen even if
5953 // PartialTemplateArgs is false (the list of arguments is complete but
5954 // still dependent).
5955 if (CTAI.MatchingTTP ||
5956 (CurrentInstantiationScope &&
5957 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
5958 while (ArgIdx < NumArgs &&
5959 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
5960 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
5961 CTAI.SugaredConverted.push_back(Elt: Arg);
5962 CTAI.CanonicalConverted.push_back(
5963 Elt: Context.getCanonicalTemplateArgument(Arg));
5964 }
5965 }
5966
5967 // If we have any leftover arguments, then there were too many arguments.
5968 // Complain and fail.
5969 if (ArgIdx < NumArgs) {
5970 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5971 << /*too many args*/1
5972 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5973 << Template
5974 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5975 NoteTemplateLocation(*Template, Params->getSourceRange());
5976 return true;
5977 }
5978
5979 // No problems found with the new argument list, propagate changes back
5980 // to caller.
5981 if (UpdateArgsWithConversions)
5982 TemplateArgs = std::move(NewArgs);
5983
5984 if (!PartialTemplateArgs) {
5985 // Setup the context/ThisScope for the case where we are needing to
5986 // re-instantiate constraints outside of normal instantiation.
5987 DeclContext *NewContext = Template->getDeclContext();
5988
5989 // If this template is in a template, make sure we extract the templated
5990 // decl.
5991 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
5992 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
5993 auto *RD = dyn_cast<CXXRecordDecl>(Val: NewContext);
5994
5995 Qualifiers ThisQuals;
5996 if (const auto *Method =
5997 dyn_cast_or_null<CXXMethodDecl>(Val: Template->getTemplatedDecl()))
5998 ThisQuals = Method->getMethodQualifiers();
5999
6000 ContextRAII Context(*this, NewContext);
6001 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6002
6003 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6004 Template, NewContext, /*Final=*/false, CTAI.CanonicalConverted,
6005 /*RelativeToPrimary=*/true,
6006 /*Pattern=*/nullptr,
6007 /*ForConceptInstantiation=*/true);
6008 if (EnsureTemplateArgumentListConstraints(
6009 Template, TemplateArgs: MLTAL,
6010 TemplateIDRange: SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6011 if (ConstraintsNotSatisfied)
6012 *ConstraintsNotSatisfied = true;
6013 return true;
6014 }
6015 }
6016
6017 return false;
6018}
6019
6020namespace {
6021 class UnnamedLocalNoLinkageFinder
6022 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6023 {
6024 Sema &S;
6025 SourceRange SR;
6026
6027 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6028
6029 public:
6030 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6031
6032 bool Visit(QualType T) {
6033 return T.isNull() ? false : inherited::Visit(T: T.getTypePtr());
6034 }
6035
6036#define TYPE(Class, Parent) \
6037 bool Visit##Class##Type(const Class##Type *);
6038#define ABSTRACT_TYPE(Class, Parent) \
6039 bool Visit##Class##Type(const Class##Type *) { return false; }
6040#define NON_CANONICAL_TYPE(Class, Parent) \
6041 bool Visit##Class##Type(const Class##Type *) { return false; }
6042#include "clang/AST/TypeNodes.inc"
6043
6044 bool VisitTagDecl(const TagDecl *Tag);
6045 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
6046 };
6047} // end anonymous namespace
6048
6049bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6050 return false;
6051}
6052
6053bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6054 return Visit(T: T->getElementType());
6055}
6056
6057bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6058 return Visit(T: T->getPointeeType());
6059}
6060
6061bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6062 const BlockPointerType* T) {
6063 return Visit(T: T->getPointeeType());
6064}
6065
6066bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6067 const LValueReferenceType* T) {
6068 return Visit(T: T->getPointeeType());
6069}
6070
6071bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6072 const RValueReferenceType* T) {
6073 return Visit(T: T->getPointeeType());
6074}
6075
6076bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6077 const MemberPointerType *T) {
6078 if (Visit(T: T->getPointeeType()))
6079 return true;
6080 if (auto *RD = T->getMostRecentCXXRecordDecl())
6081 return VisitTagDecl(RD);
6082 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6083}
6084
6085bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6086 const ConstantArrayType* T) {
6087 return Visit(T: T->getElementType());
6088}
6089
6090bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6091 const IncompleteArrayType* T) {
6092 return Visit(T: T->getElementType());
6093}
6094
6095bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6096 const VariableArrayType* T) {
6097 return Visit(T: T->getElementType());
6098}
6099
6100bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6101 const DependentSizedArrayType* T) {
6102 return Visit(T: T->getElementType());
6103}
6104
6105bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6106 const DependentSizedExtVectorType* T) {
6107 return Visit(T: T->getElementType());
6108}
6109
6110bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6111 const DependentSizedMatrixType *T) {
6112 return Visit(T: T->getElementType());
6113}
6114
6115bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6116 const DependentAddressSpaceType *T) {
6117 return Visit(T: T->getPointeeType());
6118}
6119
6120bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6121 return Visit(T: T->getElementType());
6122}
6123
6124bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6125 const DependentVectorType *T) {
6126 return Visit(T: T->getElementType());
6127}
6128
6129bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6130 return Visit(T: T->getElementType());
6131}
6132
6133bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6134 const ConstantMatrixType *T) {
6135 return Visit(T: T->getElementType());
6136}
6137
6138bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6139 const FunctionProtoType* T) {
6140 for (const auto &A : T->param_types()) {
6141 if (Visit(T: A))
6142 return true;
6143 }
6144
6145 return Visit(T: T->getReturnType());
6146}
6147
6148bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6149 const FunctionNoProtoType* T) {
6150 return Visit(T: T->getReturnType());
6151}
6152
6153bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6154 const UnresolvedUsingType*) {
6155 return false;
6156}
6157
6158bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6159 return false;
6160}
6161
6162bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6163 return Visit(T: T->getUnmodifiedType());
6164}
6165
6166bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6167 return false;
6168}
6169
6170bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6171 const PackIndexingType *) {
6172 return false;
6173}
6174
6175bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6176 const UnaryTransformType*) {
6177 return false;
6178}
6179
6180bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6181 return Visit(T: T->getDeducedType());
6182}
6183
6184bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6185 const DeducedTemplateSpecializationType *T) {
6186 return Visit(T: T->getDeducedType());
6187}
6188
6189bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6190 return VisitTagDecl(T->getDecl());
6191}
6192
6193bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6194 return VisitTagDecl(T->getDecl());
6195}
6196
6197bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6198 const TemplateTypeParmType*) {
6199 return false;
6200}
6201
6202bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6203 const SubstTemplateTypeParmPackType *) {
6204 return false;
6205}
6206
6207bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6208 const TemplateSpecializationType*) {
6209 return false;
6210}
6211
6212bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6213 const InjectedClassNameType* T) {
6214 return VisitTagDecl(T->getDecl());
6215}
6216
6217bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6218 const DependentNameType* T) {
6219 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6220}
6221
6222bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6223 const DependentTemplateSpecializationType* T) {
6224 if (auto *Q = T->getDependentTemplateName().getQualifier())
6225 return VisitNestedNameSpecifier(NNS: Q);
6226
6227 return false;
6228}
6229
6230bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6231 const PackExpansionType* T) {
6232 return Visit(T: T->getPattern());
6233}
6234
6235bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6236 return false;
6237}
6238
6239bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6240 const ObjCInterfaceType *) {
6241 return false;
6242}
6243
6244bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6245 const ObjCObjectPointerType *) {
6246 return false;
6247}
6248
6249bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6250 return Visit(T: T->getValueType());
6251}
6252
6253bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6254 return false;
6255}
6256
6257bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6258 return false;
6259}
6260
6261bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6262 const ArrayParameterType *T) {
6263 return VisitConstantArrayType(T);
6264}
6265
6266bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6267 const DependentBitIntType *T) {
6268 return false;
6269}
6270
6271bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6272 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6273 S.Diag(SR.getBegin(),
6274 S.getLangOpts().CPlusPlus11 ?
6275 diag::warn_cxx98_compat_template_arg_local_type :
6276 diag::ext_template_arg_local_type)
6277 << S.Context.getTypeDeclType(Tag) << SR;
6278 return true;
6279 }
6280
6281 if (!Tag->hasNameForLinkage()) {
6282 S.Diag(SR.getBegin(),
6283 S.getLangOpts().CPlusPlus11 ?
6284 diag::warn_cxx98_compat_template_arg_unnamed_type :
6285 diag::ext_template_arg_unnamed_type) << SR;
6286 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6287 return true;
6288 }
6289
6290 return false;
6291}
6292
6293bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6294 NestedNameSpecifier *NNS) {
6295 assert(NNS);
6296 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS: NNS->getPrefix()))
6297 return true;
6298
6299 switch (NNS->getKind()) {
6300 case NestedNameSpecifier::Identifier:
6301 case NestedNameSpecifier::Namespace:
6302 case NestedNameSpecifier::NamespaceAlias:
6303 case NestedNameSpecifier::Global:
6304 case NestedNameSpecifier::Super:
6305 return false;
6306
6307 case NestedNameSpecifier::TypeSpec:
6308 return Visit(T: QualType(NNS->getAsType(), 0));
6309 }
6310 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6311}
6312
6313bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6314 const HLSLAttributedResourceType *T) {
6315 if (T->hasContainedType() && Visit(T: T->getContainedType()))
6316 return true;
6317 return Visit(T: T->getWrappedType());
6318}
6319
6320bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6321 const HLSLInlineSpirvType *T) {
6322 for (auto &Operand : T->getOperands())
6323 if (Operand.isConstant() && Operand.isLiteral())
6324 if (Visit(T: Operand.getResultType()))
6325 return true;
6326 return false;
6327}
6328
6329bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6330 assert(ArgInfo && "invalid TypeSourceInfo");
6331 QualType Arg = ArgInfo->getType();
6332 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6333 QualType CanonArg = Context.getCanonicalType(T: Arg);
6334
6335 if (CanonArg->isVariablyModifiedType()) {
6336 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6337 } else if (Context.hasSameUnqualifiedType(T1: Arg, T2: Context.OverloadTy)) {
6338 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6339 }
6340
6341 // C++03 [temp.arg.type]p2:
6342 // A local type, a type with no linkage, an unnamed type or a type
6343 // compounded from any of these types shall not be used as a
6344 // template-argument for a template type-parameter.
6345 //
6346 // C++11 allows these, and even in C++03 we allow them as an extension with
6347 // a warning.
6348 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6349 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6350 (void)Finder.Visit(T: CanonArg);
6351 }
6352
6353 return false;
6354}
6355
6356enum NullPointerValueKind {
6357 NPV_NotNullPointer,
6358 NPV_NullPointer,
6359 NPV_Error
6360};
6361
6362/// Determine whether the given template argument is a null pointer
6363/// value of the appropriate type.
6364static NullPointerValueKind
6365isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
6366 QualType ParamType, Expr *Arg,
6367 Decl *Entity = nullptr) {
6368 if (Arg->isValueDependent() || Arg->isTypeDependent())
6369 return NPV_NotNullPointer;
6370
6371 // dllimport'd entities aren't constant but are available inside of template
6372 // arguments.
6373 if (Entity && Entity->hasAttr<DLLImportAttr>())
6374 return NPV_NotNullPointer;
6375
6376 if (!S.isCompleteType(Loc: Arg->getExprLoc(), T: ParamType))
6377 llvm_unreachable(
6378 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6379
6380 if (!S.getLangOpts().CPlusPlus11)
6381 return NPV_NotNullPointer;
6382
6383 // Determine whether we have a constant expression.
6384 ExprResult ArgRV = S.DefaultFunctionArrayConversion(E: Arg);
6385 if (ArgRV.isInvalid())
6386 return NPV_Error;
6387 Arg = ArgRV.get();
6388
6389 Expr::EvalResult EvalResult;
6390 SmallVector<PartialDiagnosticAt, 8> Notes;
6391 EvalResult.Diag = &Notes;
6392 if (!Arg->EvaluateAsRValue(Result&: EvalResult, Ctx: S.Context) ||
6393 EvalResult.HasSideEffects) {
6394 SourceLocation DiagLoc = Arg->getExprLoc();
6395
6396 // If our only note is the usual "invalid subexpression" note, just point
6397 // the caret at its location rather than producing an essentially
6398 // redundant note.
6399 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6400 diag::note_invalid_subexpr_in_const_expr) {
6401 DiagLoc = Notes[0].first;
6402 Notes.clear();
6403 }
6404
6405 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6406 << Arg->getType() << Arg->getSourceRange();
6407 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6408 S.Diag(Notes[I].first, Notes[I].second);
6409
6410 S.NoteTemplateParameterLocation(*Param);
6411 return NPV_Error;
6412 }
6413
6414 // C++11 [temp.arg.nontype]p1:
6415 // - an address constant expression of type std::nullptr_t
6416 if (Arg->getType()->isNullPtrType())
6417 return NPV_NullPointer;
6418
6419 // - a constant expression that evaluates to a null pointer value (4.10); or
6420 // - a constant expression that evaluates to a null member pointer value
6421 // (4.11); or
6422 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6423 (EvalResult.Val.isMemberPointer() &&
6424 !EvalResult.Val.getMemberPointerDecl())) {
6425 // If our expression has an appropriate type, we've succeeded.
6426 bool ObjCLifetimeConversion;
6427 if (S.Context.hasSameUnqualifiedType(T1: Arg->getType(), T2: ParamType) ||
6428 S.IsQualificationConversion(FromType: Arg->getType(), ToType: ParamType, CStyle: false,
6429 ObjCLifetimeConversion))
6430 return NPV_NullPointer;
6431
6432 // The types didn't match, but we know we got a null pointer; complain,
6433 // then recover as if the types were correct.
6434 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6435 << Arg->getType() << ParamType << Arg->getSourceRange();
6436 S.NoteTemplateParameterLocation(*Param);
6437 return NPV_NullPointer;
6438 }
6439
6440 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6441 // We found a pointer that isn't null, but doesn't refer to an object.
6442 // We could just return NPV_NotNullPointer, but we can print a better
6443 // message with the information we have here.
6444 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6445 << EvalResult.Val.getAsString(S.Context, ParamType);
6446 S.NoteTemplateParameterLocation(*Param);
6447 return NPV_Error;
6448 }
6449
6450 // If we don't have a null pointer value, but we do have a NULL pointer
6451 // constant, suggest a cast to the appropriate type.
6452 if (Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_NeverValueDependent)) {
6453 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6454 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6455 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6456 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
6457 ")");
6458 S.NoteTemplateParameterLocation(*Param);
6459 return NPV_NullPointer;
6460 }
6461
6462 // FIXME: If we ever want to support general, address-constant expressions
6463 // as non-type template arguments, we should return the ExprResult here to
6464 // be interpreted by the caller.
6465 return NPV_NotNullPointer;
6466}
6467
6468/// Checks whether the given template argument is compatible with its
6469/// template parameter.
6470static bool CheckTemplateArgumentIsCompatibleWithParameter(
6471 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6472 Expr *Arg, QualType ArgType) {
6473 bool ObjCLifetimeConversion;
6474 if (ParamType->isPointerType() &&
6475 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6476 S.IsQualificationConversion(FromType: ArgType, ToType: ParamType, CStyle: false,
6477 ObjCLifetimeConversion)) {
6478 // For pointer-to-object types, qualification conversions are
6479 // permitted.
6480 } else {
6481 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6482 if (!ParamRef->getPointeeType()->isFunctionType()) {
6483 // C++ [temp.arg.nontype]p5b3:
6484 // For a non-type template-parameter of type reference to
6485 // object, no conversions apply. The type referred to by the
6486 // reference may be more cv-qualified than the (otherwise
6487 // identical) type of the template- argument. The
6488 // template-parameter is bound directly to the
6489 // template-argument, which shall be an lvalue.
6490
6491 // FIXME: Other qualifiers?
6492 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6493 unsigned ArgQuals = ArgType.getCVRQualifiers();
6494
6495 if ((ParamQuals | ArgQuals) != ParamQuals) {
6496 S.Diag(Arg->getBeginLoc(),
6497 diag::err_template_arg_ref_bind_ignores_quals)
6498 << ParamType << Arg->getType() << Arg->getSourceRange();
6499 S.NoteTemplateParameterLocation(*Param);
6500 return true;
6501 }
6502 }
6503 }
6504
6505 // At this point, the template argument refers to an object or
6506 // function with external linkage. We now need to check whether the
6507 // argument and parameter types are compatible.
6508 if (!S.Context.hasSameUnqualifiedType(T1: ArgType,
6509 T2: ParamType.getNonReferenceType())) {
6510 // We can't perform this conversion or binding.
6511 if (ParamType->isReferenceType())
6512 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6513 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6514 else
6515 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6516 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6517 S.NoteTemplateParameterLocation(*Param);
6518 return true;
6519 }
6520 }
6521
6522 return false;
6523}
6524
6525/// Checks whether the given template argument is the address
6526/// of an object or function according to C++ [temp.arg.nontype]p1.
6527static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6528 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6529 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6530 bool Invalid = false;
6531 Expr *Arg = ArgIn;
6532 QualType ArgType = Arg->getType();
6533
6534 bool AddressTaken = false;
6535 SourceLocation AddrOpLoc;
6536 if (S.getLangOpts().MicrosoftExt) {
6537 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6538 // dereference and address-of operators.
6539 Arg = Arg->IgnoreParenCasts();
6540
6541 bool ExtWarnMSTemplateArg = false;
6542 UnaryOperatorKind FirstOpKind;
6543 SourceLocation FirstOpLoc;
6544 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6545 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6546 if (UnOpKind == UO_Deref)
6547 ExtWarnMSTemplateArg = true;
6548 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6549 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6550 if (!AddrOpLoc.isValid()) {
6551 FirstOpKind = UnOpKind;
6552 FirstOpLoc = UnOp->getOperatorLoc();
6553 }
6554 } else
6555 break;
6556 }
6557 if (FirstOpLoc.isValid()) {
6558 if (ExtWarnMSTemplateArg)
6559 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6560 << ArgIn->getSourceRange();
6561
6562 if (FirstOpKind == UO_AddrOf)
6563 AddressTaken = true;
6564 else if (Arg->getType()->isPointerType()) {
6565 // We cannot let pointers get dereferenced here, that is obviously not a
6566 // constant expression.
6567 assert(FirstOpKind == UO_Deref);
6568 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6569 << Arg->getSourceRange();
6570 }
6571 }
6572 } else {
6573 // See through any implicit casts we added to fix the type.
6574 Arg = Arg->IgnoreImpCasts();
6575
6576 // C++ [temp.arg.nontype]p1:
6577 //
6578 // A template-argument for a non-type, non-template
6579 // template-parameter shall be one of: [...]
6580 //
6581 // -- the address of an object or function with external
6582 // linkage, including function templates and function
6583 // template-ids but excluding non-static class members,
6584 // expressed as & id-expression where the & is optional if
6585 // the name refers to a function or array, or if the
6586 // corresponding template-parameter is a reference; or
6587
6588 // In C++98/03 mode, give an extension warning on any extra parentheses.
6589 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6590 bool ExtraParens = false;
6591 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6592 if (!Invalid && !ExtraParens) {
6593 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
6594 << Arg->getSourceRange();
6595 ExtraParens = true;
6596 }
6597
6598 Arg = Parens->getSubExpr();
6599 }
6600
6601 while (SubstNonTypeTemplateParmExpr *subst =
6602 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6603 Arg = subst->getReplacement()->IgnoreImpCasts();
6604
6605 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6606 if (UnOp->getOpcode() == UO_AddrOf) {
6607 Arg = UnOp->getSubExpr();
6608 AddressTaken = true;
6609 AddrOpLoc = UnOp->getOperatorLoc();
6610 }
6611 }
6612
6613 while (SubstNonTypeTemplateParmExpr *subst =
6614 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6615 Arg = subst->getReplacement()->IgnoreImpCasts();
6616 }
6617
6618 ValueDecl *Entity = nullptr;
6619 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg))
6620 Entity = DRE->getDecl();
6621 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Val: Arg))
6622 Entity = CUE->getGuidDecl();
6623
6624 // If our parameter has pointer type, check for a null template value.
6625 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6626 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6627 Entity)) {
6628 case NPV_NullPointer:
6629 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6630 SugaredConverted = TemplateArgument(ParamType,
6631 /*isNullPtr=*/true);
6632 CanonicalConverted =
6633 TemplateArgument(S.Context.getCanonicalType(T: ParamType),
6634 /*isNullPtr=*/true);
6635 return false;
6636
6637 case NPV_Error:
6638 return true;
6639
6640 case NPV_NotNullPointer:
6641 break;
6642 }
6643 }
6644
6645 // Stop checking the precise nature of the argument if it is value dependent,
6646 // it should be checked when instantiated.
6647 if (Arg->isValueDependent()) {
6648 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6649 CanonicalConverted =
6650 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6651 return false;
6652 }
6653
6654 if (!Entity) {
6655 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6656 << Arg->getSourceRange();
6657 S.NoteTemplateParameterLocation(*Param);
6658 return true;
6659 }
6660
6661 // Cannot refer to non-static data members
6662 if (isa<FieldDecl>(Val: Entity) || isa<IndirectFieldDecl>(Val: Entity)) {
6663 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6664 << Entity << Arg->getSourceRange();
6665 S.NoteTemplateParameterLocation(*Param);
6666 return true;
6667 }
6668
6669 // Cannot refer to non-static member functions
6670 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Entity)) {
6671 if (!Method->isStatic()) {
6672 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6673 << Method << Arg->getSourceRange();
6674 S.NoteTemplateParameterLocation(*Param);
6675 return true;
6676 }
6677 }
6678
6679 FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Entity);
6680 VarDecl *Var = dyn_cast<VarDecl>(Val: Entity);
6681 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Val: Entity);
6682
6683 // A non-type template argument must refer to an object or function.
6684 if (!Func && !Var && !Guid) {
6685 // We found something, but we don't know specifically what it is.
6686 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6687 << Arg->getSourceRange();
6688 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6689 return true;
6690 }
6691
6692 // Address / reference template args must have external linkage in C++98.
6693 if (Entity->getFormalLinkage() == Linkage::Internal) {
6694 S.Diag(Arg->getBeginLoc(),
6695 S.getLangOpts().CPlusPlus11
6696 ? diag::warn_cxx98_compat_template_arg_object_internal
6697 : diag::ext_template_arg_object_internal)
6698 << !Func << Entity << Arg->getSourceRange();
6699 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6700 << !Func;
6701 } else if (!Entity->hasLinkage()) {
6702 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6703 << !Func << Entity << Arg->getSourceRange();
6704 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6705 << !Func;
6706 return true;
6707 }
6708
6709 if (Var) {
6710 // A value of reference type is not an object.
6711 if (Var->getType()->isReferenceType()) {
6712 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6713 << Var->getType() << Arg->getSourceRange();
6714 S.NoteTemplateParameterLocation(*Param);
6715 return true;
6716 }
6717
6718 // A template argument must have static storage duration.
6719 if (Var->getTLSKind()) {
6720 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6721 << Arg->getSourceRange();
6722 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6723 return true;
6724 }
6725 }
6726
6727 if (AddressTaken && ParamType->isReferenceType()) {
6728 // If we originally had an address-of operator, but the
6729 // parameter has reference type, complain and (if things look
6730 // like they will work) drop the address-of operator.
6731 if (!S.Context.hasSameUnqualifiedType(T1: Entity->getType(),
6732 T2: ParamType.getNonReferenceType())) {
6733 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6734 << ParamType;
6735 S.NoteTemplateParameterLocation(*Param);
6736 return true;
6737 }
6738
6739 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6740 << ParamType
6741 << FixItHint::CreateRemoval(AddrOpLoc);
6742 S.NoteTemplateParameterLocation(*Param);
6743
6744 ArgType = Entity->getType();
6745 }
6746
6747 // If the template parameter has pointer type, either we must have taken the
6748 // address or the argument must decay to a pointer.
6749 if (!AddressTaken && ParamType->isPointerType()) {
6750 if (Func) {
6751 // Function-to-pointer decay.
6752 ArgType = S.Context.getPointerType(Func->getType());
6753 } else if (Entity->getType()->isArrayType()) {
6754 // Array-to-pointer decay.
6755 ArgType = S.Context.getArrayDecayedType(T: Entity->getType());
6756 } else {
6757 // If the template parameter has pointer type but the address of
6758 // this object was not taken, complain and (possibly) recover by
6759 // taking the address of the entity.
6760 ArgType = S.Context.getPointerType(T: Entity->getType());
6761 if (!S.Context.hasSameUnqualifiedType(T1: ArgType, T2: ParamType)) {
6762 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6763 << ParamType;
6764 S.NoteTemplateParameterLocation(*Param);
6765 return true;
6766 }
6767
6768 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6769 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6770
6771 S.NoteTemplateParameterLocation(*Param);
6772 }
6773 }
6774
6775 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6776 Arg, ArgType))
6777 return true;
6778
6779 // Create the template argument.
6780 SugaredConverted = TemplateArgument(Entity, ParamType);
6781 CanonicalConverted =
6782 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
6783 S.Context.getCanonicalType(T: ParamType));
6784 S.MarkAnyDeclReferenced(Loc: Arg->getBeginLoc(), D: Entity, MightBeOdrUse: false);
6785 return false;
6786}
6787
6788/// Checks whether the given template argument is a pointer to
6789/// member constant according to C++ [temp.arg.nontype]p1.
6790static bool
6791CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param,
6792 QualType ParamType, Expr *&ResultArg,
6793 TemplateArgument &SugaredConverted,
6794 TemplateArgument &CanonicalConverted) {
6795 bool Invalid = false;
6796
6797 Expr *Arg = ResultArg;
6798 bool ObjCLifetimeConversion;
6799
6800 // C++ [temp.arg.nontype]p1:
6801 //
6802 // A template-argument for a non-type, non-template
6803 // template-parameter shall be one of: [...]
6804 //
6805 // -- a pointer to member expressed as described in 5.3.1.
6806 DeclRefExpr *DRE = nullptr;
6807
6808 // In C++98/03 mode, give an extension warning on any extra parentheses.
6809 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6810 bool ExtraParens = false;
6811 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6812 if (!Invalid && !ExtraParens) {
6813 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
6814 << Arg->getSourceRange();
6815 ExtraParens = true;
6816 }
6817
6818 Arg = Parens->getSubExpr();
6819 }
6820
6821 while (SubstNonTypeTemplateParmExpr *subst =
6822 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6823 Arg = subst->getReplacement()->IgnoreImpCasts();
6824
6825 // A pointer-to-member constant written &Class::member.
6826 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6827 if (UnOp->getOpcode() == UO_AddrOf) {
6828 DRE = dyn_cast<DeclRefExpr>(Val: UnOp->getSubExpr());
6829 if (DRE && !DRE->getQualifier())
6830 DRE = nullptr;
6831 }
6832 }
6833 // A constant of pointer-to-member type.
6834 else if ((DRE = dyn_cast<DeclRefExpr>(Val: Arg))) {
6835 ValueDecl *VD = DRE->getDecl();
6836 if (VD->getType()->isMemberPointerType()) {
6837 if (isa<NonTypeTemplateParmDecl>(Val: VD)) {
6838 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6839 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
6840 CanonicalConverted =
6841 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6842 } else {
6843 SugaredConverted = TemplateArgument(VD, ParamType);
6844 CanonicalConverted =
6845 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
6846 S.Context.getCanonicalType(T: ParamType));
6847 }
6848 return Invalid;
6849 }
6850 }
6851
6852 DRE = nullptr;
6853 }
6854
6855 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6856
6857 // Check for a null pointer value.
6858 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6859 Entity)) {
6860 case NPV_Error:
6861 return true;
6862 case NPV_NullPointer:
6863 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6864 SugaredConverted = TemplateArgument(ParamType,
6865 /*isNullPtr*/ true);
6866 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(T: ParamType),
6867 /*isNullPtr*/ true);
6868 return false;
6869 case NPV_NotNullPointer:
6870 break;
6871 }
6872
6873 if (S.IsQualificationConversion(FromType: ResultArg->getType(),
6874 ToType: ParamType.getNonReferenceType(), CStyle: false,
6875 ObjCLifetimeConversion)) {
6876 ResultArg = S.ImpCastExprToType(E: ResultArg, Type: ParamType, CK: CK_NoOp,
6877 VK: ResultArg->getValueKind())
6878 .get();
6879 } else if (!S.Context.hasSameUnqualifiedType(
6880 T1: ResultArg->getType(), T2: ParamType.getNonReferenceType())) {
6881 // We can't perform this conversion.
6882 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6883 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6884 S.NoteTemplateParameterLocation(*Param);
6885 return true;
6886 }
6887
6888 if (!DRE)
6889 return S.Diag(Arg->getBeginLoc(),
6890 diag::err_template_arg_not_pointer_to_member_form)
6891 << Arg->getSourceRange();
6892
6893 if (isa<FieldDecl>(Val: DRE->getDecl()) ||
6894 isa<IndirectFieldDecl>(Val: DRE->getDecl()) ||
6895 isa<CXXMethodDecl>(Val: DRE->getDecl())) {
6896 assert((isa<FieldDecl>(DRE->getDecl()) ||
6897 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6898 cast<CXXMethodDecl>(DRE->getDecl())
6899 ->isImplicitObjectMemberFunction()) &&
6900 "Only non-static member pointers can make it here");
6901
6902 // Okay: this is the address of a non-static member, and therefore
6903 // a member pointer constant.
6904 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6905 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
6906 CanonicalConverted =
6907 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6908 } else {
6909 ValueDecl *D = DRE->getDecl();
6910 SugaredConverted = TemplateArgument(D, ParamType);
6911 CanonicalConverted =
6912 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
6913 S.Context.getCanonicalType(T: ParamType));
6914 }
6915 return Invalid;
6916 }
6917
6918 // We found something else, but we don't know specifically what it is.
6919 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6920 << Arg->getSourceRange();
6921 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6922 return true;
6923}
6924
6925ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6926 QualType ParamType, Expr *Arg,
6927 TemplateArgument &SugaredConverted,
6928 TemplateArgument &CanonicalConverted,
6929 bool StrictCheck,
6930 CheckTemplateArgumentKind CTAK) {
6931 SourceLocation StartLoc = Arg->getBeginLoc();
6932 auto *ArgPE = dyn_cast<PackExpansionExpr>(Val: Arg);
6933 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
6934 auto setDeductionArg = [&](Expr *NewDeductionArg) {
6935 DeductionArg = NewDeductionArg;
6936 if (ArgPE) {
6937 // Recreate a pack expansion if we unwrapped one.
6938 Arg = new (Context) PackExpansionExpr(
6939 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
6940 } else {
6941 Arg = DeductionArg;
6942 }
6943 };
6944
6945 // If the parameter type somehow involves auto, deduce the type now.
6946 DeducedType *DeducedT = ParamType->getContainedDeducedType();
6947 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
6948 // During template argument deduction, we allow 'decltype(auto)' to
6949 // match an arbitrary dependent argument.
6950 // FIXME: The language rules don't say what happens in this case.
6951 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6952 // expression is merely instantiation-dependent; is this enough?
6953 if (DeductionArg->isTypeDependent()) {
6954 auto *AT = dyn_cast<AutoType>(Val: DeducedT);
6955 if (AT && AT->isDecltypeAuto()) {
6956 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
6957 CanonicalConverted = TemplateArgument(
6958 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
6959 return Arg;
6960 }
6961 }
6962
6963 // When checking a deduced template argument, deduce from its type even if
6964 // the type is dependent, in order to check the types of non-type template
6965 // arguments line up properly in partial ordering.
6966 TypeSourceInfo *TSI =
6967 Context.getTrivialTypeSourceInfo(T: ParamType, Loc: Param->getLocation());
6968 if (isa<DeducedTemplateSpecializationType>(Val: DeducedT)) {
6969 InitializedEntity Entity =
6970 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
6971 InitializationKind Kind = InitializationKind::CreateForInit(
6972 Loc: DeductionArg->getBeginLoc(), /*DirectInit*/false, Init: DeductionArg);
6973 Expr *Inits[1] = {DeductionArg};
6974 ParamType =
6975 DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind, Init: Inits);
6976 if (ParamType.isNull())
6977 return ExprError();
6978 } else {
6979 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
6980 Param->getDepth() + 1);
6981 ParamType = QualType();
6982 TemplateDeductionResult Result =
6983 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeductionArg, Result&: ParamType, Info,
6984 /*DependentDeduction=*/true,
6985 // We do not check constraints right now because the
6986 // immediately-declared constraint of the auto type is
6987 // also an associated constraint, and will be checked
6988 // along with the other associated constraints after
6989 // checking the template argument list.
6990 /*IgnoreConstraints=*/true);
6991 if (Result == TemplateDeductionResult::AlreadyDiagnosed) {
6992 if (ParamType.isNull())
6993 return ExprError();
6994 } else if (Result != TemplateDeductionResult::Success) {
6995 Diag(Arg->getExprLoc(),
6996 diag::err_non_type_template_parm_type_deduction_failure)
6997 << Param->getDeclName() << Param->getType() << Arg->getType()
6998 << Arg->getSourceRange();
6999 NoteTemplateParameterLocation(*Param);
7000 return ExprError();
7001 }
7002 }
7003 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7004 // an error. The error message normally references the parameter
7005 // declaration, but here we'll pass the argument location because that's
7006 // where the parameter type is deduced.
7007 ParamType = CheckNonTypeTemplateParameterType(T: ParamType, Loc: Arg->getExprLoc());
7008 if (ParamType.isNull()) {
7009 NoteTemplateParameterLocation(*Param);
7010 return ExprError();
7011 }
7012 }
7013
7014 // We should have already dropped all cv-qualifiers by now.
7015 assert(!ParamType.hasQualifiers() &&
7016 "non-type template parameter type cannot be qualified");
7017
7018 // If either the parameter has a dependent type or the argument is
7019 // type-dependent, there's nothing we can check now.
7020 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7021 // Force the argument to the type of the parameter to maintain invariants.
7022 ExprResult E = ImpCastExprToType(
7023 E: DeductionArg, Type: ParamType.getNonLValueExprType(Context), CK: CK_Dependent,
7024 VK: ParamType->isLValueReferenceType() ? VK_LValue
7025 : ParamType->isRValueReferenceType() ? VK_XValue
7026 : VK_PRValue);
7027 if (E.isInvalid())
7028 return ExprError();
7029 setDeductionArg(E.get());
7030 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7031 CanonicalConverted = TemplateArgument(
7032 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7033 return Arg;
7034 }
7035
7036 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7037 if (CTAK == CTAK_Deduced && !StrictCheck &&
7038 (ParamType->isReferenceType()
7039 ? !Context.hasSameType(T1: ParamType.getNonReferenceType(),
7040 T2: DeductionArg->getType())
7041 : !Context.hasSameUnqualifiedType(T1: ParamType,
7042 T2: DeductionArg->getType()))) {
7043 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7044 // we should actually be checking the type of the template argument in P,
7045 // not the type of the template argument deduced from A, against the
7046 // template parameter type.
7047 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7048 << Arg->getType() << ParamType.getUnqualifiedType();
7049 NoteTemplateParameterLocation(*Param);
7050 return ExprError();
7051 }
7052
7053 // If the argument is a pack expansion, we don't know how many times it would
7054 // expand. If we continue checking the argument, this will make the template
7055 // definition ill-formed if it would be ill-formed for any number of
7056 // expansions during instantiation time. When partial ordering or matching
7057 // template template parameters, this is exactly what we want. Otherwise, the
7058 // normal template rules apply: we accept the template if it would be valid
7059 // for any number of expansions (i.e. none).
7060 if (ArgPE && !StrictCheck) {
7061 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7062 CanonicalConverted = TemplateArgument(
7063 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7064 return Arg;
7065 }
7066
7067 // Avoid making a copy when initializing a template parameter of class type
7068 // from a template parameter object of the same type. This is going beyond
7069 // the standard, but is required for soundness: in
7070 // template<A a> struct X { X *p; X<a> *q; };
7071 // ... we need p and q to have the same type.
7072 //
7073 // Similarly, don't inject a call to a copy constructor when initializing
7074 // from a template parameter of the same type.
7075 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7076 if (ParamType->isRecordType() && isa<DeclRefExpr>(Val: InnerArg) &&
7077 Context.hasSameUnqualifiedType(T1: ParamType, T2: InnerArg->getType())) {
7078 NamedDecl *ND = cast<DeclRefExpr>(Val: InnerArg)->getDecl();
7079 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7080
7081 SugaredConverted = TemplateArgument(TPO, ParamType);
7082 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7083 ParamType.getCanonicalType());
7084 return Arg;
7085 }
7086 if (isa<NonTypeTemplateParmDecl>(Val: ND)) {
7087 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7088 CanonicalConverted =
7089 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7090 return Arg;
7091 }
7092 }
7093
7094 // The initialization of the parameter from the argument is
7095 // a constant-evaluated context.
7096 EnterExpressionEvaluationContext ConstantEvaluated(
7097 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7098
7099 bool IsConvertedConstantExpression = true;
7100 if (isa<InitListExpr>(Val: DeductionArg) || ParamType->isRecordType()) {
7101 InitializationKind Kind = InitializationKind::CreateForInit(
7102 Loc: StartLoc, /*DirectInit=*/false, Init: DeductionArg);
7103 Expr *Inits[1] = {DeductionArg};
7104 InitializedEntity Entity =
7105 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7106 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7107 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Inits);
7108 if (Result.isInvalid() || !Result.get())
7109 return ExprError();
7110 Result = ActOnConstantExpression(Res: Result.get());
7111 if (Result.isInvalid() || !Result.get())
7112 return ExprError();
7113 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7114 /*DiscardedValue=*/false,
7115 /*IsConstexpr=*/true,
7116 /*IsTemplateArgument=*/true)
7117 .get());
7118 IsConvertedConstantExpression = false;
7119 }
7120
7121 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7122 // C++17 [temp.arg.nontype]p1:
7123 // A template-argument for a non-type template parameter shall be
7124 // a converted constant expression of the type of the template-parameter.
7125 APValue Value;
7126 ExprResult ArgResult;
7127 if (IsConvertedConstantExpression) {
7128 ArgResult = BuildConvertedConstantExpression(
7129 DeductionArg, ParamType,
7130 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7131 assert(!ArgResult.isUnset());
7132 if (ArgResult.isInvalid()) {
7133 NoteTemplateParameterLocation(*Param);
7134 return ExprError();
7135 }
7136 } else {
7137 ArgResult = DeductionArg;
7138 }
7139
7140 // For a value-dependent argument, CheckConvertedConstantExpression is
7141 // permitted (and expected) to be unable to determine a value.
7142 if (ArgResult.get()->isValueDependent()) {
7143 setDeductionArg(ArgResult.get());
7144 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7145 CanonicalConverted =
7146 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7147 return Arg;
7148 }
7149
7150 APValue PreNarrowingValue;
7151 ArgResult = EvaluateConvertedConstantExpression(
7152 E: ArgResult.get(), T: ParamType, Value, CCE: CCEKind::TemplateArg, /*RequireInt=*/
7153 false, PreNarrowingValue);
7154 if (ArgResult.isInvalid())
7155 return ExprError();
7156 setDeductionArg(ArgResult.get());
7157
7158 if (Value.isLValue()) {
7159 APValue::LValueBase Base = Value.getLValueBase();
7160 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7161 // For a non-type template-parameter of pointer or reference type,
7162 // the value of the constant expression shall not refer to
7163 assert(ParamType->isPointerOrReferenceType() ||
7164 ParamType->isNullPtrType());
7165 // -- a temporary object
7166 // -- a string literal
7167 // -- the result of a typeid expression, or
7168 // -- a predefined __func__ variable
7169 if (Base &&
7170 (!VD ||
7171 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(Val: VD))) {
7172 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7173 << Arg->getSourceRange();
7174 return ExprError();
7175 }
7176
7177 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7178 VD->getType()->isArrayType() &&
7179 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7180 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7181 if (ArgPE) {
7182 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7183 CanonicalConverted =
7184 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7185 } else {
7186 SugaredConverted = TemplateArgument(VD, ParamType);
7187 CanonicalConverted =
7188 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7189 ParamType.getCanonicalType());
7190 }
7191 return Arg;
7192 }
7193
7194 // -- a subobject [until C++20]
7195 if (!getLangOpts().CPlusPlus20) {
7196 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7197 Value.isLValueOnePastTheEnd()) {
7198 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7199 << Value.getAsString(Context, ParamType);
7200 return ExprError();
7201 }
7202 assert((VD || !ParamType->isReferenceType()) &&
7203 "null reference should not be a constant expression");
7204 assert((!VD || !ParamType->isNullPtrType()) &&
7205 "non-null value of type nullptr_t?");
7206 }
7207 }
7208
7209 if (Value.isAddrLabelDiff())
7210 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7211
7212 if (ArgPE) {
7213 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7214 CanonicalConverted =
7215 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7216 } else {
7217 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7218 CanonicalConverted =
7219 TemplateArgument(Context, ParamType.getCanonicalType(), Value);
7220 }
7221 return Arg;
7222 }
7223
7224 // C++ [temp.arg.nontype]p5:
7225 // The following conversions are performed on each expression used
7226 // as a non-type template-argument. If a non-type
7227 // template-argument cannot be converted to the type of the
7228 // corresponding template-parameter then the program is
7229 // ill-formed.
7230 if (ParamType->isIntegralOrEnumerationType()) {
7231 // C++11:
7232 // -- for a non-type template-parameter of integral or
7233 // enumeration type, conversions permitted in a converted
7234 // constant expression are applied.
7235 //
7236 // C++98:
7237 // -- for a non-type template-parameter of integral or
7238 // enumeration type, integral promotions (4.5) and integral
7239 // conversions (4.7) are applied.
7240
7241 if (getLangOpts().CPlusPlus11) {
7242 // C++ [temp.arg.nontype]p1:
7243 // A template-argument for a non-type, non-template template-parameter
7244 // shall be one of:
7245 //
7246 // -- for a non-type template-parameter of integral or enumeration
7247 // type, a converted constant expression of the type of the
7248 // template-parameter; or
7249 llvm::APSInt Value;
7250 ExprResult ArgResult = CheckConvertedConstantExpression(
7251 From: DeductionArg, T: ParamType, Value, CCE: CCEKind::TemplateArg);
7252 if (ArgResult.isInvalid())
7253 return ExprError();
7254 setDeductionArg(ArgResult.get());
7255
7256 // We can't check arbitrary value-dependent arguments.
7257 if (DeductionArg->isValueDependent()) {
7258 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7259 CanonicalConverted =
7260 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7261 return Arg;
7262 }
7263
7264 // Widen the argument value to sizeof(parameter type). This is almost
7265 // always a no-op, except when the parameter type is bool. In
7266 // that case, this may extend the argument from 1 bit to 8 bits.
7267 QualType IntegerType = ParamType;
7268 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
7269 IntegerType = Enum->getDecl()->getIntegerType();
7270 Value = Value.extOrTrunc(width: IntegerType->isBitIntType()
7271 ? Context.getIntWidth(T: IntegerType)
7272 : Context.getTypeSize(T: IntegerType));
7273
7274 if (ArgPE) {
7275 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7276 CanonicalConverted =
7277 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7278 } else {
7279 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7280 CanonicalConverted = TemplateArgument(
7281 Context, Value, Context.getCanonicalType(T: ParamType));
7282 }
7283 return Arg;
7284 }
7285
7286 ExprResult ArgResult = DefaultLvalueConversion(E: Arg);
7287 if (ArgResult.isInvalid())
7288 return ExprError();
7289 DeductionArg = ArgResult.get();
7290
7291 QualType ArgType = DeductionArg->getType();
7292
7293 // C++ [temp.arg.nontype]p1:
7294 // A template-argument for a non-type, non-template
7295 // template-parameter shall be one of:
7296 //
7297 // -- an integral constant-expression of integral or enumeration
7298 // type; or
7299 // -- the name of a non-type template-parameter; or
7300 llvm::APSInt Value;
7301 if (!ArgType->isIntegralOrEnumerationType()) {
7302 Diag(StartLoc, diag::err_template_arg_not_integral_or_enumeral)
7303 << ArgType << DeductionArg->getSourceRange();
7304 NoteTemplateParameterLocation(*Param);
7305 return ExprError();
7306 } else if (!DeductionArg->isValueDependent()) {
7307 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7308 QualType T;
7309
7310 public:
7311 TmplArgICEDiagnoser(QualType T) : T(T) { }
7312
7313 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7314 SourceLocation Loc) override {
7315 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7316 }
7317 } Diagnoser(ArgType);
7318
7319 DeductionArg =
7320 VerifyIntegerConstantExpression(DeductionArg, &Value, Diagnoser)
7321 .get();
7322 if (!DeductionArg)
7323 return ExprError();
7324 }
7325
7326 // From here on out, all we care about is the unqualified form
7327 // of the argument type.
7328 ArgType = ArgType.getUnqualifiedType();
7329
7330 // Try to convert the argument to the parameter's type.
7331 if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
7332 // Okay: no conversion necessary
7333 } else if (ParamType->isBooleanType()) {
7334 // This is an integral-to-boolean conversion.
7335 DeductionArg =
7336 ImpCastExprToType(E: DeductionArg, Type: ParamType, CK: CK_IntegralToBoolean)
7337 .get();
7338 } else if (IsIntegralPromotion(From: Arg, FromType: ArgType, ToType: ParamType) ||
7339 !ParamType->isEnumeralType()) {
7340 // This is an integral promotion or conversion.
7341 DeductionArg =
7342 ImpCastExprToType(E: DeductionArg, Type: ParamType, CK: CK_IntegralCast).get();
7343 } else {
7344 // We can't perform this conversion.
7345 Diag(StartLoc, diag::err_template_arg_not_convertible)
7346 << DeductionArg->getType() << ParamType
7347 << DeductionArg->getSourceRange();
7348 NoteTemplateParameterLocation(*Param);
7349 return ExprError();
7350 }
7351 setDeductionArg(DeductionArg);
7352
7353 // Add the value of this argument to the list of converted
7354 // arguments. We use the bitwidth and signedness of the template
7355 // parameter.
7356 if (DeductionArg->isValueDependent()) {
7357 // The argument is value-dependent. Create a new
7358 // TemplateArgument with the converted expression.
7359 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7360 CanonicalConverted =
7361 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7362 return Arg;
7363 }
7364
7365 QualType IntegerType = ParamType;
7366 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
7367 IntegerType = Enum->getDecl()->getIntegerType();
7368 }
7369
7370 if (ParamType->isBooleanType()) {
7371 // Value must be zero or one.
7372 Value = Value != 0;
7373 unsigned AllowedBits = Context.getTypeSize(T: IntegerType);
7374 if (Value.getBitWidth() != AllowedBits)
7375 Value = Value.extOrTrunc(width: AllowedBits);
7376 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7377 } else {
7378 llvm::APSInt OldValue = Value;
7379
7380 // Coerce the template argument's value to the value it will have
7381 // based on the template parameter's type.
7382 unsigned AllowedBits = IntegerType->isBitIntType()
7383 ? Context.getIntWidth(T: IntegerType)
7384 : Context.getTypeSize(T: IntegerType);
7385 if (Value.getBitWidth() != AllowedBits)
7386 Value = Value.extOrTrunc(width: AllowedBits);
7387 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7388
7389 // Complain if an unsigned parameter received a negative value.
7390 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7391 (OldValue.isSigned() && OldValue.isNegative())) {
7392 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7393 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7394 << Arg->getSourceRange();
7395 NoteTemplateParameterLocation(*Param);
7396 }
7397
7398 // Complain if we overflowed the template parameter's type.
7399 unsigned RequiredBits;
7400 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7401 RequiredBits = OldValue.getActiveBits();
7402 else if (OldValue.isUnsigned())
7403 RequiredBits = OldValue.getActiveBits() + 1;
7404 else
7405 RequiredBits = OldValue.getSignificantBits();
7406 if (RequiredBits > AllowedBits) {
7407 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7408 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7409 << Arg->getSourceRange();
7410 NoteTemplateParameterLocation(*Param);
7411 }
7412 }
7413
7414 if (ArgPE) {
7415 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7416 CanonicalConverted =
7417 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7418 } else {
7419 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7420 SugaredConverted = TemplateArgument(Context, Value, T);
7421 CanonicalConverted =
7422 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7423 }
7424 return Arg;
7425 }
7426
7427 QualType ArgType = DeductionArg->getType();
7428 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7429
7430 // Handle pointer-to-function, reference-to-function, and
7431 // pointer-to-member-function all in (roughly) the same way.
7432 if (// -- For a non-type template-parameter of type pointer to
7433 // function, only the function-to-pointer conversion (4.3) is
7434 // applied. If the template-argument represents a set of
7435 // overloaded functions (or a pointer to such), the matching
7436 // function is selected from the set (13.4).
7437 (ParamType->isPointerType() &&
7438 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7439 // -- For a non-type template-parameter of type reference to
7440 // function, no conversions apply. If the template-argument
7441 // represents a set of overloaded functions, the matching
7442 // function is selected from the set (13.4).
7443 (ParamType->isReferenceType() &&
7444 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7445 // -- For a non-type template-parameter of type pointer to
7446 // member function, no conversions apply. If the
7447 // template-argument represents a set of overloaded member
7448 // functions, the matching member function is selected from
7449 // the set (13.4).
7450 (ParamType->isMemberPointerType() &&
7451 ParamType->castAs<MemberPointerType>()->getPointeeType()
7452 ->isFunctionType())) {
7453
7454 if (DeductionArg->getType() == Context.OverloadTy) {
7455 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg, TargetType: ParamType,
7456 Complain: true,
7457 Found&: FoundResult)) {
7458 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7459 return ExprError();
7460
7461 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7462 if (Res.isInvalid())
7463 return ExprError();
7464 DeductionArg = Res.get();
7465 ArgType = Arg->getType();
7466 } else
7467 return ExprError();
7468 }
7469 setDeductionArg(DeductionArg);
7470
7471 if (!ParamType->isMemberPointerType()) {
7472 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7473 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted,
7474 CanonicalConverted))
7475 return ExprError();
7476 return Arg;
7477 }
7478
7479 if (CheckTemplateArgumentPointerToMember(
7480 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7481 return ExprError();
7482 return Arg;
7483 }
7484
7485 setDeductionArg(DeductionArg);
7486
7487 if (ParamType->isPointerType()) {
7488 // -- for a non-type template-parameter of type pointer to
7489 // object, qualification conversions (4.4) and the
7490 // array-to-pointer conversion (4.2) are applied.
7491 // C++0x also allows a value of std::nullptr_t.
7492 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7493 "Only object pointers allowed here");
7494
7495 // FIXME: Deal with pack expansions here.
7496 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7497 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted))
7498 return ExprError();
7499 return Arg;
7500 }
7501
7502 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7503 // -- For a non-type template-parameter of type reference to
7504 // object, no conversions apply. The type referred to by the
7505 // reference may be more cv-qualified than the (otherwise
7506 // identical) type of the template-argument. The
7507 // template-parameter is bound directly to the
7508 // template-argument, which must be an lvalue.
7509 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7510 "Only object references allowed here");
7511
7512 // FIXME: Deal with pack expansions here.
7513 if (Arg->getType() == Context.OverloadTy) {
7514 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg,
7515 TargetType: ParamRefType->getPointeeType(),
7516 Complain: true,
7517 Found&: FoundResult)) {
7518 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7519 return ExprError();
7520 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7521 if (Res.isInvalid())
7522 return ExprError();
7523 Arg = Res.get();
7524 ArgType = Arg->getType();
7525 } else
7526 return ExprError();
7527 }
7528
7529 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7530 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted))
7531 return ExprError();
7532 return Arg;
7533 }
7534
7535 // Deal with parameters of type std::nullptr_t.
7536 if (ParamType->isNullPtrType()) {
7537 if (DeductionArg->isTypeDependent() || DeductionArg->isValueDependent()) {
7538 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7539 CanonicalConverted =
7540 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7541 return Arg;
7542 }
7543
7544 switch (isNullPointerValueTemplateArgument(S&: *this, Param, ParamType,
7545 Arg: DeductionArg)) {
7546 case NPV_NotNullPointer:
7547 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7548 << DeductionArg->getType() << ParamType;
7549 NoteTemplateParameterLocation(*Param);
7550 return ExprError();
7551
7552 case NPV_Error:
7553 return ExprError();
7554
7555 case NPV_NullPointer:
7556 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7557 if (ArgPE) {
7558 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7559 CanonicalConverted =
7560 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7561 } else {
7562 SugaredConverted = TemplateArgument(ParamType,
7563 /*isNullPtr=*/true);
7564 CanonicalConverted =
7565 TemplateArgument(Context.getCanonicalType(T: ParamType),
7566 /*isNullPtr=*/true);
7567 }
7568 return Arg;
7569 }
7570 }
7571
7572 // -- For a non-type template-parameter of type pointer to data
7573 // member, qualification conversions (4.4) are applied.
7574 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7575
7576 // FIXME: Deal with pack expansions here.
7577 if (CheckTemplateArgumentPointerToMember(
7578 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7579 return ExprError();
7580 return Arg;
7581}
7582
7583static void DiagnoseTemplateParameterListArityMismatch(
7584 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7585 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7586
7587bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7588 TemplateParameterList *Params,
7589 TemplateArgumentLoc &Arg,
7590 bool PartialOrdering,
7591 bool *StrictPackMatch) {
7592 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7593 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7594 if (!Template) {
7595 // Any dependent template name is fine.
7596 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7597 return false;
7598 }
7599
7600 if (Template->isInvalidDecl())
7601 return true;
7602
7603 // C++0x [temp.arg.template]p1:
7604 // A template-argument for a template template-parameter shall be
7605 // the name of a class template or an alias template, expressed as an
7606 // id-expression. When the template-argument names a class template, only
7607 // primary class templates are considered when matching the
7608 // template template argument with the corresponding parameter;
7609 // partial specializations are not considered even if their
7610 // parameter lists match that of the template template parameter.
7611 //
7612 // Note that we also allow template template parameters here, which
7613 // will happen when we are dealing with, e.g., class template
7614 // partial specializations.
7615 if (!isa<ClassTemplateDecl>(Val: Template) &&
7616 !isa<TemplateTemplateParmDecl>(Val: Template) &&
7617 !isa<TypeAliasTemplateDecl>(Val: Template) &&
7618 !isa<BuiltinTemplateDecl>(Val: Template)) {
7619 assert(isa<FunctionTemplateDecl>(Template) &&
7620 "Only function templates are possible here");
7621 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7622 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7623 << Template;
7624 }
7625
7626 // C++1z [temp.arg.template]p3: (DR 150)
7627 // A template-argument matches a template template-parameter P when P
7628 // is at least as specialized as the template-argument A.
7629 if (!isTemplateTemplateParameterAtLeastAsSpecializedAs(
7630 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7631 PartialOrdering, StrictPackMatch))
7632 return true;
7633 // P2113
7634 // C++20[temp.func.order]p2
7635 // [...] If both deductions succeed, the partial ordering selects the
7636 // more constrained template (if one exists) as determined below.
7637 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7638 Params->getAssociatedConstraints(AC&: ParamsAC);
7639 // C++20[temp.arg.template]p3
7640 // [...] In this comparison, if P is unconstrained, the constraints on A
7641 // are not considered.
7642 if (ParamsAC.empty())
7643 return false;
7644
7645 Template->getAssociatedConstraints(AC&: TemplateAC);
7646
7647 bool IsParamAtLeastAsConstrained;
7648 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7649 IsParamAtLeastAsConstrained))
7650 return true;
7651 if (!IsParamAtLeastAsConstrained) {
7652 Diag(Arg.getLocation(),
7653 diag::err_template_template_parameter_not_at_least_as_constrained)
7654 << Template << Param << Arg.getSourceRange();
7655 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7656 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7657 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7658 TemplateAC);
7659 return true;
7660 }
7661 return false;
7662}
7663
7664static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7665 unsigned HereDiagID,
7666 unsigned ExternalDiagID) {
7667 if (Decl.getLocation().isValid())
7668 return S.Diag(Decl.getLocation(), HereDiagID);
7669
7670 SmallString<128> Str;
7671 llvm::raw_svector_ostream Out(Str);
7672 PrintingPolicy PP = S.getPrintingPolicy();
7673 PP.TerseOutput = 1;
7674 Decl.print(Out, PP);
7675 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7676}
7677
7678void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7679 std::optional<SourceRange> ParamRange) {
7680 SemaDiagnosticBuilder DB =
7681 noteLocation(*this, Decl, diag::note_template_decl_here,
7682 diag::note_template_decl_external);
7683 if (ParamRange && ParamRange->isValid()) {
7684 assert(Decl.getLocation().isValid() &&
7685 "Parameter range has location when Decl does not");
7686 DB << *ParamRange;
7687 }
7688}
7689
7690void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7691 noteLocation(*this, Decl, diag::note_template_param_here,
7692 diag::note_template_param_external);
7693}
7694
7695ExprResult Sema::BuildExpressionFromDeclTemplateArgument(
7696 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7697 NamedDecl *TemplateParam) {
7698 // C++ [temp.param]p8:
7699 //
7700 // A non-type template-parameter of type "array of T" or
7701 // "function returning T" is adjusted to be of type "pointer to
7702 // T" or "pointer to function returning T", respectively.
7703 if (ParamType->isArrayType())
7704 ParamType = Context.getArrayDecayedType(T: ParamType);
7705 else if (ParamType->isFunctionType())
7706 ParamType = Context.getPointerType(T: ParamType);
7707
7708 // For a NULL non-type template argument, return nullptr casted to the
7709 // parameter's type.
7710 if (Arg.getKind() == TemplateArgument::NullPtr) {
7711 return ImpCastExprToType(
7712 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7713 ParamType,
7714 ParamType->getAs<MemberPointerType>()
7715 ? CK_NullToMemberPointer
7716 : CK_NullToPointer);
7717 }
7718 assert(Arg.getKind() == TemplateArgument::Declaration &&
7719 "Only declaration template arguments permitted here");
7720
7721 ValueDecl *VD = Arg.getAsDecl();
7722
7723 CXXScopeSpec SS;
7724 if (ParamType->isMemberPointerType()) {
7725 // If this is a pointer to member, we need to use a qualified name to
7726 // form a suitable pointer-to-member constant.
7727 assert(VD->getDeclContext()->isRecord() &&
7728 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7729 isa<IndirectFieldDecl>(VD)));
7730 QualType ClassType
7731 = Context.getTypeDeclType(Decl: cast<RecordDecl>(VD->getDeclContext()));
7732 NestedNameSpecifier *Qualifier =
7733 NestedNameSpecifier::Create(Context, Prefix: nullptr, T: ClassType.getTypePtr());
7734 SS.MakeTrivial(Context, Qualifier, R: Loc);
7735 }
7736
7737 ExprResult RefExpr = BuildDeclarationNameExpr(
7738 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7739 if (RefExpr.isInvalid())
7740 return ExprError();
7741
7742 // For a pointer, the argument declaration is the pointee. Take its address.
7743 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7744 if (ParamType->isPointerType() && !ElemT.isNull() &&
7745 Context.hasSimilarType(T1: ElemT, T2: ParamType->getPointeeType())) {
7746 // Decay an array argument if we want a pointer to its first element.
7747 RefExpr = DefaultFunctionArrayConversion(E: RefExpr.get());
7748 if (RefExpr.isInvalid())
7749 return ExprError();
7750 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7751 // For any other pointer, take the address (or form a pointer-to-member).
7752 RefExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_AddrOf, InputExpr: RefExpr.get());
7753 if (RefExpr.isInvalid())
7754 return ExprError();
7755 } else if (ParamType->isRecordType()) {
7756 assert(isa<TemplateParamObjectDecl>(VD) &&
7757 "arg for class template param not a template parameter object");
7758 // No conversions apply in this case.
7759 return RefExpr;
7760 } else {
7761 assert(ParamType->isReferenceType() &&
7762 "unexpected type for decl template argument");
7763 if (NonTypeTemplateParmDecl *NTTP =
7764 dyn_cast_if_present<NonTypeTemplateParmDecl>(Val: TemplateParam)) {
7765 QualType TemplateParamType = NTTP->getType();
7766 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7767 if (AT && AT->isDecltypeAuto()) {
7768 RefExpr = new (getASTContext()) SubstNonTypeTemplateParmExpr(
7769 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7770 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7771 /*PackIndex=*/std::nullopt,
7772 /*RefParam=*/true, /*Final=*/true);
7773 }
7774 }
7775 }
7776
7777 // At this point we should have the right value category.
7778 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7779 "value kind mismatch for non-type template argument");
7780
7781 // The type of the template parameter can differ from the type of the
7782 // argument in various ways; convert it now if necessary.
7783 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7784 if (!Context.hasSameType(T1: RefExpr.get()->getType(), T2: DestExprType)) {
7785 CastKind CK;
7786 if (Context.hasSimilarType(T1: RefExpr.get()->getType(), T2: DestExprType) ||
7787 IsFunctionConversion(FromType: RefExpr.get()->getType(), ToType: DestExprType)) {
7788 CK = CK_NoOp;
7789 } else if (ParamType->isVoidPointerType() &&
7790 RefExpr.get()->getType()->isPointerType()) {
7791 CK = CK_BitCast;
7792 } else {
7793 // FIXME: Pointers to members can need conversion derived-to-base or
7794 // base-to-derived conversions. We currently don't retain enough
7795 // information to convert properly (we need to track a cast path or
7796 // subobject number in the template argument).
7797 llvm_unreachable(
7798 "unexpected conversion required for non-type template argument");
7799 }
7800 RefExpr = ImpCastExprToType(E: RefExpr.get(), Type: DestExprType, CK,
7801 VK: RefExpr.get()->getValueKind());
7802 }
7803
7804 return RefExpr;
7805}
7806
7807/// Construct a new expression that refers to the given
7808/// integral template argument with the given source-location
7809/// information.
7810///
7811/// This routine takes care of the mapping from an integral template
7812/// argument (which may have any integral type) to the appropriate
7813/// literal value.
7814static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
7815 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
7816 assert(OrigT->isIntegralOrEnumerationType());
7817
7818 // If this is an enum type that we're instantiating, we need to use an integer
7819 // type the same size as the enumerator. We don't want to build an
7820 // IntegerLiteral with enum type. The integer type of an enum type can be of
7821 // any integral type with C++11 enum classes, make sure we create the right
7822 // type of literal for it.
7823 QualType T = OrigT;
7824 if (const EnumType *ET = OrigT->getAs<EnumType>())
7825 T = ET->getDecl()->getIntegerType();
7826
7827 Expr *E;
7828 if (T->isAnyCharacterType()) {
7829 CharacterLiteralKind Kind;
7830 if (T->isWideCharType())
7831 Kind = CharacterLiteralKind::Wide;
7832 else if (T->isChar8Type() && S.getLangOpts().Char8)
7833 Kind = CharacterLiteralKind::UTF8;
7834 else if (T->isChar16Type())
7835 Kind = CharacterLiteralKind::UTF16;
7836 else if (T->isChar32Type())
7837 Kind = CharacterLiteralKind::UTF32;
7838 else
7839 Kind = CharacterLiteralKind::Ascii;
7840
7841 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
7842 } else if (T->isBooleanType()) {
7843 E = CXXBoolLiteralExpr::Create(C: S.Context, Val: Int.getBoolValue(), Ty: T, Loc);
7844 } else {
7845 E = IntegerLiteral::Create(C: S.Context, V: Int, type: T, l: Loc);
7846 }
7847
7848 if (OrigT->isEnumeralType()) {
7849 // FIXME: This is a hack. We need a better way to handle substituted
7850 // non-type template parameters.
7851 E = CStyleCastExpr::Create(Context: S.Context, T: OrigT, VK: VK_PRValue, K: CK_IntegralCast, Op: E,
7852 BasePath: nullptr, FPO: S.CurFPFeatureOverrides(),
7853 WrittenTy: S.Context.getTrivialTypeSourceInfo(T: OrigT, Loc),
7854 L: Loc, R: Loc);
7855 }
7856
7857 return E;
7858}
7859
7860static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
7861 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
7862 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
7863 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
7864 ILE->setType(T);
7865 return ILE;
7866 };
7867
7868 switch (Val.getKind()) {
7869 case APValue::AddrLabelDiff:
7870 // This cannot occur in a template argument at all.
7871 case APValue::Array:
7872 case APValue::Struct:
7873 case APValue::Union:
7874 // These can only occur within a template parameter object, which is
7875 // represented as a TemplateArgument::Declaration.
7876 llvm_unreachable("unexpected template argument value");
7877
7878 case APValue::Int:
7879 return BuildExpressionFromIntegralTemplateArgumentValue(S, OrigT: T, Int: Val.getInt(),
7880 Loc);
7881
7882 case APValue::Float:
7883 return FloatingLiteral::Create(C: S.Context, V: Val.getFloat(), /*IsExact=*/isexact: true,
7884 Type: T, L: Loc);
7885
7886 case APValue::FixedPoint:
7887 return FixedPointLiteral::CreateFromRawInt(
7888 C: S.Context, V: Val.getFixedPoint().getValue(), type: T, l: Loc,
7889 Scale: Val.getFixedPoint().getScale());
7890
7891 case APValue::ComplexInt: {
7892 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7893 return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
7894 S, OrigT: ElemT, Int: Val.getComplexIntReal(), Loc),
7895 BuildExpressionFromIntegralTemplateArgumentValue(
7896 S, OrigT: ElemT, Int: Val.getComplexIntImag(), Loc)});
7897 }
7898
7899 case APValue::ComplexFloat: {
7900 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7901 return MakeInitList(
7902 {FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatReal(), isexact: true,
7903 Type: ElemT, L: Loc),
7904 FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatImag(), isexact: true,
7905 Type: ElemT, L: Loc)});
7906 }
7907
7908 case APValue::Vector: {
7909 QualType ElemT = T->castAs<VectorType>()->getElementType();
7910 llvm::SmallVector<Expr *, 8> Elts;
7911 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
7912 Elts.push_back(Elt: BuildExpressionFromNonTypeTemplateArgumentValue(
7913 S, T: ElemT, Val: Val.getVectorElt(I), Loc));
7914 return MakeInitList(Elts);
7915 }
7916
7917 case APValue::None:
7918 case APValue::Indeterminate:
7919 llvm_unreachable("Unexpected APValue kind.");
7920 case APValue::LValue:
7921 case APValue::MemberPointer:
7922 // There isn't necessarily a valid equivalent source-level syntax for
7923 // these; in particular, a naive lowering might violate access control.
7924 // So for now we lower to a ConstantExpr holding the value, wrapped around
7925 // an OpaqueValueExpr.
7926 // FIXME: We should have a better representation for this.
7927 ExprValueKind VK = VK_PRValue;
7928 if (T->isReferenceType()) {
7929 T = T->getPointeeType();
7930 VK = VK_LValue;
7931 }
7932 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
7933 return ConstantExpr::Create(S.Context, OVE, Val);
7934 }
7935 llvm_unreachable("Unhandled APValue::ValueKind enum");
7936}
7937
7938ExprResult
7939Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
7940 SourceLocation Loc) {
7941 switch (Arg.getKind()) {
7942 case TemplateArgument::Null:
7943 case TemplateArgument::Type:
7944 case TemplateArgument::Template:
7945 case TemplateArgument::TemplateExpansion:
7946 case TemplateArgument::Pack:
7947 llvm_unreachable("not a non-type template argument");
7948
7949 case TemplateArgument::Expression:
7950 return Arg.getAsExpr();
7951
7952 case TemplateArgument::NullPtr:
7953 case TemplateArgument::Declaration:
7954 return BuildExpressionFromDeclTemplateArgument(
7955 Arg, ParamType: Arg.getNonTypeTemplateArgumentType(), Loc);
7956
7957 case TemplateArgument::Integral:
7958 return BuildExpressionFromIntegralTemplateArgumentValue(
7959 S&: *this, OrigT: Arg.getIntegralType(), Int: Arg.getAsIntegral(), Loc);
7960
7961 case TemplateArgument::StructuralValue:
7962 return BuildExpressionFromNonTypeTemplateArgumentValue(
7963 S&: *this, T: Arg.getStructuralValueType(), Val: Arg.getAsStructuralValue(), Loc);
7964 }
7965 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
7966}
7967
7968/// Match two template parameters within template parameter lists.
7969static bool MatchTemplateParameterKind(
7970 Sema &S, NamedDecl *New,
7971 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
7972 const NamedDecl *OldInstFrom, bool Complain,
7973 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
7974 // Check the actual kind (type, non-type, template).
7975 if (Old->getKind() != New->getKind()) {
7976 if (Complain) {
7977 unsigned NextDiag = diag::err_template_param_different_kind;
7978 if (TemplateArgLoc.isValid()) {
7979 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7980 NextDiag = diag::note_template_param_different_kind;
7981 }
7982 S.Diag(New->getLocation(), NextDiag)
7983 << (Kind != Sema::TPL_TemplateMatch);
7984 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7985 << (Kind != Sema::TPL_TemplateMatch);
7986 }
7987
7988 return false;
7989 }
7990
7991 // Check that both are parameter packs or neither are parameter packs.
7992 // However, if we are matching a template template argument to a
7993 // template template parameter, the template template parameter can have
7994 // a parameter pack where the template template argument does not.
7995 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
7996 if (Complain) {
7997 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7998 if (TemplateArgLoc.isValid()) {
7999 S.Diag(TemplateArgLoc,
8000 diag::err_template_arg_template_params_mismatch);
8001 NextDiag = diag::note_template_parameter_pack_non_pack;
8002 }
8003
8004 unsigned ParamKind = isa<TemplateTypeParmDecl>(Val: New)? 0
8005 : isa<NonTypeTemplateParmDecl>(Val: New)? 1
8006 : 2;
8007 S.Diag(New->getLocation(), NextDiag)
8008 << ParamKind << New->isParameterPack();
8009 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8010 << ParamKind << Old->isParameterPack();
8011 }
8012
8013 return false;
8014 }
8015
8016 // For non-type template parameters, check the type of the parameter.
8017 if (NonTypeTemplateParmDecl *OldNTTP
8018 = dyn_cast<NonTypeTemplateParmDecl>(Val: Old)) {
8019 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(Val: New);
8020
8021 // C++20 [temp.over.link]p6:
8022 // Two [non-type] template-parameters are equivalent [if] they have
8023 // equivalent types ignoring the use of type-constraints for
8024 // placeholder types
8025 QualType OldType = S.Context.getUnconstrainedType(T: OldNTTP->getType());
8026 QualType NewType = S.Context.getUnconstrainedType(T: NewNTTP->getType());
8027 if (!S.Context.hasSameType(T1: OldType, T2: NewType)) {
8028 if (Complain) {
8029 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8030 if (TemplateArgLoc.isValid()) {
8031 S.Diag(TemplateArgLoc,
8032 diag::err_template_arg_template_params_mismatch);
8033 NextDiag = diag::note_template_nontype_parm_different_type;
8034 }
8035 S.Diag(NewNTTP->getLocation(), NextDiag)
8036 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8037 S.Diag(OldNTTP->getLocation(),
8038 diag::note_template_nontype_parm_prev_declaration)
8039 << OldNTTP->getType();
8040 }
8041
8042 return false;
8043 }
8044 }
8045 // For template template parameters, check the template parameter types.
8046 // The template parameter lists of template template
8047 // parameters must agree.
8048 else if (TemplateTemplateParmDecl *OldTTP =
8049 dyn_cast<TemplateTemplateParmDecl>(Val: Old)) {
8050 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(Val: New);
8051 if (!S.TemplateParameterListsAreEqual(
8052 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8053 OldTTP->getTemplateParameters(), Complain,
8054 (Kind == Sema::TPL_TemplateMatch
8055 ? Sema::TPL_TemplateTemplateParmMatch
8056 : Kind),
8057 TemplateArgLoc))
8058 return false;
8059 }
8060
8061 if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8062 !isa<TemplateTemplateParmDecl>(Val: Old)) {
8063 const Expr *NewC = nullptr, *OldC = nullptr;
8064
8065 if (isa<TemplateTypeParmDecl>(Val: New)) {
8066 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: New)->getTypeConstraint())
8067 NewC = TC->getImmediatelyDeclaredConstraint();
8068 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: Old)->getTypeConstraint())
8069 OldC = TC->getImmediatelyDeclaredConstraint();
8070 } else if (isa<NonTypeTemplateParmDecl>(Val: New)) {
8071 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: New)
8072 ->getPlaceholderTypeConstraint())
8073 NewC = E;
8074 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: Old)
8075 ->getPlaceholderTypeConstraint())
8076 OldC = E;
8077 } else
8078 llvm_unreachable("unexpected template parameter type");
8079
8080 auto Diagnose = [&] {
8081 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8082 diag::err_template_different_type_constraint);
8083 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8084 diag::note_template_prev_declaration) << /*declaration*/0;
8085 };
8086
8087 if (!NewC != !OldC) {
8088 if (Complain)
8089 Diagnose();
8090 return false;
8091 }
8092
8093 if (NewC) {
8094 if (!S.AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldC, New: NewInstFrom,
8095 NewConstr: NewC)) {
8096 if (Complain)
8097 Diagnose();
8098 return false;
8099 }
8100 }
8101 }
8102
8103 return true;
8104}
8105
8106/// Diagnose a known arity mismatch when comparing template argument
8107/// lists.
8108static
8109void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8110 TemplateParameterList *New,
8111 TemplateParameterList *Old,
8112 Sema::TemplateParameterListEqualKind Kind,
8113 SourceLocation TemplateArgLoc) {
8114 unsigned NextDiag = diag::err_template_param_list_different_arity;
8115 if (TemplateArgLoc.isValid()) {
8116 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8117 NextDiag = diag::note_template_param_list_different_arity;
8118 }
8119 S.Diag(New->getTemplateLoc(), NextDiag)
8120 << (New->size() > Old->size())
8121 << (Kind != Sema::TPL_TemplateMatch)
8122 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8123 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8124 << (Kind != Sema::TPL_TemplateMatch)
8125 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8126}
8127
8128bool Sema::TemplateParameterListsAreEqual(
8129 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8130 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8131 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8132 if (Old->size() != New->size()) {
8133 if (Complain)
8134 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8135 TemplateArgLoc);
8136
8137 return false;
8138 }
8139
8140 // C++0x [temp.arg.template]p3:
8141 // A template-argument matches a template template-parameter (call it P)
8142 // when each of the template parameters in the template-parameter-list of
8143 // the template-argument's corresponding class template or alias template
8144 // (call it A) matches the corresponding template parameter in the
8145 // template-parameter-list of P. [...]
8146 TemplateParameterList::iterator NewParm = New->begin();
8147 TemplateParameterList::iterator NewParmEnd = New->end();
8148 for (TemplateParameterList::iterator OldParm = Old->begin(),
8149 OldParmEnd = Old->end();
8150 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8151 if (NewParm == NewParmEnd) {
8152 if (Complain)
8153 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8154 TemplateArgLoc);
8155 return false;
8156 }
8157 if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm,
8158 OldInstFrom, Complain, Kind,
8159 TemplateArgLoc))
8160 return false;
8161 }
8162
8163 // Make sure we exhausted all of the arguments.
8164 if (NewParm != NewParmEnd) {
8165 if (Complain)
8166 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8167 TemplateArgLoc);
8168
8169 return false;
8170 }
8171
8172 if (Kind != TPL_TemplateParamsEquivalent) {
8173 const Expr *NewRC = New->getRequiresClause();
8174 const Expr *OldRC = Old->getRequiresClause();
8175
8176 auto Diagnose = [&] {
8177 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8178 diag::err_template_different_requires_clause);
8179 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8180 diag::note_template_prev_declaration) << /*declaration*/0;
8181 };
8182
8183 if (!NewRC != !OldRC) {
8184 if (Complain)
8185 Diagnose();
8186 return false;
8187 }
8188
8189 if (NewRC) {
8190 if (!AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldRC, New: NewInstFrom,
8191 NewConstr: NewRC)) {
8192 if (Complain)
8193 Diagnose();
8194 return false;
8195 }
8196 }
8197 }
8198
8199 return true;
8200}
8201
8202bool
8203Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8204 if (!S)
8205 return false;
8206
8207 // Find the nearest enclosing declaration scope.
8208 S = S->getDeclParent();
8209
8210 // C++ [temp.pre]p6: [P2096]
8211 // A template, explicit specialization, or partial specialization shall not
8212 // have C linkage.
8213 DeclContext *Ctx = S->getEntity();
8214 if (Ctx && Ctx->isExternCContext()) {
8215 SourceRange Range =
8216 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8217 ? TemplateParams->getParam(Idx: 0)->getSourceRange()
8218 : TemplateParams->getSourceRange();
8219 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8220 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8221 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8222 return true;
8223 }
8224 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8225
8226 // C++ [temp]p2:
8227 // A template-declaration can appear only as a namespace scope or
8228 // class scope declaration.
8229 // C++ [temp.expl.spec]p3:
8230 // An explicit specialization may be declared in any scope in which the
8231 // corresponding primary template may be defined.
8232 // C++ [temp.class.spec]p6: [P2096]
8233 // A partial specialization may be declared in any scope in which the
8234 // corresponding primary template may be defined.
8235 if (Ctx) {
8236 if (Ctx->isFileContext())
8237 return false;
8238 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Ctx)) {
8239 // C++ [temp.mem]p2:
8240 // A local class shall not have member templates.
8241 if (RD->isLocalClass())
8242 return Diag(TemplateParams->getTemplateLoc(),
8243 diag::err_template_inside_local_class)
8244 << TemplateParams->getSourceRange();
8245 else
8246 return false;
8247 }
8248 }
8249
8250 return Diag(TemplateParams->getTemplateLoc(),
8251 diag::err_template_outside_namespace_or_class_scope)
8252 << TemplateParams->getSourceRange();
8253}
8254
8255/// Determine what kind of template specialization the given declaration
8256/// is.
8257static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8258 if (!D)
8259 return TSK_Undeclared;
8260
8261 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D))
8262 return Record->getTemplateSpecializationKind();
8263 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D))
8264 return Function->getTemplateSpecializationKind();
8265 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D))
8266 return Var->getTemplateSpecializationKind();
8267
8268 return TSK_Undeclared;
8269}
8270
8271/// Check whether a specialization is well-formed in the current
8272/// context.
8273///
8274/// This routine determines whether a template specialization can be declared
8275/// in the current context (C++ [temp.expl.spec]p2).
8276///
8277/// \param S the semantic analysis object for which this check is being
8278/// performed.
8279///
8280/// \param Specialized the entity being specialized or instantiated, which
8281/// may be a kind of template (class template, function template, etc.) or
8282/// a member of a class template (member function, static data member,
8283/// member class).
8284///
8285/// \param PrevDecl the previous declaration of this entity, if any.
8286///
8287/// \param Loc the location of the explicit specialization or instantiation of
8288/// this entity.
8289///
8290/// \param IsPartialSpecialization whether this is a partial specialization of
8291/// a class template.
8292///
8293/// \returns true if there was an error that we cannot recover from, false
8294/// otherwise.
8295static bool CheckTemplateSpecializationScope(Sema &S,
8296 NamedDecl *Specialized,
8297 NamedDecl *PrevDecl,
8298 SourceLocation Loc,
8299 bool IsPartialSpecialization) {
8300 // Keep these "kind" numbers in sync with the %select statements in the
8301 // various diagnostics emitted by this routine.
8302 int EntityKind = 0;
8303 if (isa<ClassTemplateDecl>(Val: Specialized))
8304 EntityKind = IsPartialSpecialization? 1 : 0;
8305 else if (isa<VarTemplateDecl>(Val: Specialized))
8306 EntityKind = IsPartialSpecialization ? 3 : 2;
8307 else if (isa<FunctionTemplateDecl>(Val: Specialized))
8308 EntityKind = 4;
8309 else if (isa<CXXMethodDecl>(Val: Specialized))
8310 EntityKind = 5;
8311 else if (isa<VarDecl>(Val: Specialized))
8312 EntityKind = 6;
8313 else if (isa<RecordDecl>(Val: Specialized))
8314 EntityKind = 7;
8315 else if (isa<EnumDecl>(Val: Specialized) && S.getLangOpts().CPlusPlus11)
8316 EntityKind = 8;
8317 else {
8318 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8319 << S.getLangOpts().CPlusPlus11;
8320 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8321 return true;
8322 }
8323
8324 // C++ [temp.expl.spec]p2:
8325 // An explicit specialization may be declared in any scope in which
8326 // the corresponding primary template may be defined.
8327 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8328 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8329 << Specialized;
8330 return true;
8331 }
8332
8333 // C++ [temp.class.spec]p6:
8334 // A class template partial specialization may be declared in any
8335 // scope in which the primary template may be defined.
8336 DeclContext *SpecializedContext =
8337 Specialized->getDeclContext()->getRedeclContext();
8338 DeclContext *DC = S.CurContext->getRedeclContext();
8339
8340 // Make sure that this redeclaration (or definition) occurs in the same
8341 // scope or an enclosing namespace.
8342 if (!(DC->isFileContext() ? DC->Encloses(DC: SpecializedContext)
8343 : DC->Equals(DC: SpecializedContext))) {
8344 if (isa<TranslationUnitDecl>(Val: SpecializedContext))
8345 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8346 << EntityKind << Specialized;
8347 else {
8348 auto *ND = cast<NamedDecl>(Val: SpecializedContext);
8349 int Diag = diag::err_template_spec_redecl_out_of_scope;
8350 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8351 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8352 S.Diag(Loc, Diag) << EntityKind << Specialized
8353 << ND << isa<CXXRecordDecl>(ND);
8354 }
8355
8356 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8357
8358 // Don't allow specializing in the wrong class during error recovery.
8359 // Otherwise, things can go horribly wrong.
8360 if (DC->isRecord())
8361 return true;
8362 }
8363
8364 return false;
8365}
8366
8367static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8368 if (!E->isTypeDependent())
8369 return SourceLocation();
8370 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8371 Checker.TraverseStmt(E);
8372 if (Checker.MatchLoc.isInvalid())
8373 return E->getSourceRange();
8374 return Checker.MatchLoc;
8375}
8376
8377static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8378 if (!TL.getType()->isDependentType())
8379 return SourceLocation();
8380 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8381 Checker.TraverseTypeLoc(TL);
8382 if (Checker.MatchLoc.isInvalid())
8383 return TL.getSourceRange();
8384 return Checker.MatchLoc;
8385}
8386
8387/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8388/// that checks non-type template partial specialization arguments.
8389static bool CheckNonTypeTemplatePartialSpecializationArgs(
8390 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8391 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8392 for (unsigned I = 0; I != NumArgs; ++I) {
8393 if (Args[I].getKind() == TemplateArgument::Pack) {
8394 if (CheckNonTypeTemplatePartialSpecializationArgs(
8395 S, TemplateNameLoc, Param, Args: Args[I].pack_begin(),
8396 NumArgs: Args[I].pack_size(), IsDefaultArgument))
8397 return true;
8398
8399 continue;
8400 }
8401
8402 if (Args[I].getKind() != TemplateArgument::Expression)
8403 continue;
8404
8405 Expr *ArgExpr = Args[I].getAsExpr();
8406
8407 // We can have a pack expansion of any of the bullets below.
8408 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: ArgExpr))
8409 ArgExpr = Expansion->getPattern();
8410
8411 // Strip off any implicit casts we added as part of type checking.
8412 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
8413 ArgExpr = ICE->getSubExpr();
8414
8415 // C++ [temp.class.spec]p8:
8416 // A non-type argument is non-specialized if it is the name of a
8417 // non-type parameter. All other non-type arguments are
8418 // specialized.
8419 //
8420 // Below, we check the two conditions that only apply to
8421 // specialized non-type arguments, so skip any non-specialized
8422 // arguments.
8423 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ArgExpr))
8424 if (isa<NonTypeTemplateParmDecl>(Val: DRE->getDecl()))
8425 continue;
8426
8427 // C++ [temp.class.spec]p9:
8428 // Within the argument list of a class template partial
8429 // specialization, the following restrictions apply:
8430 // -- A partially specialized non-type argument expression
8431 // shall not involve a template parameter of the partial
8432 // specialization except when the argument expression is a
8433 // simple identifier.
8434 // -- The type of a template parameter corresponding to a
8435 // specialized non-type argument shall not be dependent on a
8436 // parameter of the specialization.
8437 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8438 // We implement a compromise between the original rules and DR1315:
8439 // -- A specialized non-type template argument shall not be
8440 // type-dependent and the corresponding template parameter
8441 // shall have a non-dependent type.
8442 SourceRange ParamUseRange =
8443 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8444 if (ParamUseRange.isValid()) {
8445 if (IsDefaultArgument) {
8446 S.Diag(TemplateNameLoc,
8447 diag::err_dependent_non_type_arg_in_partial_spec);
8448 S.Diag(ParamUseRange.getBegin(),
8449 diag::note_dependent_non_type_default_arg_in_partial_spec)
8450 << ParamUseRange;
8451 } else {
8452 S.Diag(ParamUseRange.getBegin(),
8453 diag::err_dependent_non_type_arg_in_partial_spec)
8454 << ParamUseRange;
8455 }
8456 return true;
8457 }
8458
8459 ParamUseRange = findTemplateParameter(
8460 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8461 if (ParamUseRange.isValid()) {
8462 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8463 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8464 << Param->getType();
8465 S.NoteTemplateParameterLocation(*Param);
8466 return true;
8467 }
8468 }
8469
8470 return false;
8471}
8472
8473bool Sema::CheckTemplatePartialSpecializationArgs(
8474 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8475 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8476 // We have to be conservative when checking a template in a dependent
8477 // context.
8478 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8479 return false;
8480
8481 TemplateParameterList *TemplateParams =
8482 PrimaryTemplate->getTemplateParameters();
8483 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8484 NonTypeTemplateParmDecl *Param
8485 = dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: I));
8486 if (!Param)
8487 continue;
8488
8489 if (CheckNonTypeTemplatePartialSpecializationArgs(S&: *this, TemplateNameLoc,
8490 Param, Args: &TemplateArgs[I],
8491 NumArgs: 1, IsDefaultArgument: I >= NumExplicit))
8492 return true;
8493 }
8494
8495 return false;
8496}
8497
8498DeclResult Sema::ActOnClassTemplateSpecialization(
8499 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8500 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8501 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8502 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8503 assert(TUK != TagUseKind::Reference && "References are not specializations");
8504
8505 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8506 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8507 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8508
8509 // Find the class template we're specializing
8510 TemplateName Name = TemplateId.Template.get();
8511 ClassTemplateDecl *ClassTemplate
8512 = dyn_cast_or_null<ClassTemplateDecl>(Val: Name.getAsTemplateDecl());
8513
8514 if (!ClassTemplate) {
8515 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8516 << (Name.getAsTemplateDecl() &&
8517 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8518 return true;
8519 }
8520
8521 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8522 auto Message = DSA->getMessage();
8523 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8524 << ClassTemplate << !Message.empty() << Message;
8525 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8526 }
8527
8528 if (S->isTemplateParamScope())
8529 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8530
8531 DeclContext *DC = ClassTemplate->getDeclContext();
8532
8533 bool isMemberSpecialization = false;
8534 bool isPartialSpecialization = false;
8535
8536 if (SS.isSet()) {
8537 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8538 diagnoseQualifiedDeclaration(SS, DC, Name: ClassTemplate->getDeclName(),
8539 Loc: TemplateNameLoc, TemplateId: &TemplateId,
8540 /*IsMemberSpecialization=*/false))
8541 return true;
8542 }
8543
8544 // Check the validity of the template headers that introduce this
8545 // template.
8546 // FIXME: We probably shouldn't complain about these headers for
8547 // friend declarations.
8548 bool Invalid = false;
8549 TemplateParameterList *TemplateParams =
8550 MatchTemplateParametersToScopeSpecifier(
8551 DeclStartLoc: KWLoc, DeclLoc: TemplateNameLoc, SS, TemplateId: &TemplateId, ParamLists: TemplateParameterLists,
8552 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
8553 if (Invalid)
8554 return true;
8555
8556 // Check that we can declare a template specialization here.
8557 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8558 return true;
8559
8560 if (TemplateParams && DC->isDependentContext()) {
8561 ContextRAII SavedContext(*this, DC);
8562 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
8563 return true;
8564 }
8565
8566 if (TemplateParams && TemplateParams->size() > 0) {
8567 isPartialSpecialization = true;
8568
8569 if (TUK == TagUseKind::Friend) {
8570 Diag(KWLoc, diag::err_partial_specialization_friend)
8571 << SourceRange(LAngleLoc, RAngleLoc);
8572 return true;
8573 }
8574
8575 // C++ [temp.class.spec]p10:
8576 // The template parameter list of a specialization shall not
8577 // contain default template argument values.
8578 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8579 Decl *Param = TemplateParams->getParam(Idx: I);
8580 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
8581 if (TTP->hasDefaultArgument()) {
8582 Diag(TTP->getDefaultArgumentLoc(),
8583 diag::err_default_arg_in_partial_spec);
8584 TTP->removeDefaultArgument();
8585 }
8586 } else if (NonTypeTemplateParmDecl *NTTP
8587 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
8588 if (NTTP->hasDefaultArgument()) {
8589 Diag(NTTP->getDefaultArgumentLoc(),
8590 diag::err_default_arg_in_partial_spec)
8591 << NTTP->getDefaultArgument().getSourceRange();
8592 NTTP->removeDefaultArgument();
8593 }
8594 } else {
8595 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
8596 if (TTP->hasDefaultArgument()) {
8597 Diag(TTP->getDefaultArgument().getLocation(),
8598 diag::err_default_arg_in_partial_spec)
8599 << TTP->getDefaultArgument().getSourceRange();
8600 TTP->removeDefaultArgument();
8601 }
8602 }
8603 }
8604 } else if (TemplateParams) {
8605 if (TUK == TagUseKind::Friend)
8606 Diag(KWLoc, diag::err_template_spec_friend)
8607 << FixItHint::CreateRemoval(
8608 SourceRange(TemplateParams->getTemplateLoc(),
8609 TemplateParams->getRAngleLoc()))
8610 << SourceRange(LAngleLoc, RAngleLoc);
8611 } else {
8612 assert(TUK == TagUseKind::Friend &&
8613 "should have a 'template<>' for this decl");
8614 }
8615
8616 // Check that the specialization uses the same tag kind as the
8617 // original template.
8618 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
8619 assert(Kind != TagTypeKind::Enum &&
8620 "Invalid enum tag in class template spec!");
8621 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(), NewTag: Kind,
8622 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
8623 Name: ClassTemplate->getIdentifier())) {
8624 Diag(KWLoc, diag::err_use_with_wrong_tag)
8625 << ClassTemplate
8626 << FixItHint::CreateReplacement(KWLoc,
8627 ClassTemplate->getTemplatedDecl()->getKindName());
8628 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8629 diag::note_previous_use);
8630 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8631 }
8632
8633 // Translate the parser's template argument list in our AST format.
8634 TemplateArgumentListInfo TemplateArgs =
8635 makeTemplateArgumentListInfo(S&: *this, TemplateId);
8636
8637 // Check for unexpanded parameter packs in any of the template arguments.
8638 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8639 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
8640 UPPC: isPartialSpecialization
8641 ? UPPC_PartialSpecialization
8642 : UPPC_ExplicitSpecialization))
8643 return true;
8644
8645 // Check that the template argument list is well-formed for this
8646 // template.
8647 CheckTemplateArgumentInfo CTAI;
8648 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8649 /*DefaultArgs=*/{},
8650 /*PartialTemplateArgs=*/false, CTAI,
8651 /*UpdateArgsWithConversions=*/true))
8652 return true;
8653
8654 // Find the class template (partial) specialization declaration that
8655 // corresponds to these arguments.
8656 if (isPartialSpecialization) {
8657 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
8658 TemplateArgs.size(),
8659 CTAI.CanonicalConverted))
8660 return true;
8661
8662 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8663 // also do it during instantiation.
8664 if (!Name.isDependent() &&
8665 !TemplateSpecializationType::anyDependentTemplateArguments(
8666 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
8667 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8668 << ClassTemplate->getDeclName();
8669 isPartialSpecialization = false;
8670 Invalid = true;
8671 }
8672 }
8673
8674 void *InsertPos = nullptr;
8675 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8676
8677 if (isPartialSpecialization)
8678 PrevDecl = ClassTemplate->findPartialSpecialization(
8679 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
8680 else
8681 PrevDecl =
8682 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
8683
8684 ClassTemplateSpecializationDecl *Specialization = nullptr;
8685
8686 // Check whether we can declare a class template specialization in
8687 // the current scope.
8688 if (TUK != TagUseKind::Friend &&
8689 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
8690 TemplateNameLoc,
8691 isPartialSpecialization))
8692 return true;
8693
8694 QualType CanonType;
8695 if (!isPartialSpecialization) {
8696 // Create a new class template specialization declaration node for
8697 // this explicit specialization or friend declaration.
8698 Specialization = ClassTemplateSpecializationDecl::Create(
8699 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
8700 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
8701 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8702 SetNestedNameSpecifier(*this, Specialization, SS);
8703 if (TemplateParameterLists.size() > 0) {
8704 Specialization->setTemplateParameterListsInfo(Context,
8705 TemplateParameterLists);
8706 }
8707
8708 if (!PrevDecl)
8709 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
8710
8711 if (!CurContext->isDependentContext())
8712 CanonType = Context.getTypeDeclType(Specialization);
8713 }
8714
8715 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
8716 T: Name, TLoc: TemplateNameLoc, SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted, Canon: CanonType);
8717
8718 if (isPartialSpecialization) {
8719 if (Context.hasSameType(
8720 T1: WrittenTy->getType(),
8721 T2: ClassTemplate->getInjectedClassNameSpecialization()) &&
8722 (!Context.getLangOpts().CPlusPlus20 ||
8723 !TemplateParams->hasAssociatedConstraints())) {
8724 // C++ [temp.class.spec]p9b3:
8725 //
8726 // -- The argument list of the specialization shall not be identical
8727 // to the implicit argument list of the primary template.
8728 //
8729 // This rule has since been removed, because it's redundant given DR1495,
8730 // but we keep it because it produces better diagnostics and recovery.
8731 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8732 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8733 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8734 return CheckClassTemplate(
8735 S, TagSpec, TUK, KWLoc, SS, Name: ClassTemplate->getIdentifier(),
8736 NameLoc: TemplateNameLoc, Attr, TemplateParams, AS: AS_none,
8737 /*ModulePrivateLoc=*/SourceLocation(),
8738 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
8739 OuterTemplateParamLists: TemplateParameterLists.data());
8740 }
8741
8742 // Create a new class template partial specialization declaration node.
8743 ClassTemplatePartialSpecializationDecl *PrevPartial
8744 = cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl);
8745 ClassTemplatePartialSpecializationDecl *Partial =
8746 ClassTemplatePartialSpecializationDecl::Create(
8747 Context, TK: Kind, DC, StartLoc: KWLoc, IdLoc: TemplateNameLoc, Params: TemplateParams,
8748 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, CanonInjectedType: WrittenTy->getType(),
8749 PrevDecl: PrevPartial);
8750 Partial->setTemplateArgsAsWritten(TemplateArgs);
8751 SetNestedNameSpecifier(*this, Partial, SS);
8752 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8753 Partial->setTemplateParameterListsInfo(
8754 Context, TemplateParameterLists.drop_back(N: 1));
8755 }
8756
8757 if (!PrevPartial)
8758 ClassTemplate->AddPartialSpecialization(D: Partial, InsertPos);
8759 Specialization = Partial;
8760
8761 // If we are providing an explicit specialization of a member class
8762 // template specialization, make a note of that.
8763 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8764 PrevPartial->setMemberSpecialization();
8765
8766 CheckTemplatePartialSpecialization(Partial);
8767 }
8768
8769 // C++ [temp.expl.spec]p6:
8770 // If a template, a member template or the member of a class template is
8771 // explicitly specialized then that specialization shall be declared
8772 // before the first use of that specialization that would cause an implicit
8773 // instantiation to take place, in every translation unit in which such a
8774 // use occurs; no diagnostic is required.
8775 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8776 bool Okay = false;
8777 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8778 // Is there any previous explicit specialization declaration?
8779 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
8780 Okay = true;
8781 break;
8782 }
8783 }
8784
8785 if (!Okay) {
8786 SourceRange Range(TemplateNameLoc, RAngleLoc);
8787 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8788 << Context.getTypeDeclType(Specialization) << Range;
8789
8790 Diag(PrevDecl->getPointOfInstantiation(),
8791 diag::note_instantiation_required_here)
8792 << (PrevDecl->getTemplateSpecializationKind()
8793 != TSK_ImplicitInstantiation);
8794 return true;
8795 }
8796 }
8797
8798 // If this is not a friend, note that this is an explicit specialization.
8799 if (TUK != TagUseKind::Friend)
8800 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8801
8802 // Check that this isn't a redefinition of this specialization.
8803 if (TUK == TagUseKind::Definition) {
8804 RecordDecl *Def = Specialization->getDefinition();
8805 NamedDecl *Hidden = nullptr;
8806 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8807 SkipBody->ShouldSkip = true;
8808 SkipBody->Previous = Def;
8809 makeMergedDefinitionVisible(ND: Hidden);
8810 } else if (Def) {
8811 SourceRange Range(TemplateNameLoc, RAngleLoc);
8812 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8813 Diag(Def->getLocation(), diag::note_previous_definition);
8814 Specialization->setInvalidDecl();
8815 return true;
8816 }
8817 }
8818
8819 ProcessDeclAttributeList(S, Specialization, Attr);
8820 ProcessAPINotes(Specialization);
8821
8822 // Add alignment attributes if necessary; these attributes are checked when
8823 // the ASTContext lays out the structure.
8824 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8825 if (LangOpts.HLSL)
8826 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
8827 AddAlignmentAttributesForRecord(Specialization);
8828 AddMsStructLayoutForRecord(Specialization);
8829 }
8830
8831 if (ModulePrivateLoc.isValid())
8832 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8833 << (isPartialSpecialization? 1 : 0)
8834 << FixItHint::CreateRemoval(ModulePrivateLoc);
8835
8836 // C++ [temp.expl.spec]p9:
8837 // A template explicit specialization is in the scope of the
8838 // namespace in which the template was defined.
8839 //
8840 // We actually implement this paragraph where we set the semantic
8841 // context (in the creation of the ClassTemplateSpecializationDecl),
8842 // but we also maintain the lexical context where the actual
8843 // definition occurs.
8844 Specialization->setLexicalDeclContext(CurContext);
8845
8846 // We may be starting the definition of this specialization.
8847 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
8848 Specialization->startDefinition();
8849
8850 if (TUK == TagUseKind::Friend) {
8851 // Build the fully-sugared type for this class template
8852 // specialization as the user wrote in the specialization
8853 // itself. This means that we'll pretty-print the type retrieved
8854 // from the specialization's declaration the way that the user
8855 // actually wrote the specialization, rather than formatting the
8856 // name based on the "canonical" representation used to store the
8857 // template arguments in the specialization.
8858 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext,
8859 L: TemplateNameLoc,
8860 Friend_: WrittenTy,
8861 /*FIXME:*/FriendL: KWLoc);
8862 Friend->setAccess(AS_public);
8863 CurContext->addDecl(Friend);
8864 } else {
8865 // Add the specialization into its lexical context, so that it can
8866 // be seen when iterating through the list of declarations in that
8867 // context. However, specializations are not found by name lookup.
8868 CurContext->addDecl(Specialization);
8869 }
8870
8871 if (SkipBody && SkipBody->ShouldSkip)
8872 return SkipBody->Previous;
8873
8874 Specialization->setInvalidDecl(Invalid);
8875 inferGslOwnerPointerAttribute(Specialization);
8876 return Specialization;
8877}
8878
8879Decl *Sema::ActOnTemplateDeclarator(Scope *S,
8880 MultiTemplateParamsArg TemplateParameterLists,
8881 Declarator &D) {
8882 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8883 ActOnDocumentableDecl(D: NewDecl);
8884 return NewDecl;
8885}
8886
8887ConceptDecl *Sema::ActOnStartConceptDefinition(
8888 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8889 const IdentifierInfo *Name, SourceLocation NameLoc) {
8890 DeclContext *DC = CurContext;
8891
8892 if (!DC->getRedeclContext()->isFileContext()) {
8893 Diag(NameLoc,
8894 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8895 return nullptr;
8896 }
8897
8898 if (TemplateParameterLists.size() > 1) {
8899 Diag(NameLoc, diag::err_concept_extra_headers);
8900 return nullptr;
8901 }
8902
8903 TemplateParameterList *Params = TemplateParameterLists.front();
8904
8905 if (Params->size() == 0) {
8906 Diag(NameLoc, diag::err_concept_no_parameters);
8907 return nullptr;
8908 }
8909
8910 // Ensure that the parameter pack, if present, is the last parameter in the
8911 // template.
8912 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
8913 ParamEnd = Params->end();
8914 ParamIt != ParamEnd; ++ParamIt) {
8915 Decl const *Param = *ParamIt;
8916 if (Param->isParameterPack()) {
8917 if (++ParamIt == ParamEnd)
8918 break;
8919 Diag(Param->getLocation(),
8920 diag::err_template_param_pack_must_be_last_template_parameter);
8921 return nullptr;
8922 }
8923 }
8924
8925 ConceptDecl *NewDecl =
8926 ConceptDecl::Create(C&: Context, DC, L: NameLoc, Name, Params);
8927
8928 if (NewDecl->hasAssociatedConstraints()) {
8929 // C++2a [temp.concept]p4:
8930 // A concept shall not have associated constraints.
8931 Diag(NameLoc, diag::err_concept_no_associated_constraints);
8932 NewDecl->setInvalidDecl();
8933 }
8934
8935 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
8936 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8937 forRedeclarationInCurContext());
8938 LookupName(R&: Previous, S);
8939 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
8940 /*AllowInlineNamespace*/ false);
8941
8942 // We cannot properly handle redeclarations until we parse the constraint
8943 // expression, so only inject the name if we are sure we are not redeclaring a
8944 // symbol
8945 if (Previous.empty())
8946 PushOnScopeChains(NewDecl, S, true);
8947
8948 return NewDecl;
8949}
8950
8951static bool RemoveLookupResult(LookupResult &R, NamedDecl *C) {
8952 bool Found = false;
8953 LookupResult::Filter F = R.makeFilter();
8954 while (F.hasNext()) {
8955 NamedDecl *D = F.next();
8956 if (D == C) {
8957 F.erase();
8958 Found = true;
8959 break;
8960 }
8961 }
8962 F.done();
8963 return Found;
8964}
8965
8966ConceptDecl *
8967Sema::ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
8968 Expr *ConstraintExpr,
8969 const ParsedAttributesView &Attrs) {
8970 assert(!C->hasDefinition() && "Concept already defined");
8971 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr))
8972 return nullptr;
8973 C->setDefinition(ConstraintExpr);
8974 ProcessDeclAttributeList(S, C, Attrs);
8975
8976 // Check for conflicting previous declaration.
8977 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
8978 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8979 forRedeclarationInCurContext());
8980 LookupName(R&: Previous, S);
8981 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
8982 /*AllowInlineNamespace*/ false);
8983 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
8984 bool AddToScope = true;
8985 CheckConceptRedefinition(NewDecl: C, Previous, AddToScope);
8986
8987 ActOnDocumentableDecl(C);
8988 if (!WasAlreadyAdded && AddToScope)
8989 PushOnScopeChains(C, S);
8990
8991 return C;
8992}
8993
8994void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
8995 LookupResult &Previous, bool &AddToScope) {
8996 AddToScope = true;
8997
8998 if (Previous.empty())
8999 return;
9000
9001 auto *OldConcept = dyn_cast<ConceptDecl>(Val: Previous.getRepresentativeDecl()->getUnderlyingDecl());
9002 if (!OldConcept) {
9003 auto *Old = Previous.getRepresentativeDecl();
9004 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9005 << NewDecl->getDeclName();
9006 notePreviousDefinition(Old, New: NewDecl->getLocation());
9007 AddToScope = false;
9008 return;
9009 }
9010 // Check if we can merge with a concept declaration.
9011 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9012 if (!IsSame) {
9013 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9014 << NewDecl->getDeclName();
9015 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9016 AddToScope = false;
9017 return;
9018 }
9019 if (hasReachableDefinition(OldConcept) &&
9020 IsRedefinitionInModule(NewDecl, OldConcept)) {
9021 Diag(NewDecl->getLocation(), diag::err_redefinition)
9022 << NewDecl->getDeclName();
9023 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9024 AddToScope = false;
9025 return;
9026 }
9027 if (!Previous.isSingleResult()) {
9028 // FIXME: we should produce an error in case of ambig and failed lookups.
9029 // Other decls (e.g. namespaces) also have this shortcoming.
9030 return;
9031 }
9032 // We unwrap canonical decl late to check for module visibility.
9033 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9034}
9035
9036bool Sema::CheckConceptUseInDefinition(ConceptDecl *Concept,
9037 SourceLocation Loc) {
9038 if (!Concept->isInvalidDecl() && !Concept->hasDefinition()) {
9039 Diag(Loc, diag::err_recursive_concept) << Concept;
9040 Diag(Concept->getLocation(), diag::note_declared_at);
9041 return true;
9042 }
9043 return false;
9044}
9045
9046/// \brief Strips various properties off an implicit instantiation
9047/// that has just been explicitly specialized.
9048static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9049 if (MinGW || (isa<FunctionDecl>(D) &&
9050 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9051 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9052
9053 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D))
9054 FD->setInlineSpecified(false);
9055}
9056
9057/// Compute the diagnostic location for an explicit instantiation
9058// declaration or definition.
9059static SourceLocation DiagLocForExplicitInstantiation(
9060 NamedDecl* D, SourceLocation PointOfInstantiation) {
9061 // Explicit instantiations following a specialization have no effect and
9062 // hence no PointOfInstantiation. In that case, walk decl backwards
9063 // until a valid name loc is found.
9064 SourceLocation PrevDiagLoc = PointOfInstantiation;
9065 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9066 Prev = Prev->getPreviousDecl()) {
9067 PrevDiagLoc = Prev->getLocation();
9068 }
9069 assert(PrevDiagLoc.isValid() &&
9070 "Explicit instantiation without point of instantiation?");
9071 return PrevDiagLoc;
9072}
9073
9074bool
9075Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9076 TemplateSpecializationKind NewTSK,
9077 NamedDecl *PrevDecl,
9078 TemplateSpecializationKind PrevTSK,
9079 SourceLocation PrevPointOfInstantiation,
9080 bool &HasNoEffect) {
9081 HasNoEffect = false;
9082
9083 switch (NewTSK) {
9084 case TSK_Undeclared:
9085 case TSK_ImplicitInstantiation:
9086 assert(
9087 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9088 "previous declaration must be implicit!");
9089 return false;
9090
9091 case TSK_ExplicitSpecialization:
9092 switch (PrevTSK) {
9093 case TSK_Undeclared:
9094 case TSK_ExplicitSpecialization:
9095 // Okay, we're just specializing something that is either already
9096 // explicitly specialized or has merely been mentioned without any
9097 // instantiation.
9098 return false;
9099
9100 case TSK_ImplicitInstantiation:
9101 if (PrevPointOfInstantiation.isInvalid()) {
9102 // The declaration itself has not actually been instantiated, so it is
9103 // still okay to specialize it.
9104 StripImplicitInstantiation(
9105 D: PrevDecl, MinGW: Context.getTargetInfo().getTriple().isOSCygMing());
9106 return false;
9107 }
9108 // Fall through
9109 [[fallthrough]];
9110
9111 case TSK_ExplicitInstantiationDeclaration:
9112 case TSK_ExplicitInstantiationDefinition:
9113 assert((PrevTSK == TSK_ImplicitInstantiation ||
9114 PrevPointOfInstantiation.isValid()) &&
9115 "Explicit instantiation without point of instantiation?");
9116
9117 // C++ [temp.expl.spec]p6:
9118 // If a template, a member template or the member of a class template
9119 // is explicitly specialized then that specialization shall be declared
9120 // before the first use of that specialization that would cause an
9121 // implicit instantiation to take place, in every translation unit in
9122 // which such a use occurs; no diagnostic is required.
9123 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9124 // Is there any previous explicit specialization declaration?
9125 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization)
9126 return false;
9127 }
9128
9129 Diag(NewLoc, diag::err_specialization_after_instantiation)
9130 << PrevDecl;
9131 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9132 << (PrevTSK != TSK_ImplicitInstantiation);
9133
9134 return true;
9135 }
9136 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9137
9138 case TSK_ExplicitInstantiationDeclaration:
9139 switch (PrevTSK) {
9140 case TSK_ExplicitInstantiationDeclaration:
9141 // This explicit instantiation declaration is redundant (that's okay).
9142 HasNoEffect = true;
9143 return false;
9144
9145 case TSK_Undeclared:
9146 case TSK_ImplicitInstantiation:
9147 // We're explicitly instantiating something that may have already been
9148 // implicitly instantiated; that's fine.
9149 return false;
9150
9151 case TSK_ExplicitSpecialization:
9152 // C++0x [temp.explicit]p4:
9153 // For a given set of template parameters, if an explicit instantiation
9154 // of a template appears after a declaration of an explicit
9155 // specialization for that template, the explicit instantiation has no
9156 // effect.
9157 HasNoEffect = true;
9158 return false;
9159
9160 case TSK_ExplicitInstantiationDefinition:
9161 // C++0x [temp.explicit]p10:
9162 // If an entity is the subject of both an explicit instantiation
9163 // declaration and an explicit instantiation definition in the same
9164 // translation unit, the definition shall follow the declaration.
9165 Diag(NewLoc,
9166 diag::err_explicit_instantiation_declaration_after_definition);
9167
9168 // Explicit instantiations following a specialization have no effect and
9169 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9170 // until a valid name loc is found.
9171 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9172 diag::note_explicit_instantiation_definition_here);
9173 HasNoEffect = true;
9174 return false;
9175 }
9176 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9177
9178 case TSK_ExplicitInstantiationDefinition:
9179 switch (PrevTSK) {
9180 case TSK_Undeclared:
9181 case TSK_ImplicitInstantiation:
9182 // We're explicitly instantiating something that may have already been
9183 // implicitly instantiated; that's fine.
9184 return false;
9185
9186 case TSK_ExplicitSpecialization:
9187 // C++ DR 259, C++0x [temp.explicit]p4:
9188 // For a given set of template parameters, if an explicit
9189 // instantiation of a template appears after a declaration of
9190 // an explicit specialization for that template, the explicit
9191 // instantiation has no effect.
9192 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9193 << PrevDecl;
9194 Diag(PrevDecl->getLocation(),
9195 diag::note_previous_template_specialization);
9196 HasNoEffect = true;
9197 return false;
9198
9199 case TSK_ExplicitInstantiationDeclaration:
9200 // We're explicitly instantiating a definition for something for which we
9201 // were previously asked to suppress instantiations. That's fine.
9202
9203 // C++0x [temp.explicit]p4:
9204 // For a given set of template parameters, if an explicit instantiation
9205 // of a template appears after a declaration of an explicit
9206 // specialization for that template, the explicit instantiation has no
9207 // effect.
9208 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9209 // Is there any previous explicit specialization declaration?
9210 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9211 HasNoEffect = true;
9212 break;
9213 }
9214 }
9215
9216 return false;
9217
9218 case TSK_ExplicitInstantiationDefinition:
9219 // C++0x [temp.spec]p5:
9220 // For a given template and a given set of template-arguments,
9221 // - an explicit instantiation definition shall appear at most once
9222 // in a program,
9223
9224 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9225 Diag(NewLoc, (getLangOpts().MSVCCompat)
9226 ? diag::ext_explicit_instantiation_duplicate
9227 : diag::err_explicit_instantiation_duplicate)
9228 << PrevDecl;
9229 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9230 diag::note_previous_explicit_instantiation);
9231 HasNoEffect = true;
9232 return false;
9233 }
9234 }
9235
9236 llvm_unreachable("Missing specialization/instantiation case?");
9237}
9238
9239bool Sema::CheckDependentFunctionTemplateSpecialization(
9240 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9241 LookupResult &Previous) {
9242 // Remove anything from Previous that isn't a function template in
9243 // the correct context.
9244 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9245 LookupResult::Filter F = Previous.makeFilter();
9246 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9247 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9248 while (F.hasNext()) {
9249 NamedDecl *D = F.next()->getUnderlyingDecl();
9250 if (!isa<FunctionTemplateDecl>(Val: D)) {
9251 F.erase();
9252 DiscardedCandidates.push_back(std::make_pair(x: NotAFunctionTemplate, y&: D));
9253 continue;
9254 }
9255
9256 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9257 NS: D->getDeclContext()->getRedeclContext())) {
9258 F.erase();
9259 DiscardedCandidates.push_back(std::make_pair(x: NotAMemberOfEnclosing, y&: D));
9260 continue;
9261 }
9262 }
9263 F.done();
9264
9265 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9266 if (Previous.empty()) {
9267 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9268 << IsFriend;
9269 for (auto &P : DiscardedCandidates)
9270 Diag(P.second->getLocation(),
9271 diag::note_dependent_function_template_spec_discard_reason)
9272 << P.first << IsFriend;
9273 return true;
9274 }
9275
9276 FD->setDependentTemplateSpecialization(Context, Templates: Previous.asUnresolvedSet(),
9277 TemplateArgs: ExplicitTemplateArgs);
9278 return false;
9279}
9280
9281bool Sema::CheckFunctionTemplateSpecialization(
9282 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9283 LookupResult &Previous, bool QualifiedFriend) {
9284 // The set of function template specializations that could match this
9285 // explicit function template specialization.
9286 UnresolvedSet<8> Candidates;
9287 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9288 /*ForTakingAddress=*/false);
9289
9290 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9291 ConvertedTemplateArgs;
9292
9293 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9294 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9295 I != E; ++I) {
9296 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9297 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Ovl)) {
9298 // Only consider templates found within the same semantic lookup scope as
9299 // FD.
9300 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9301 NS: Ovl->getDeclContext()->getRedeclContext()))
9302 continue;
9303
9304 QualType FT = FD->getType();
9305 // C++11 [dcl.constexpr]p8:
9306 // A constexpr specifier for a non-static member function that is not
9307 // a constructor declares that member function to be const.
9308 //
9309 // When matching a constexpr member function template specialization
9310 // against the primary template, we don't yet know whether the
9311 // specialization has an implicit 'const' (because we don't know whether
9312 // it will be a static member function until we know which template it
9313 // specializes). This rule was removed in C++14.
9314 if (auto *NewMD = dyn_cast<CXXMethodDecl>(Val: FD);
9315 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9316 !isa<CXXConstructorDecl, CXXDestructorDecl>(Val: NewMD)) {
9317 auto *OldMD = dyn_cast<CXXMethodDecl>(Val: FunTmpl->getTemplatedDecl());
9318 if (OldMD && OldMD->isConst()) {
9319 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9320 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9321 EPI.TypeQuals.addConst();
9322 FT = Context.getFunctionType(ResultTy: FPT->getReturnType(),
9323 Args: FPT->getParamTypes(), EPI);
9324 }
9325 }
9326
9327 TemplateArgumentListInfo Args;
9328 if (ExplicitTemplateArgs)
9329 Args = *ExplicitTemplateArgs;
9330
9331 // C++ [temp.expl.spec]p11:
9332 // A trailing template-argument can be left unspecified in the
9333 // template-id naming an explicit function template specialization
9334 // provided it can be deduced from the function argument type.
9335 // Perform template argument deduction to determine whether we may be
9336 // specializing this template.
9337 // FIXME: It is somewhat wasteful to build
9338 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9339 FunctionDecl *Specialization = nullptr;
9340 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9341 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9342 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9343 TDK != TemplateDeductionResult::Success) {
9344 // Template argument deduction failed; record why it failed, so
9345 // that we can provide nifty diagnostics.
9346 FailedCandidates.addCandidate().set(
9347 I.getPair(), FunTmpl->getTemplatedDecl(),
9348 MakeDeductionFailureInfo(Context, TDK, Info));
9349 (void)TDK;
9350 continue;
9351 }
9352
9353 // Target attributes are part of the cuda function signature, so
9354 // the deduced template's cuda target must match that of the
9355 // specialization. Given that C++ template deduction does not
9356 // take target attributes into account, we reject candidates
9357 // here that have a different target.
9358 if (LangOpts.CUDA &&
9359 CUDA().IdentifyTarget(D: Specialization,
9360 /* IgnoreImplicitHDAttr = */ true) !=
9361 CUDA().IdentifyTarget(D: FD, /* IgnoreImplicitHDAttr = */ true)) {
9362 FailedCandidates.addCandidate().set(
9363 I.getPair(), FunTmpl->getTemplatedDecl(),
9364 MakeDeductionFailureInfo(
9365 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
9366 continue;
9367 }
9368
9369 // Record this candidate.
9370 if (ExplicitTemplateArgs)
9371 ConvertedTemplateArgs[Specialization] = std::move(Args);
9372 Candidates.addDecl(Specialization, I.getAccess());
9373 }
9374 }
9375
9376 // For a qualified friend declaration (with no explicit marker to indicate
9377 // that a template specialization was intended), note all (template and
9378 // non-template) candidates.
9379 if (QualifiedFriend && Candidates.empty()) {
9380 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9381 << FD->getDeclName() << FDLookupContext;
9382 // FIXME: We should form a single candidate list and diagnose all
9383 // candidates at once, to get proper sorting and limiting.
9384 for (auto *OldND : Previous) {
9385 if (auto *OldFD = dyn_cast<FunctionDecl>(Val: OldND->getUnderlyingDecl()))
9386 NoteOverloadCandidate(Found: OldND, Fn: OldFD, RewriteKind: CRK_None, DestType: FD->getType(), TakingAddress: false);
9387 }
9388 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9389 return true;
9390 }
9391
9392 // Find the most specialized function template.
9393 UnresolvedSetIterator Result = getMostSpecialized(
9394 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9395 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9396 PDiag(diag::err_function_template_spec_ambiguous)
9397 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9398 PDiag(diag::note_function_template_spec_matched));
9399
9400 if (Result == Candidates.end())
9401 return true;
9402
9403 // Ignore access information; it doesn't figure into redeclaration checking.
9404 FunctionDecl *Specialization = cast<FunctionDecl>(Val: *Result);
9405
9406 if (const auto *PT = Specialization->getPrimaryTemplate();
9407 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9408 auto Message = DSA->getMessage();
9409 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9410 << PT << !Message.empty() << Message;
9411 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9412 }
9413
9414 // C++23 [except.spec]p13:
9415 // An exception specification is considered to be needed when:
9416 // - [...]
9417 // - the exception specification is compared to that of another declaration
9418 // (e.g., an explicit specialization or an overriding virtual function);
9419 // - [...]
9420 //
9421 // The exception specification of a defaulted function is evaluated as
9422 // described above only when needed; similarly, the noexcept-specifier of a
9423 // specialization of a function template or member function of a class
9424 // template is instantiated only when needed.
9425 //
9426 // The standard doesn't specify what the "comparison with another declaration"
9427 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9428 // not state which properties of an explicit specialization must match the
9429 // primary template.
9430 //
9431 // We assume that an explicit specialization must correspond with (per
9432 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9433 // the declaration produced by substitution into the function template.
9434 //
9435 // Since the determination whether two function declarations correspond does
9436 // not consider exception specification, we only need to instantiate it once
9437 // we determine the primary template when comparing types per
9438 // [basic.link]p11.1.
9439 auto *SpecializationFPT =
9440 Specialization->getType()->castAs<FunctionProtoType>();
9441 // If the function has a dependent exception specification, resolve it after
9442 // we have selected the primary template so we can check whether it matches.
9443 if (getLangOpts().CPlusPlus17 &&
9444 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9445 !ResolveExceptionSpec(Loc: FD->getLocation(), FPT: SpecializationFPT))
9446 return true;
9447
9448 FunctionTemplateSpecializationInfo *SpecInfo
9449 = Specialization->getTemplateSpecializationInfo();
9450 assert(SpecInfo && "Function template specialization info missing?");
9451
9452 // Note: do not overwrite location info if previous template
9453 // specialization kind was explicit.
9454 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9455 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9456 Specialization->setLocation(FD->getLocation());
9457 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9458 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9459 // function can differ from the template declaration with respect to
9460 // the constexpr specifier.
9461 // FIXME: We need an update record for this AST mutation.
9462 // FIXME: What if there are multiple such prior declarations (for instance,
9463 // from different modules)?
9464 Specialization->setConstexprKind(FD->getConstexprKind());
9465 }
9466
9467 // FIXME: Check if the prior specialization has a point of instantiation.
9468 // If so, we have run afoul of .
9469
9470 // If this is a friend declaration, then we're not really declaring
9471 // an explicit specialization.
9472 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9473
9474 // Check the scope of this explicit specialization.
9475 if (!isFriend &&
9476 CheckTemplateSpecializationScope(*this,
9477 Specialization->getPrimaryTemplate(),
9478 Specialization, FD->getLocation(),
9479 false))
9480 return true;
9481
9482 // C++ [temp.expl.spec]p6:
9483 // If a template, a member template or the member of a class template is
9484 // explicitly specialized then that specialization shall be declared
9485 // before the first use of that specialization that would cause an implicit
9486 // instantiation to take place, in every translation unit in which such a
9487 // use occurs; no diagnostic is required.
9488 bool HasNoEffect = false;
9489 if (!isFriend &&
9490 CheckSpecializationInstantiationRedecl(NewLoc: FD->getLocation(),
9491 NewTSK: TSK_ExplicitSpecialization,
9492 PrevDecl: Specialization,
9493 PrevTSK: SpecInfo->getTemplateSpecializationKind(),
9494 PrevPointOfInstantiation: SpecInfo->getPointOfInstantiation(),
9495 HasNoEffect))
9496 return true;
9497
9498 // Mark the prior declaration as an explicit specialization, so that later
9499 // clients know that this is an explicit specialization.
9500 // A dependent friend specialization which has a definition should be treated
9501 // as explicit specialization, despite being invalid.
9502 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9503 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9504 // Since explicit specializations do not inherit '=delete' from their
9505 // primary function template - check if the 'specialization' that was
9506 // implicitly generated (during template argument deduction for partial
9507 // ordering) from the most specialized of all the function templates that
9508 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9509 // first check that it was implicitly generated during template argument
9510 // deduction by making sure it wasn't referenced, and then reset the deleted
9511 // flag to not-deleted, so that we can inherit that information from 'FD'.
9512 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9513 !Specialization->getCanonicalDecl()->isReferenced()) {
9514 // FIXME: This assert will not hold in the presence of modules.
9515 assert(
9516 Specialization->getCanonicalDecl() == Specialization &&
9517 "This must be the only existing declaration of this specialization");
9518 // FIXME: We need an update record for this AST mutation.
9519 Specialization->setDeletedAsWritten(D: false);
9520 }
9521 // FIXME: We need an update record for this AST mutation.
9522 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9523 MarkUnusedFileScopedDecl(Specialization);
9524 }
9525
9526 // Turn the given function declaration into a function template
9527 // specialization, with the template arguments from the previous
9528 // specialization.
9529 // Take copies of (semantic and syntactic) template argument lists.
9530 TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
9531 Context, Args: Specialization->getTemplateSpecializationArgs()->asArray());
9532 FD->setFunctionTemplateSpecialization(
9533 Template: Specialization->getPrimaryTemplate(), TemplateArgs: TemplArgs, /*InsertPos=*/nullptr,
9534 TSK: SpecInfo->getTemplateSpecializationKind(),
9535 TemplateArgsAsWritten: ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9536
9537 // A function template specialization inherits the target attributes
9538 // of its template. (We require the attributes explicitly in the
9539 // code to match, but a template may have implicit attributes by
9540 // virtue e.g. of being constexpr, and it passes these implicit
9541 // attributes on to its specializations.)
9542 if (LangOpts.CUDA)
9543 CUDA().inheritTargetAttrs(FD, TD: *Specialization->getPrimaryTemplate());
9544
9545 // The "previous declaration" for this function template specialization is
9546 // the prior function template specialization.
9547 Previous.clear();
9548 Previous.addDecl(Specialization);
9549 return false;
9550}
9551
9552bool
9553Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9554 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9555 "Only for non-template members");
9556
9557 // Try to find the member we are instantiating.
9558 NamedDecl *FoundInstantiation = nullptr;
9559 NamedDecl *Instantiation = nullptr;
9560 NamedDecl *InstantiatedFrom = nullptr;
9561 MemberSpecializationInfo *MSInfo = nullptr;
9562
9563 if (Previous.empty()) {
9564 // Nowhere to look anyway.
9565 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Member)) {
9566 UnresolvedSet<8> Candidates;
9567 for (NamedDecl *Candidate : Previous) {
9568 auto *Method = dyn_cast<CXXMethodDecl>(Val: Candidate->getUnderlyingDecl());
9569 // Ignore any candidates that aren't member functions.
9570 if (!Method)
9571 continue;
9572
9573 QualType Adjusted = Function->getType();
9574 if (!hasExplicitCallingConv(T: Adjusted))
9575 Adjusted = adjustCCAndNoReturn(ArgFunctionType: Adjusted, FunctionType: Method->getType());
9576 // Ignore any candidates with the wrong type.
9577 // This doesn't handle deduced return types, but both function
9578 // declarations should be undeduced at this point.
9579 // FIXME: The exception specification should probably be ignored when
9580 // comparing the types.
9581 if (!Context.hasSameType(Adjusted, Method->getType()))
9582 continue;
9583
9584 // Ignore any candidates with unsatisfied constraints.
9585 if (ConstraintSatisfaction Satisfaction;
9586 Method->getTrailingRequiresClause() &&
9587 (CheckFunctionConstraints(FD: Method, Satisfaction,
9588 /*UsageLoc=*/Member->getLocation(),
9589 /*ForOverloadResolution=*/true) ||
9590 !Satisfaction.IsSatisfied))
9591 continue;
9592
9593 Candidates.addDecl(D: Candidate);
9594 }
9595
9596 // If we have no viable candidates left after filtering, we are done.
9597 if (Candidates.empty())
9598 return false;
9599
9600 // Find the function that is more constrained than every other function it
9601 // has been compared to.
9602 UnresolvedSetIterator Best = Candidates.begin();
9603 CXXMethodDecl *BestMethod = nullptr;
9604 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9605 I != E; ++I) {
9606 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9607 if (I == Best ||
9608 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9609 Best = I;
9610 BestMethod = Method;
9611 }
9612 }
9613
9614 FoundInstantiation = *Best;
9615 Instantiation = BestMethod;
9616 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9617 MSInfo = BestMethod->getMemberSpecializationInfo();
9618
9619 // Make sure the best candidate is more constrained than all of the others.
9620 bool Ambiguous = false;
9621 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9622 I != E; ++I) {
9623 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9624 if (I != Best &&
9625 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9626 Ambiguous = true;
9627 break;
9628 }
9629 }
9630
9631 if (Ambiguous) {
9632 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9633 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9634 for (NamedDecl *Candidate : Candidates) {
9635 Candidate = Candidate->getUnderlyingDecl();
9636 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9637 << Candidate;
9638 }
9639 return true;
9640 }
9641 } else if (isa<VarDecl>(Val: Member)) {
9642 VarDecl *PrevVar;
9643 if (Previous.isSingleResult() &&
9644 (PrevVar = dyn_cast<VarDecl>(Val: Previous.getFoundDecl())))
9645 if (PrevVar->isStaticDataMember()) {
9646 FoundInstantiation = Previous.getRepresentativeDecl();
9647 Instantiation = PrevVar;
9648 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9649 MSInfo = PrevVar->getMemberSpecializationInfo();
9650 }
9651 } else if (isa<RecordDecl>(Val: Member)) {
9652 CXXRecordDecl *PrevRecord;
9653 if (Previous.isSingleResult() &&
9654 (PrevRecord = dyn_cast<CXXRecordDecl>(Val: Previous.getFoundDecl()))) {
9655 FoundInstantiation = Previous.getRepresentativeDecl();
9656 Instantiation = PrevRecord;
9657 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9658 MSInfo = PrevRecord->getMemberSpecializationInfo();
9659 }
9660 } else if (isa<EnumDecl>(Val: Member)) {
9661 EnumDecl *PrevEnum;
9662 if (Previous.isSingleResult() &&
9663 (PrevEnum = dyn_cast<EnumDecl>(Val: Previous.getFoundDecl()))) {
9664 FoundInstantiation = Previous.getRepresentativeDecl();
9665 Instantiation = PrevEnum;
9666 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9667 MSInfo = PrevEnum->getMemberSpecializationInfo();
9668 }
9669 }
9670
9671 if (!Instantiation) {
9672 // There is no previous declaration that matches. Since member
9673 // specializations are always out-of-line, the caller will complain about
9674 // this mismatch later.
9675 return false;
9676 }
9677
9678 // A member specialization in a friend declaration isn't really declaring
9679 // an explicit specialization, just identifying a specific (possibly implicit)
9680 // specialization. Don't change the template specialization kind.
9681 //
9682 // FIXME: Is this really valid? Other compilers reject.
9683 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9684 // Preserve instantiation information.
9685 if (InstantiatedFrom && isa<CXXMethodDecl>(Val: Member)) {
9686 cast<CXXMethodDecl>(Val: Member)->setInstantiationOfMemberFunction(
9687 cast<CXXMethodDecl>(Val: InstantiatedFrom),
9688 cast<CXXMethodDecl>(Val: Instantiation)->getTemplateSpecializationKind());
9689 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Val: Member)) {
9690 cast<CXXRecordDecl>(Val: Member)->setInstantiationOfMemberClass(
9691 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom),
9692 TSK: cast<CXXRecordDecl>(Val: Instantiation)->getTemplateSpecializationKind());
9693 }
9694
9695 Previous.clear();
9696 Previous.addDecl(D: FoundInstantiation);
9697 return false;
9698 }
9699
9700 // Make sure that this is a specialization of a member.
9701 if (!InstantiatedFrom) {
9702 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9703 << Member;
9704 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9705 return true;
9706 }
9707
9708 // C++ [temp.expl.spec]p6:
9709 // If a template, a member template or the member of a class template is
9710 // explicitly specialized then that specialization shall be declared
9711 // before the first use of that specialization that would cause an implicit
9712 // instantiation to take place, in every translation unit in which such a
9713 // use occurs; no diagnostic is required.
9714 assert(MSInfo && "Member specialization info missing?");
9715
9716 bool HasNoEffect = false;
9717 if (CheckSpecializationInstantiationRedecl(NewLoc: Member->getLocation(),
9718 NewTSK: TSK_ExplicitSpecialization,
9719 PrevDecl: Instantiation,
9720 PrevTSK: MSInfo->getTemplateSpecializationKind(),
9721 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
9722 HasNoEffect))
9723 return true;
9724
9725 // Check the scope of this explicit specialization.
9726 if (CheckTemplateSpecializationScope(*this,
9727 InstantiatedFrom,
9728 Instantiation, Member->getLocation(),
9729 false))
9730 return true;
9731
9732 // Note that this member specialization is an "instantiation of" the
9733 // corresponding member of the original template.
9734 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Val: Member)) {
9735 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Val: Instantiation);
9736 if (InstantiationFunction->getTemplateSpecializationKind() ==
9737 TSK_ImplicitInstantiation) {
9738 // Explicit specializations of member functions of class templates do not
9739 // inherit '=delete' from the member function they are specializing.
9740 if (InstantiationFunction->isDeleted()) {
9741 // FIXME: This assert will not hold in the presence of modules.
9742 assert(InstantiationFunction->getCanonicalDecl() ==
9743 InstantiationFunction);
9744 // FIXME: We need an update record for this AST mutation.
9745 InstantiationFunction->setDeletedAsWritten(D: false);
9746 }
9747 }
9748
9749 MemberFunction->setInstantiationOfMemberFunction(
9750 cast<CXXMethodDecl>(Val: InstantiatedFrom), TSK_ExplicitSpecialization);
9751 } else if (auto *MemberVar = dyn_cast<VarDecl>(Val: Member)) {
9752 MemberVar->setInstantiationOfStaticDataMember(
9753 VD: cast<VarDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
9754 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
9755 MemberClass->setInstantiationOfMemberClass(
9756 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
9757 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Val: Member)) {
9758 MemberEnum->setInstantiationOfMemberEnum(
9759 ED: cast<EnumDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
9760 } else {
9761 llvm_unreachable("unknown member specialization kind");
9762 }
9763
9764 // Save the caller the trouble of having to figure out which declaration
9765 // this specialization matches.
9766 Previous.clear();
9767 Previous.addDecl(D: FoundInstantiation);
9768 return false;
9769}
9770
9771/// Complete the explicit specialization of a member of a class template by
9772/// updating the instantiated member to be marked as an explicit specialization.
9773///
9774/// \param OrigD The member declaration instantiated from the template.
9775/// \param Loc The location of the explicit specialization of the member.
9776template<typename DeclT>
9777static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9778 SourceLocation Loc) {
9779 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9780 return;
9781
9782 // FIXME: Inform AST mutation listeners of this AST mutation.
9783 // FIXME: If there are multiple in-class declarations of the member (from
9784 // multiple modules, or a declaration and later definition of a member type),
9785 // should we update all of them?
9786 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9787 OrigD->setLocation(Loc);
9788}
9789
9790void Sema::CompleteMemberSpecialization(NamedDecl *Member,
9791 LookupResult &Previous) {
9792 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9793 if (Instantiation == Member)
9794 return;
9795
9796 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9797 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9798 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9799 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9800 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9801 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9802 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9803 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9804 else
9805 llvm_unreachable("unknown member specialization kind");
9806}
9807
9808/// Check the scope of an explicit instantiation.
9809///
9810/// \returns true if a serious error occurs, false otherwise.
9811static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
9812 SourceLocation InstLoc,
9813 bool WasQualifiedName) {
9814 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
9815 DeclContext *CurContext = S.CurContext->getRedeclContext();
9816
9817 if (CurContext->isRecord()) {
9818 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9819 << D;
9820 return true;
9821 }
9822
9823 // C++11 [temp.explicit]p3:
9824 // An explicit instantiation shall appear in an enclosing namespace of its
9825 // template. If the name declared in the explicit instantiation is an
9826 // unqualified name, the explicit instantiation shall appear in the
9827 // namespace where its template is declared or, if that namespace is inline
9828 // (7.3.1), any namespace from its enclosing namespace set.
9829 //
9830 // This is DR275, which we do not retroactively apply to C++98/03.
9831 if (WasQualifiedName) {
9832 if (CurContext->Encloses(DC: OrigContext))
9833 return false;
9834 } else {
9835 if (CurContext->InEnclosingNamespaceSetOf(NS: OrigContext))
9836 return false;
9837 }
9838
9839 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: OrigContext)) {
9840 if (WasQualifiedName)
9841 S.Diag(InstLoc,
9842 S.getLangOpts().CPlusPlus11?
9843 diag::err_explicit_instantiation_out_of_scope :
9844 diag::warn_explicit_instantiation_out_of_scope_0x)
9845 << D << NS;
9846 else
9847 S.Diag(InstLoc,
9848 S.getLangOpts().CPlusPlus11?
9849 diag::err_explicit_instantiation_unqualified_wrong_namespace :
9850 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9851 << D << NS;
9852 } else
9853 S.Diag(InstLoc,
9854 S.getLangOpts().CPlusPlus11?
9855 diag::err_explicit_instantiation_must_be_global :
9856 diag::warn_explicit_instantiation_must_be_global_0x)
9857 << D;
9858 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9859 return false;
9860}
9861
9862/// Common checks for whether an explicit instantiation of \p D is valid.
9863static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
9864 SourceLocation InstLoc,
9865 bool WasQualifiedName,
9866 TemplateSpecializationKind TSK) {
9867 // C++ [temp.explicit]p13:
9868 // An explicit instantiation declaration shall not name a specialization of
9869 // a template with internal linkage.
9870 if (TSK == TSK_ExplicitInstantiationDeclaration &&
9871 D->getFormalLinkage() == Linkage::Internal) {
9872 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9873 return true;
9874 }
9875
9876 // C++11 [temp.explicit]p3: [DR 275]
9877 // An explicit instantiation shall appear in an enclosing namespace of its
9878 // template.
9879 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9880 return true;
9881
9882 return false;
9883}
9884
9885/// Determine whether the given scope specifier has a template-id in it.
9886static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
9887 if (!SS.isSet())
9888 return false;
9889
9890 // C++11 [temp.explicit]p3:
9891 // If the explicit instantiation is for a member function, a member class
9892 // or a static data member of a class template specialization, the name of
9893 // the class template specialization in the qualified-id for the member
9894 // name shall be a simple-template-id.
9895 //
9896 // C++98 has the same restriction, just worded differently.
9897 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9898 NNS = NNS->getPrefix())
9899 if (const Type *T = NNS->getAsType())
9900 if (isa<TemplateSpecializationType>(Val: T))
9901 return true;
9902
9903 return false;
9904}
9905
9906/// Make a dllexport or dllimport attr on a class template specialization take
9907/// effect.
9908static void dllExportImportClassTemplateSpecialization(
9909 Sema &S, ClassTemplateSpecializationDecl *Def) {
9910 auto *A = cast_or_null<InheritableAttr>(Val: getDLLAttr(Def));
9911 assert(A && "dllExportImportClassTemplateSpecialization called "
9912 "on Def without dllexport or dllimport");
9913
9914 // We reject explicit instantiations in class scope, so there should
9915 // never be any delayed exported classes to worry about.
9916 assert(S.DelayedDllExportClasses.empty() &&
9917 "delayed exports present at explicit instantiation");
9918 S.checkClassLevelDLLAttribute(Def);
9919
9920 // Propagate attribute to base class templates.
9921 for (auto &B : Def->bases()) {
9922 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9923 B.getType()->getAsCXXRecordDecl()))
9924 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
9925 }
9926
9927 S.referenceDLLExportedClassMethods();
9928}
9929
9930DeclResult Sema::ActOnExplicitInstantiation(
9931 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9932 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9933 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9934 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9935 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9936 // Find the class template we're specializing
9937 TemplateName Name = TemplateD.get();
9938 TemplateDecl *TD = Name.getAsTemplateDecl();
9939 // Check that the specialization uses the same tag kind as the
9940 // original template.
9941 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
9942 assert(Kind != TagTypeKind::Enum &&
9943 "Invalid enum tag in class template explicit instantiation!");
9944
9945 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: TD);
9946
9947 if (!ClassTemplate) {
9948 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9949 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
9950 Diag(TD->getLocation(), diag::note_previous_use);
9951 return true;
9952 }
9953
9954 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(),
9955 NewTag: Kind, /*isDefinition*/false, NewTagLoc: KWLoc,
9956 Name: ClassTemplate->getIdentifier())) {
9957 Diag(KWLoc, diag::err_use_with_wrong_tag)
9958 << ClassTemplate
9959 << FixItHint::CreateReplacement(KWLoc,
9960 ClassTemplate->getTemplatedDecl()->getKindName());
9961 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9962 diag::note_previous_use);
9963 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9964 }
9965
9966 // C++0x [temp.explicit]p2:
9967 // There are two forms of explicit instantiation: an explicit instantiation
9968 // definition and an explicit instantiation declaration. An explicit
9969 // instantiation declaration begins with the extern keyword. [...]
9970 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9971 ? TSK_ExplicitInstantiationDefinition
9972 : TSK_ExplicitInstantiationDeclaration;
9973
9974 if (TSK == TSK_ExplicitInstantiationDeclaration &&
9975 !Context.getTargetInfo().getTriple().isOSCygMing()) {
9976 // Check for dllexport class template instantiation declarations,
9977 // except for MinGW mode.
9978 for (const ParsedAttr &AL : Attr) {
9979 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9980 Diag(ExternLoc,
9981 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9982 Diag(AL.getLoc(), diag::note_attribute);
9983 break;
9984 }
9985 }
9986
9987 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9988 Diag(ExternLoc,
9989 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9990 Diag(A->getLocation(), diag::note_attribute);
9991 }
9992 }
9993
9994 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9995 // instantiation declarations for most purposes.
9996 bool DLLImportExplicitInstantiationDef = false;
9997 if (TSK == TSK_ExplicitInstantiationDefinition &&
9998 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9999 // Check for dllimport class template instantiation definitions.
10000 bool DLLImport =
10001 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10002 for (const ParsedAttr &AL : Attr) {
10003 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10004 DLLImport = true;
10005 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10006 // dllexport trumps dllimport here.
10007 DLLImport = false;
10008 break;
10009 }
10010 }
10011 if (DLLImport) {
10012 TSK = TSK_ExplicitInstantiationDeclaration;
10013 DLLImportExplicitInstantiationDef = true;
10014 }
10015 }
10016
10017 // Translate the parser's template argument list in our AST format.
10018 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10019 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10020
10021 // Check that the template argument list is well-formed for this
10022 // template.
10023 CheckTemplateArgumentInfo CTAI;
10024 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10025 /*DefaultArgs=*/{}, false, CTAI,
10026 /*UpdateArgsWithConversions=*/true,
10027 /*ConstraintsNotSatisfied=*/nullptr))
10028 return true;
10029
10030 // Find the class template specialization declaration that
10031 // corresponds to these arguments.
10032 void *InsertPos = nullptr;
10033 ClassTemplateSpecializationDecl *PrevDecl =
10034 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
10035
10036 TemplateSpecializationKind PrevDecl_TSK
10037 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10038
10039 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10040 Context.getTargetInfo().getTriple().isOSCygMing()) {
10041 // Check for dllexport class template instantiation definitions in MinGW
10042 // mode, if a previous declaration of the instantiation was seen.
10043 for (const ParsedAttr &AL : Attr) {
10044 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10045 Diag(AL.getLoc(),
10046 diag::warn_attribute_dllexport_explicit_instantiation_def);
10047 break;
10048 }
10049 }
10050 }
10051
10052 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10053 SS.isSet(), TSK))
10054 return true;
10055
10056 ClassTemplateSpecializationDecl *Specialization = nullptr;
10057
10058 bool HasNoEffect = false;
10059 if (PrevDecl) {
10060 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10061 PrevDecl, PrevDecl_TSK,
10062 PrevDecl->getPointOfInstantiation(),
10063 HasNoEffect))
10064 return PrevDecl;
10065
10066 // Even though HasNoEffect == true means that this explicit instantiation
10067 // has no effect on semantics, we go on to put its syntax in the AST.
10068
10069 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10070 PrevDecl_TSK == TSK_Undeclared) {
10071 // Since the only prior class template specialization with these
10072 // arguments was referenced but not declared, reuse that
10073 // declaration node as our own, updating the source location
10074 // for the template name to reflect our new declaration.
10075 // (Other source locations will be updated later.)
10076 Specialization = PrevDecl;
10077 Specialization->setLocation(TemplateNameLoc);
10078 PrevDecl = nullptr;
10079 }
10080
10081 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10082 DLLImportExplicitInstantiationDef) {
10083 // The new specialization might add a dllimport attribute.
10084 HasNoEffect = false;
10085 }
10086 }
10087
10088 if (!Specialization) {
10089 // Create a new class template specialization declaration node for
10090 // this explicit specialization.
10091 Specialization = ClassTemplateSpecializationDecl::Create(
10092 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
10093 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
10094 SetNestedNameSpecifier(*this, Specialization, SS);
10095
10096 // A MSInheritanceAttr attached to the previous declaration must be
10097 // propagated to the new node prior to instantiation.
10098 if (PrevDecl) {
10099 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10100 auto *Clone = A->clone(getASTContext());
10101 Clone->setInherited(true);
10102 Specialization->addAttr(A: Clone);
10103 Consumer.AssignInheritanceModel(Specialization);
10104 }
10105 }
10106
10107 if (!HasNoEffect && !PrevDecl) {
10108 // Insert the new specialization.
10109 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
10110 }
10111 }
10112
10113 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10114
10115 // Set source locations for keywords.
10116 Specialization->setExternKeywordLoc(ExternLoc);
10117 Specialization->setTemplateKeywordLoc(TemplateLoc);
10118 Specialization->setBraceRange(SourceRange());
10119
10120 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10121 ProcessDeclAttributeList(S, Specialization, Attr);
10122 ProcessAPINotes(Specialization);
10123
10124 // Add the explicit instantiation into its lexical context. However,
10125 // since explicit instantiations are never found by name lookup, we
10126 // just put it into the declaration context directly.
10127 Specialization->setLexicalDeclContext(CurContext);
10128 CurContext->addDecl(Specialization);
10129
10130 // Syntax is now OK, so return if it has no other effect on semantics.
10131 if (HasNoEffect) {
10132 // Set the template specialization kind.
10133 Specialization->setTemplateSpecializationKind(TSK);
10134 return Specialization;
10135 }
10136
10137 // C++ [temp.explicit]p3:
10138 // A definition of a class template or class member template
10139 // shall be in scope at the point of the explicit instantiation of
10140 // the class template or class member template.
10141 //
10142 // This check comes when we actually try to perform the
10143 // instantiation.
10144 ClassTemplateSpecializationDecl *Def
10145 = cast_or_null<ClassTemplateSpecializationDecl>(
10146 Specialization->getDefinition());
10147 if (!Def)
10148 InstantiateClassTemplateSpecialization(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Specialization, TSK,
10149 /*Complain=*/true,
10150 PrimaryStrictPackMatch: CTAI.StrictPackMatch);
10151 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10152 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10153 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10154 }
10155
10156 // Instantiate the members of this class template specialization.
10157 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10158 Specialization->getDefinition());
10159 if (Def) {
10160 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10161 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10162 // TSK_ExplicitInstantiationDefinition
10163 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10164 (TSK == TSK_ExplicitInstantiationDefinition ||
10165 DLLImportExplicitInstantiationDef)) {
10166 // FIXME: Need to notify the ASTMutationListener that we did this.
10167 Def->setTemplateSpecializationKind(TSK);
10168
10169 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10170 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10171 // An explicit instantiation definition can add a dll attribute to a
10172 // template with a previous instantiation declaration. MinGW doesn't
10173 // allow this.
10174 auto *A = cast<InheritableAttr>(
10175 Val: getDLLAttr(Specialization)->clone(C&: getASTContext()));
10176 A->setInherited(true);
10177 Def->addAttr(A: A);
10178 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10179 }
10180 }
10181
10182 // Fix a TSK_ImplicitInstantiation followed by a
10183 // TSK_ExplicitInstantiationDefinition
10184 bool NewlyDLLExported =
10185 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10186 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10187 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10188 // An explicit instantiation definition can add a dll attribute to a
10189 // template with a previous implicit instantiation. MinGW doesn't allow
10190 // this. We limit clang to only adding dllexport, to avoid potentially
10191 // strange codegen behavior. For example, if we extend this conditional
10192 // to dllimport, and we have a source file calling a method on an
10193 // implicitly instantiated template class instance and then declaring a
10194 // dllimport explicit instantiation definition for the same template
10195 // class, the codegen for the method call will not respect the dllimport,
10196 // while it will with cl. The Def will already have the DLL attribute,
10197 // since the Def and Specialization will be the same in the case of
10198 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10199 // attribute to the Specialization; we just need to make it take effect.
10200 assert(Def == Specialization &&
10201 "Def and Specialization should match for implicit instantiation");
10202 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10203 }
10204
10205 // In MinGW mode, export the template instantiation if the declaration
10206 // was marked dllexport.
10207 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10208 Context.getTargetInfo().getTriple().isOSCygMing() &&
10209 PrevDecl->hasAttr<DLLExportAttr>()) {
10210 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10211 }
10212
10213 // Set the template specialization kind. Make sure it is set before
10214 // instantiating the members which will trigger ASTConsumer callbacks.
10215 Specialization->setTemplateSpecializationKind(TSK);
10216 InstantiateClassTemplateSpecializationMembers(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Def, TSK);
10217 } else {
10218
10219 // Set the template specialization kind.
10220 Specialization->setTemplateSpecializationKind(TSK);
10221 }
10222
10223 return Specialization;
10224}
10225
10226DeclResult
10227Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10228 SourceLocation TemplateLoc, unsigned TagSpec,
10229 SourceLocation KWLoc, CXXScopeSpec &SS,
10230 IdentifierInfo *Name, SourceLocation NameLoc,
10231 const ParsedAttributesView &Attr) {
10232
10233 bool Owned = false;
10234 bool IsDependent = false;
10235 Decl *TagD =
10236 ActOnTag(S, TagSpec, TUK: TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10237 Attr, AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10238 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent, ScopedEnumKWLoc: SourceLocation(),
10239 ScopedEnumUsesClassTag: false, UnderlyingType: TypeResult(), /*IsTypeSpecifier*/ false,
10240 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10241 .get();
10242 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10243
10244 if (!TagD)
10245 return true;
10246
10247 TagDecl *Tag = cast<TagDecl>(Val: TagD);
10248 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10249
10250 if (Tag->isInvalidDecl())
10251 return true;
10252
10253 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: Tag);
10254 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10255 if (!Pattern) {
10256 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10257 << Context.getTypeDeclType(Record);
10258 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10259 return true;
10260 }
10261
10262 // C++0x [temp.explicit]p2:
10263 // If the explicit instantiation is for a class or member class, the
10264 // elaborated-type-specifier in the declaration shall include a
10265 // simple-template-id.
10266 //
10267 // C++98 has the same restriction, just worded differently.
10268 if (!ScopeSpecifierHasTemplateId(SS))
10269 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10270 << Record << SS.getRange();
10271
10272 // C++0x [temp.explicit]p2:
10273 // There are two forms of explicit instantiation: an explicit instantiation
10274 // definition and an explicit instantiation declaration. An explicit
10275 // instantiation declaration begins with the extern keyword. [...]
10276 TemplateSpecializationKind TSK
10277 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10278 : TSK_ExplicitInstantiationDeclaration;
10279
10280 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10281
10282 // Verify that it is okay to explicitly instantiate here.
10283 CXXRecordDecl *PrevDecl
10284 = cast_or_null<CXXRecordDecl>(Val: Record->getPreviousDecl());
10285 if (!PrevDecl && Record->getDefinition())
10286 PrevDecl = Record;
10287 if (PrevDecl) {
10288 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10289 bool HasNoEffect = false;
10290 assert(MSInfo && "No member specialization information?");
10291 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10292 PrevDecl,
10293 MSInfo->getTemplateSpecializationKind(),
10294 MSInfo->getPointOfInstantiation(),
10295 HasNoEffect))
10296 return true;
10297 if (HasNoEffect)
10298 return TagD;
10299 }
10300
10301 CXXRecordDecl *RecordDef
10302 = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10303 if (!RecordDef) {
10304 // C++ [temp.explicit]p3:
10305 // A definition of a member class of a class template shall be in scope
10306 // at the point of an explicit instantiation of the member class.
10307 CXXRecordDecl *Def
10308 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
10309 if (!Def) {
10310 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10311 << 0 << Record->getDeclName() << Record->getDeclContext();
10312 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10313 << Pattern;
10314 return true;
10315 } else {
10316 if (InstantiateClass(PointOfInstantiation: NameLoc, Instantiation: Record, Pattern: Def,
10317 TemplateArgs: getTemplateInstantiationArgs(Record),
10318 TSK))
10319 return true;
10320
10321 RecordDef = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10322 if (!RecordDef)
10323 return true;
10324 }
10325 }
10326
10327 // Instantiate all of the members of the class.
10328 InstantiateClassMembers(PointOfInstantiation: NameLoc, Instantiation: RecordDef,
10329 TemplateArgs: getTemplateInstantiationArgs(Record), TSK);
10330
10331 if (TSK == TSK_ExplicitInstantiationDefinition)
10332 MarkVTableUsed(Loc: NameLoc, Class: RecordDef, DefinitionRequired: true);
10333
10334 // FIXME: We don't have any representation for explicit instantiations of
10335 // member classes. Such a representation is not needed for compilation, but it
10336 // should be available for clients that want to see all of the declarations in
10337 // the source code.
10338 return TagD;
10339}
10340
10341DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10342 SourceLocation ExternLoc,
10343 SourceLocation TemplateLoc,
10344 Declarator &D) {
10345 // Explicit instantiations always require a name.
10346 // TODO: check if/when DNInfo should replace Name.
10347 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10348 DeclarationName Name = NameInfo.getName();
10349 if (!Name) {
10350 if (!D.isInvalidType())
10351 Diag(D.getDeclSpec().getBeginLoc(),
10352 diag::err_explicit_instantiation_requires_name)
10353 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10354
10355 return true;
10356 }
10357
10358 // Get the innermost enclosing declaration scope.
10359 S = S->getDeclParent();
10360
10361 // Determine the type of the declaration.
10362 TypeSourceInfo *T = GetTypeForDeclarator(D);
10363 QualType R = T->getType();
10364 if (R.isNull())
10365 return true;
10366
10367 // C++ [dcl.stc]p1:
10368 // A storage-class-specifier shall not be specified in [...] an explicit
10369 // instantiation (14.7.2) directive.
10370 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10371 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10372 << Name;
10373 return true;
10374 } else if (D.getDeclSpec().getStorageClassSpec()
10375 != DeclSpec::SCS_unspecified) {
10376 // Complain about then remove the storage class specifier.
10377 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10378 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10379
10380 D.getMutableDeclSpec().ClearStorageClassSpecs();
10381 }
10382
10383 // C++0x [temp.explicit]p1:
10384 // [...] An explicit instantiation of a function template shall not use the
10385 // inline or constexpr specifiers.
10386 // Presumably, this also applies to member functions of class templates as
10387 // well.
10388 if (D.getDeclSpec().isInlineSpecified())
10389 Diag(D.getDeclSpec().getInlineSpecLoc(),
10390 getLangOpts().CPlusPlus11 ?
10391 diag::err_explicit_instantiation_inline :
10392 diag::warn_explicit_instantiation_inline_0x)
10393 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10394 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10395 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10396 // not already specified.
10397 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10398 diag::err_explicit_instantiation_constexpr);
10399
10400 // A deduction guide is not on the list of entities that can be explicitly
10401 // instantiated.
10402 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10403 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10404 << /*explicit instantiation*/ 0;
10405 return true;
10406 }
10407
10408 // C++0x [temp.explicit]p2:
10409 // There are two forms of explicit instantiation: an explicit instantiation
10410 // definition and an explicit instantiation declaration. An explicit
10411 // instantiation declaration begins with the extern keyword. [...]
10412 TemplateSpecializationKind TSK
10413 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10414 : TSK_ExplicitInstantiationDeclaration;
10415
10416 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10417 LookupParsedName(R&: Previous, S, SS: &D.getCXXScopeSpec(),
10418 /*ObjectType=*/QualType());
10419
10420 if (!R->isFunctionType()) {
10421 // C++ [temp.explicit]p1:
10422 // A [...] static data member of a class template can be explicitly
10423 // instantiated from the member definition associated with its class
10424 // template.
10425 // C++1y [temp.explicit]p1:
10426 // A [...] variable [...] template specialization can be explicitly
10427 // instantiated from its template.
10428 if (Previous.isAmbiguous())
10429 return true;
10430
10431 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10432 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10433
10434 if (!PrevTemplate) {
10435 if (!Prev || !Prev->isStaticDataMember()) {
10436 // We expect to see a static data member here.
10437 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10438 << Name;
10439 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10440 P != PEnd; ++P)
10441 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10442 return true;
10443 }
10444
10445 if (!Prev->getInstantiatedFromStaticDataMember()) {
10446 // FIXME: Check for explicit specialization?
10447 Diag(D.getIdentifierLoc(),
10448 diag::err_explicit_instantiation_data_member_not_instantiated)
10449 << Prev;
10450 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10451 // FIXME: Can we provide a note showing where this was declared?
10452 return true;
10453 }
10454 } else {
10455 // Explicitly instantiate a variable template.
10456
10457 // C++1y [dcl.spec.auto]p6:
10458 // ... A program that uses auto or decltype(auto) in a context not
10459 // explicitly allowed in this section is ill-formed.
10460 //
10461 // This includes auto-typed variable template instantiations.
10462 if (R->isUndeducedType()) {
10463 Diag(T->getTypeLoc().getBeginLoc(),
10464 diag::err_auto_not_allowed_var_inst);
10465 return true;
10466 }
10467
10468 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10469 // C++1y [temp.explicit]p3:
10470 // If the explicit instantiation is for a variable, the unqualified-id
10471 // in the declaration shall be a template-id.
10472 Diag(D.getIdentifierLoc(),
10473 diag::err_explicit_instantiation_without_template_id)
10474 << PrevTemplate;
10475 Diag(PrevTemplate->getLocation(),
10476 diag::note_explicit_instantiation_here);
10477 return true;
10478 }
10479
10480 // Translate the parser's template argument list into our AST format.
10481 TemplateArgumentListInfo TemplateArgs =
10482 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10483
10484 DeclResult Res = CheckVarTemplateId(Template: PrevTemplate, TemplateLoc,
10485 TemplateNameLoc: D.getIdentifierLoc(), TemplateArgs);
10486 if (Res.isInvalid())
10487 return true;
10488
10489 if (!Res.isUsable()) {
10490 // We somehow specified dependent template arguments in an explicit
10491 // instantiation. This should probably only happen during error
10492 // recovery.
10493 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10494 return true;
10495 }
10496
10497 // Ignore access control bits, we don't need them for redeclaration
10498 // checking.
10499 Prev = cast<VarDecl>(Val: Res.get());
10500 }
10501
10502 // C++0x [temp.explicit]p2:
10503 // If the explicit instantiation is for a member function, a member class
10504 // or a static data member of a class template specialization, the name of
10505 // the class template specialization in the qualified-id for the member
10506 // name shall be a simple-template-id.
10507 //
10508 // C++98 has the same restriction, just worded differently.
10509 //
10510 // This does not apply to variable template specializations, where the
10511 // template-id is in the unqualified-id instead.
10512 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10513 Diag(D.getIdentifierLoc(),
10514 diag::ext_explicit_instantiation_without_qualified_id)
10515 << Prev << D.getCXXScopeSpec().getRange();
10516
10517 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10518
10519 // Verify that it is okay to explicitly instantiate here.
10520 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10521 SourceLocation POI = Prev->getPointOfInstantiation();
10522 bool HasNoEffect = false;
10523 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
10524 PrevTSK, POI, HasNoEffect))
10525 return true;
10526
10527 if (!HasNoEffect) {
10528 // Instantiate static data member or variable template.
10529 Prev->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
10530 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: Prev)) {
10531 VTSD->setExternKeywordLoc(ExternLoc);
10532 VTSD->setTemplateKeywordLoc(TemplateLoc);
10533 }
10534
10535 // Merge attributes.
10536 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10537 if (PrevTemplate)
10538 ProcessAPINotes(Prev);
10539
10540 if (TSK == TSK_ExplicitInstantiationDefinition)
10541 InstantiateVariableDefinition(PointOfInstantiation: D.getIdentifierLoc(), Var: Prev);
10542 }
10543
10544 // Check the new variable specialization against the parsed input.
10545 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10546 Diag(T->getTypeLoc().getBeginLoc(),
10547 diag::err_invalid_var_template_spec_type)
10548 << 0 << PrevTemplate << R << Prev->getType();
10549 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10550 << 2 << PrevTemplate->getDeclName();
10551 return true;
10552 }
10553
10554 // FIXME: Create an ExplicitInstantiation node?
10555 return (Decl*) nullptr;
10556 }
10557
10558 // If the declarator is a template-id, translate the parser's template
10559 // argument list into our AST format.
10560 bool HasExplicitTemplateArgs = false;
10561 TemplateArgumentListInfo TemplateArgs;
10562 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10563 TemplateArgs = makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10564 HasExplicitTemplateArgs = true;
10565 }
10566
10567 // C++ [temp.explicit]p1:
10568 // A [...] function [...] can be explicitly instantiated from its template.
10569 // A member function [...] of a class template can be explicitly
10570 // instantiated from the member definition associated with its class
10571 // template.
10572 UnresolvedSet<8> TemplateMatches;
10573 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10574 OverloadCandidateSet::CSK_Normal);
10575 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10576 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10577 P != PEnd; ++P) {
10578 NamedDecl *Prev = *P;
10579 if (!HasExplicitTemplateArgs) {
10580 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Prev)) {
10581 QualType Adjusted = adjustCCAndNoReturn(ArgFunctionType: R, FunctionType: Method->getType(),
10582 /*AdjustExceptionSpec*/true);
10583 if (Context.hasSameUnqualifiedType(T1: Method->getType(), T2: Adjusted)) {
10584 if (Method->getPrimaryTemplate()) {
10585 TemplateMatches.addDecl(Method, P.getAccess());
10586 } else {
10587 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10588 C.FoundDecl = P.getPair();
10589 C.Function = Method;
10590 C.Viable = true;
10591 ConstraintSatisfaction S;
10592 if (Method->getTrailingRequiresClause() &&
10593 (CheckFunctionConstraints(Method, S, D.getIdentifierLoc(),
10594 /*ForOverloadResolution=*/true) ||
10595 !S.IsSatisfied)) {
10596 C.Viable = false;
10597 C.FailureKind = ovl_fail_constraints_not_satisfied;
10598 }
10599 }
10600 }
10601 }
10602 }
10603
10604 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Prev);
10605 if (!FunTmpl)
10606 continue;
10607
10608 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10609 FunctionDecl *Specialization = nullptr;
10610 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
10611 FunctionTemplate: FunTmpl, ExplicitTemplateArgs: (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), ArgFunctionType: R,
10612 Specialization, Info);
10613 TDK != TemplateDeductionResult::Success) {
10614 // Keep track of almost-matches.
10615 FailedTemplateCandidates.addCandidate().set(
10616 P.getPair(), FunTmpl->getTemplatedDecl(),
10617 MakeDeductionFailureInfo(Context, TDK, Info));
10618 (void)TDK;
10619 continue;
10620 }
10621
10622 // Target attributes are part of the cuda function signature, so
10623 // the cuda target of the instantiated function must match that of its
10624 // template. Given that C++ template deduction does not take
10625 // target attributes into account, we reject candidates here that
10626 // have a different target.
10627 if (LangOpts.CUDA &&
10628 CUDA().IdentifyTarget(D: Specialization,
10629 /* IgnoreImplicitHDAttr = */ true) !=
10630 CUDA().IdentifyTarget(Attrs: D.getDeclSpec().getAttributes())) {
10631 FailedTemplateCandidates.addCandidate().set(
10632 P.getPair(), FunTmpl->getTemplatedDecl(),
10633 MakeDeductionFailureInfo(
10634 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
10635 continue;
10636 }
10637
10638 TemplateMatches.addDecl(Specialization, P.getAccess());
10639 }
10640
10641 FunctionDecl *Specialization = nullptr;
10642 if (!NonTemplateMatches.empty()) {
10643 unsigned Msg = 0;
10644 OverloadCandidateDisplayKind DisplayKind;
10645 OverloadCandidateSet::iterator Best;
10646 switch (NonTemplateMatches.BestViableFunction(S&: *this, Loc: D.getIdentifierLoc(),
10647 Best)) {
10648 case OR_Success:
10649 case OR_Deleted:
10650 Specialization = cast<FunctionDecl>(Val: Best->Function);
10651 break;
10652 case OR_Ambiguous:
10653 Msg = diag::err_explicit_instantiation_ambiguous;
10654 DisplayKind = OCD_AmbiguousCandidates;
10655 break;
10656 case OR_No_Viable_Function:
10657 Msg = diag::err_explicit_instantiation_no_candidate;
10658 DisplayKind = OCD_AllCandidates;
10659 break;
10660 }
10661 if (Msg) {
10662 PartialDiagnostic Diag = PDiag(Msg) << Name;
10663 NonTemplateMatches.NoteCandidates(
10664 PA: PartialDiagnosticAt(D.getIdentifierLoc(), Diag), S&: *this, OCD: DisplayKind,
10665 Args: {});
10666 return true;
10667 }
10668 }
10669
10670 if (!Specialization) {
10671 // Find the most specialized function template specialization.
10672 UnresolvedSetIterator Result = getMostSpecialized(
10673 TemplateMatches.begin(), TemplateMatches.end(),
10674 FailedTemplateCandidates, D.getIdentifierLoc(),
10675 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10676 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10677 PDiag(diag::note_explicit_instantiation_candidate));
10678
10679 if (Result == TemplateMatches.end())
10680 return true;
10681
10682 // Ignore access control bits, we don't need them for redeclaration checking.
10683 Specialization = cast<FunctionDecl>(Val: *Result);
10684 }
10685
10686 // C++11 [except.spec]p4
10687 // In an explicit instantiation an exception-specification may be specified,
10688 // but is not required.
10689 // If an exception-specification is specified in an explicit instantiation
10690 // directive, it shall be compatible with the exception-specifications of
10691 // other declarations of that function.
10692 if (auto *FPT = R->getAs<FunctionProtoType>())
10693 if (FPT->hasExceptionSpec()) {
10694 unsigned DiagID =
10695 diag::err_mismatched_exception_spec_explicit_instantiation;
10696 if (getLangOpts().MicrosoftExt)
10697 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10698 bool Result = CheckEquivalentExceptionSpec(
10699 PDiag(DiagID) << Specialization->getType(),
10700 PDiag(diag::note_explicit_instantiation_here),
10701 Specialization->getType()->getAs<FunctionProtoType>(),
10702 Specialization->getLocation(), FPT, D.getBeginLoc());
10703 // In Microsoft mode, mismatching exception specifications just cause a
10704 // warning.
10705 if (!getLangOpts().MicrosoftExt && Result)
10706 return true;
10707 }
10708
10709 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10710 Diag(D.getIdentifierLoc(),
10711 diag::err_explicit_instantiation_member_function_not_instantiated)
10712 << Specialization
10713 << (Specialization->getTemplateSpecializationKind() ==
10714 TSK_ExplicitSpecialization);
10715 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10716 return true;
10717 }
10718
10719 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10720 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10721 PrevDecl = Specialization;
10722
10723 if (PrevDecl) {
10724 bool HasNoEffect = false;
10725 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10726 PrevDecl,
10727 PrevDecl->getTemplateSpecializationKind(),
10728 PrevDecl->getPointOfInstantiation(),
10729 HasNoEffect))
10730 return true;
10731
10732 // FIXME: We may still want to build some representation of this
10733 // explicit specialization.
10734 if (HasNoEffect)
10735 return (Decl*) nullptr;
10736 }
10737
10738 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10739 // functions
10740 // valarray<size_t>::valarray(size_t) and
10741 // valarray<size_t>::~valarray()
10742 // that it declared to have internal linkage with the internal_linkage
10743 // attribute. Ignore the explicit instantiation declaration in this case.
10744 if (Specialization->hasAttr<InternalLinkageAttr>() &&
10745 TSK == TSK_ExplicitInstantiationDeclaration) {
10746 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10747 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10748 RD->isInStdNamespace())
10749 return (Decl*) nullptr;
10750 }
10751
10752 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10753 ProcessAPINotes(Specialization);
10754
10755 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10756 // instantiation declarations.
10757 if (TSK == TSK_ExplicitInstantiationDefinition &&
10758 Specialization->hasAttr<DLLImportAttr>() &&
10759 Context.getTargetInfo().getCXXABI().isMicrosoft())
10760 TSK = TSK_ExplicitInstantiationDeclaration;
10761
10762 Specialization->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
10763
10764 if (Specialization->isDefined()) {
10765 // Let the ASTConsumer know that this function has been explicitly
10766 // instantiated now, and its linkage might have changed.
10767 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Specialization));
10768 } else if (TSK == TSK_ExplicitInstantiationDefinition)
10769 InstantiateFunctionDefinition(PointOfInstantiation: D.getIdentifierLoc(), Function: Specialization);
10770
10771 // C++0x [temp.explicit]p2:
10772 // If the explicit instantiation is for a member function, a member class
10773 // or a static data member of a class template specialization, the name of
10774 // the class template specialization in the qualified-id for the member
10775 // name shall be a simple-template-id.
10776 //
10777 // C++98 has the same restriction, just worded differently.
10778 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10779 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10780 D.getCXXScopeSpec().isSet() &&
10781 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10782 Diag(D.getIdentifierLoc(),
10783 diag::ext_explicit_instantiation_without_qualified_id)
10784 << Specialization << D.getCXXScopeSpec().getRange();
10785
10786 CheckExplicitInstantiation(
10787 *this,
10788 FunTmpl ? (NamedDecl *)FunTmpl
10789 : Specialization->getInstantiatedFromMemberFunction(),
10790 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10791
10792 // FIXME: Create some kind of ExplicitInstantiationDecl here.
10793 return (Decl*) nullptr;
10794}
10795
10796TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10797 const CXXScopeSpec &SS,
10798 const IdentifierInfo *Name,
10799 SourceLocation TagLoc,
10800 SourceLocation NameLoc) {
10801 // This has to hold, because SS is expected to be defined.
10802 assert(Name && "Expected a name in a dependent tag");
10803
10804 NestedNameSpecifier *NNS = SS.getScopeRep();
10805 if (!NNS)
10806 return true;
10807
10808 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10809
10810 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
10811 Diag(NameLoc, diag::err_dependent_tag_decl)
10812 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
10813 return true;
10814 }
10815
10816 // Create the resulting type.
10817 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
10818 QualType Result = Context.getDependentNameType(Keyword: Kwd, NNS, Name);
10819
10820 // Create type-source location information for this type.
10821 TypeLocBuilder TLB;
10822 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: Result);
10823 TL.setElaboratedKeywordLoc(TagLoc);
10824 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10825 TL.setNameLoc(NameLoc);
10826 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
10827}
10828
10829TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10830 const CXXScopeSpec &SS,
10831 const IdentifierInfo &II,
10832 SourceLocation IdLoc,
10833 ImplicitTypenameContext IsImplicitTypename) {
10834 if (SS.isInvalid())
10835 return true;
10836
10837 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10838 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
10839 << FixItHint::CreateRemoval(TypenameLoc);
10840
10841 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10842 TypeSourceInfo *TSI = nullptr;
10843 QualType T =
10844 CheckTypenameType(Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
10845 : ElaboratedTypeKeyword::None,
10846 KeywordLoc: TypenameLoc, QualifierLoc, II, IILoc: IdLoc, TSI: &TSI,
10847 /*DeducedTSTContext=*/true);
10848 if (T.isNull())
10849 return true;
10850 return CreateParsedType(T, TInfo: TSI);
10851}
10852
10853TypeResult
10854Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10855 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
10856 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
10857 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
10858 ASTTemplateArgsPtr TemplateArgsIn,
10859 SourceLocation RAngleLoc) {
10860 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10861 Diag(TypenameLoc, getLangOpts().CPlusPlus11
10862 ? diag::compat_cxx11_typename_outside_of_template
10863 : diag::compat_pre_cxx11_typename_outside_of_template)
10864 << FixItHint::CreateRemoval(TypenameLoc);
10865
10866 // Strangely, non-type results are not ignored by this lookup, so the
10867 // program is ill-formed if it finds an injected-class-name.
10868 if (TypenameLoc.isValid()) {
10869 auto *LookupRD =
10870 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: false));
10871 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10872 Diag(TemplateIILoc,
10873 diag::ext_out_of_line_qualified_id_type_names_constructor)
10874 << TemplateII << 0 /*injected-class-name used as template name*/
10875 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10876 }
10877 }
10878
10879 // Translate the parser's template argument list in our AST format.
10880 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10881 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10882
10883 auto Keyword = TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
10884 : ElaboratedTypeKeyword::None;
10885
10886 TemplateName Template = TemplateIn.get();
10887 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10888 // Construct a dependent template specialization type.
10889 assert(DTN && "dependent template has non-dependent name?");
10890 assert(DTN->getQualifier() == SS.getScopeRep());
10891
10892 if (!DTN->getName().getIdentifier()) {
10893 Diag(TemplateIILoc, diag::err_template_id_not_a_type) << Template;
10894 NoteAllFoundTemplates(Name: Template);
10895 return true;
10896 }
10897
10898 QualType T = Context.getDependentTemplateSpecializationType(
10899 Keyword, Name: *DTN, Args: TemplateArgs.arguments());
10900
10901 // Create source-location information for this type.
10902 TypeLocBuilder Builder;
10903 DependentTemplateSpecializationTypeLoc SpecTL
10904 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
10905 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10906 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
10907 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10908 SpecTL.setTemplateNameLoc(TemplateIILoc);
10909 SpecTL.setLAngleLoc(LAngleLoc);
10910 SpecTL.setRAngleLoc(RAngleLoc);
10911 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10912 SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo());
10913 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
10914 }
10915
10916 QualType T = CheckTemplateIdType(Name: Template, TemplateLoc: TemplateIILoc, TemplateArgs);
10917 if (T.isNull())
10918 return true;
10919
10920 // Provide source-location information for the template specialization type.
10921 TypeLocBuilder Builder;
10922 TemplateSpecializationTypeLoc SpecTL
10923 = Builder.push<TemplateSpecializationTypeLoc>(T);
10924 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10925 SpecTL.setTemplateNameLoc(TemplateIILoc);
10926 SpecTL.setLAngleLoc(LAngleLoc);
10927 SpecTL.setRAngleLoc(RAngleLoc);
10928 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10929 SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo());
10930
10931 T = Context.getElaboratedType(Keyword, NNS: SS.getScopeRep(), NamedType: T);
10932 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10933 TL.setElaboratedKeywordLoc(TypenameLoc);
10934 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10935
10936 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10937 return CreateParsedType(T, TInfo: TSI);
10938}
10939
10940/// Determine whether this failed name lookup should be treated as being
10941/// disabled by a usage of std::enable_if.
10942static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
10943 SourceRange &CondRange, Expr *&Cond) {
10944 // We must be looking for a ::type...
10945 if (!II.isStr(Str: "type"))
10946 return false;
10947
10948 // ... within an explicitly-written template specialization...
10949 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10950 return false;
10951 TypeLoc EnableIfTy = NNS.getTypeLoc();
10952 TemplateSpecializationTypeLoc EnableIfTSTLoc =
10953 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
10954 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10955 return false;
10956 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10957
10958 // ... which names a complete class template declaration...
10959 const TemplateDecl *EnableIfDecl =
10960 EnableIfTST->getTemplateName().getAsTemplateDecl();
10961 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10962 return false;
10963
10964 // ... called "enable_if".
10965 const IdentifierInfo *EnableIfII =
10966 EnableIfDecl->getDeclName().getAsIdentifierInfo();
10967 if (!EnableIfII || !EnableIfII->isStr(Str: "enable_if"))
10968 return false;
10969
10970 // Assume the first template argument is the condition.
10971 CondRange = EnableIfTSTLoc.getArgLoc(i: 0).getSourceRange();
10972
10973 // Dig out the condition.
10974 Cond = nullptr;
10975 if (EnableIfTSTLoc.getArgLoc(i: 0).getArgument().getKind()
10976 != TemplateArgument::Expression)
10977 return true;
10978
10979 Cond = EnableIfTSTLoc.getArgLoc(i: 0).getSourceExpression();
10980
10981 // Ignore Boolean literals; they add no value.
10982 if (isa<CXXBoolLiteralExpr>(Val: Cond->IgnoreParenCasts()))
10983 Cond = nullptr;
10984
10985 return true;
10986}
10987
10988QualType
10989Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
10990 SourceLocation KeywordLoc,
10991 NestedNameSpecifierLoc QualifierLoc,
10992 const IdentifierInfo &II,
10993 SourceLocation IILoc,
10994 TypeSourceInfo **TSI,
10995 bool DeducedTSTContext) {
10996 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
10997 DeducedTSTContext);
10998 if (T.isNull())
10999 return QualType();
11000
11001 *TSI = Context.CreateTypeSourceInfo(T);
11002 if (isa<DependentNameType>(Val: T)) {
11003 DependentNameTypeLoc TL =
11004 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
11005 TL.setElaboratedKeywordLoc(KeywordLoc);
11006 TL.setQualifierLoc(QualifierLoc);
11007 TL.setNameLoc(IILoc);
11008 } else {
11009 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
11010 TL.setElaboratedKeywordLoc(KeywordLoc);
11011 TL.setQualifierLoc(QualifierLoc);
11012 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
11013 }
11014 return T;
11015}
11016
11017/// Build the type that describes a C++ typename specifier,
11018/// e.g., "typename T::type".
11019QualType
11020Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11021 SourceLocation KeywordLoc,
11022 NestedNameSpecifierLoc QualifierLoc,
11023 const IdentifierInfo &II,
11024 SourceLocation IILoc, bool DeducedTSTContext) {
11025 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11026
11027 CXXScopeSpec SS;
11028 SS.Adopt(Other: QualifierLoc);
11029
11030 DeclContext *Ctx = nullptr;
11031 if (QualifierLoc) {
11032 Ctx = computeDeclContext(SS);
11033 if (!Ctx) {
11034 // If the nested-name-specifier is dependent and couldn't be
11035 // resolved to a type, build a typename type.
11036 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
11037 return Context.getDependentNameType(Keyword,
11038 NNS: QualifierLoc.getNestedNameSpecifier(),
11039 Name: &II);
11040 }
11041
11042 // If the nested-name-specifier refers to the current instantiation,
11043 // the "typename" keyword itself is superfluous. In C++03, the
11044 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11045 // allows such extraneous "typename" keywords, and we retroactively
11046 // apply this DR to C++03 code with only a warning. In any case we continue.
11047
11048 if (RequireCompleteDeclContext(SS, DC: Ctx))
11049 return QualType();
11050 }
11051
11052 DeclarationName Name(&II);
11053 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11054 if (Ctx)
11055 LookupQualifiedName(R&: Result, LookupCtx: Ctx, SS);
11056 else
11057 LookupName(R&: Result, S: CurScope);
11058 unsigned DiagID = 0;
11059 Decl *Referenced = nullptr;
11060 switch (Result.getResultKind()) {
11061 case LookupResultKind::NotFound: {
11062 // If we're looking up 'type' within a template named 'enable_if', produce
11063 // a more specific diagnostic.
11064 SourceRange CondRange;
11065 Expr *Cond = nullptr;
11066 if (Ctx && isEnableIf(NNS: QualifierLoc, II, CondRange, Cond)) {
11067 // If we have a condition, narrow it down to the specific failed
11068 // condition.
11069 if (Cond) {
11070 Expr *FailedCond;
11071 std::string FailedDescription;
11072 std::tie(args&: FailedCond, args&: FailedDescription) =
11073 findFailedBooleanCondition(Cond);
11074
11075 Diag(FailedCond->getExprLoc(),
11076 diag::err_typename_nested_not_found_requirement)
11077 << FailedDescription
11078 << FailedCond->getSourceRange();
11079 return QualType();
11080 }
11081
11082 Diag(CondRange.getBegin(),
11083 diag::err_typename_nested_not_found_enable_if)
11084 << Ctx << CondRange;
11085 return QualType();
11086 }
11087
11088 DiagID = Ctx ? diag::err_typename_nested_not_found
11089 : diag::err_unknown_typename;
11090 break;
11091 }
11092
11093 case LookupResultKind::FoundUnresolvedValue: {
11094 // We found a using declaration that is a value. Most likely, the using
11095 // declaration itself is meant to have the 'typename' keyword.
11096 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11097 IILoc);
11098 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11099 << Name << Ctx << FullRange;
11100 if (UnresolvedUsingValueDecl *Using
11101 = dyn_cast<UnresolvedUsingValueDecl>(Val: Result.getRepresentativeDecl())){
11102 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11103 Diag(Loc, diag::note_using_value_decl_missing_typename)
11104 << FixItHint::CreateInsertion(Loc, "typename ");
11105 }
11106 }
11107 // Fall through to create a dependent typename type, from which we can
11108 // recover better.
11109 [[fallthrough]];
11110
11111 case LookupResultKind::NotFoundInCurrentInstantiation:
11112 // Okay, it's a member of an unknown instantiation.
11113 return Context.getDependentNameType(Keyword,
11114 NNS: QualifierLoc.getNestedNameSpecifier(),
11115 Name: &II);
11116
11117 case LookupResultKind::Found:
11118 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: Result.getFoundDecl())) {
11119 // C++ [class.qual]p2:
11120 // In a lookup in which function names are not ignored and the
11121 // nested-name-specifier nominates a class C, if the name specified
11122 // after the nested-name-specifier, when looked up in C, is the
11123 // injected-class-name of C [...] then the name is instead considered
11124 // to name the constructor of class C.
11125 //
11126 // Unlike in an elaborated-type-specifier, function names are not ignored
11127 // in typename-specifier lookup. However, they are ignored in all the
11128 // contexts where we form a typename type with no keyword (that is, in
11129 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11130 //
11131 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11132 // ignore functions, but that appears to be an oversight.
11133 QualType T = getTypeDeclType(LookupCtx: Ctx,
11134 DCK: Keyword == ElaboratedTypeKeyword::Typename
11135 ? DiagCtorKind::Typename
11136 : DiagCtorKind::None,
11137 TD: Type, NameLoc: IILoc);
11138 // We found a type. Build an ElaboratedType, since the
11139 // typename-specifier was just sugar.
11140 return Context.getElaboratedType(
11141 Keyword, NNS: QualifierLoc.getNestedNameSpecifier(), NamedType: T);
11142 }
11143
11144 // C++ [dcl.type.simple]p2:
11145 // A type-specifier of the form
11146 // typename[opt] nested-name-specifier[opt] template-name
11147 // is a placeholder for a deduced class type [...].
11148 if (getLangOpts().CPlusPlus17) {
11149 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11150 if (!DeducedTSTContext) {
11151 QualType T(QualifierLoc
11152 ? QualifierLoc.getNestedNameSpecifier()->getAsType()
11153 : nullptr, 0);
11154 if (!T.isNull())
11155 Diag(IILoc, diag::err_dependent_deduced_tst)
11156 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T;
11157 else
11158 Diag(IILoc, diag::err_deduced_tst)
11159 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD));
11160 NoteTemplateLocation(Decl: *TD);
11161 return QualType();
11162 }
11163 return Context.getElaboratedType(
11164 Keyword, NNS: QualifierLoc.getNestedNameSpecifier(),
11165 NamedType: Context.getDeducedTemplateSpecializationType(Template: TemplateName(TD),
11166 DeducedType: QualType(), IsDependent: false));
11167 }
11168 }
11169
11170 DiagID = Ctx ? diag::err_typename_nested_not_type
11171 : diag::err_typename_not_type;
11172 Referenced = Result.getFoundDecl();
11173 break;
11174
11175 case LookupResultKind::FoundOverloaded:
11176 DiagID = Ctx ? diag::err_typename_nested_not_type
11177 : diag::err_typename_not_type;
11178 Referenced = *Result.begin();
11179 break;
11180
11181 case LookupResultKind::Ambiguous:
11182 return QualType();
11183 }
11184
11185 // If we get here, it's because name lookup did not find a
11186 // type. Emit an appropriate diagnostic and return an error.
11187 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11188 IILoc);
11189 if (Ctx)
11190 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11191 else
11192 Diag(IILoc, DiagID) << FullRange << Name;
11193 if (Referenced)
11194 Diag(Referenced->getLocation(),
11195 Ctx ? diag::note_typename_member_refers_here
11196 : diag::note_typename_refers_here)
11197 << Name;
11198 return QualType();
11199}
11200
11201namespace {
11202 // See Sema::RebuildTypeInCurrentInstantiation
11203 class CurrentInstantiationRebuilder
11204 : public TreeTransform<CurrentInstantiationRebuilder> {
11205 SourceLocation Loc;
11206 DeclarationName Entity;
11207
11208 public:
11209 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11210
11211 CurrentInstantiationRebuilder(Sema &SemaRef,
11212 SourceLocation Loc,
11213 DeclarationName Entity)
11214 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11215 Loc(Loc), Entity(Entity) { }
11216
11217 /// Determine whether the given type \p T has already been
11218 /// transformed.
11219 ///
11220 /// For the purposes of type reconstruction, a type has already been
11221 /// transformed if it is NULL or if it is not dependent.
11222 bool AlreadyTransformed(QualType T) {
11223 return T.isNull() || !T->isInstantiationDependentType();
11224 }
11225
11226 /// Returns the location of the entity whose type is being
11227 /// rebuilt.
11228 SourceLocation getBaseLocation() { return Loc; }
11229
11230 /// Returns the name of the entity whose type is being rebuilt.
11231 DeclarationName getBaseEntity() { return Entity; }
11232
11233 /// Sets the "base" location and entity when that
11234 /// information is known based on another transformation.
11235 void setBase(SourceLocation Loc, DeclarationName Entity) {
11236 this->Loc = Loc;
11237 this->Entity = Entity;
11238 }
11239
11240 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11241 // Lambdas never need to be transformed.
11242 return E;
11243 }
11244 };
11245} // end anonymous namespace
11246
11247TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11248 SourceLocation Loc,
11249 DeclarationName Name) {
11250 if (!T || !T->getType()->isInstantiationDependentType())
11251 return T;
11252
11253 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11254 return Rebuilder.TransformType(T);
11255}
11256
11257ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11258 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11259 DeclarationName());
11260 return Rebuilder.TransformExpr(E);
11261}
11262
11263bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11264 if (SS.isInvalid())
11265 return true;
11266
11267 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11268 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11269 DeclarationName());
11270 NestedNameSpecifierLoc Rebuilt
11271 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11272 if (!Rebuilt)
11273 return true;
11274
11275 SS.Adopt(Other: Rebuilt);
11276 return false;
11277}
11278
11279bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11280 TemplateParameterList *Params) {
11281 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11282 Decl *Param = Params->getParam(Idx: I);
11283
11284 // There is nothing to rebuild in a type parameter.
11285 if (isa<TemplateTypeParmDecl>(Val: Param))
11286 continue;
11287
11288 // Rebuild the template parameter list of a template template parameter.
11289 if (TemplateTemplateParmDecl *TTP
11290 = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) {
11291 if (RebuildTemplateParamsInCurrentInstantiation(
11292 Params: TTP->getTemplateParameters()))
11293 return true;
11294
11295 continue;
11296 }
11297
11298 // Rebuild the type of a non-type template parameter.
11299 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Val: Param);
11300 TypeSourceInfo *NewTSI
11301 = RebuildTypeInCurrentInstantiation(T: NTTP->getTypeSourceInfo(),
11302 Loc: NTTP->getLocation(),
11303 Name: NTTP->getDeclName());
11304 if (!NewTSI)
11305 return true;
11306
11307 if (NewTSI->getType()->isUndeducedType()) {
11308 // C++17 [temp.dep.expr]p3:
11309 // An id-expression is type-dependent if it contains
11310 // - an identifier associated by name lookup with a non-type
11311 // template-parameter declared with a type that contains a
11312 // placeholder type (7.1.7.4),
11313 NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: NewTSI);
11314 }
11315
11316 if (NewTSI != NTTP->getTypeSourceInfo()) {
11317 NTTP->setTypeSourceInfo(NewTSI);
11318 NTTP->setType(NewTSI->getType());
11319 }
11320 }
11321
11322 return false;
11323}
11324
11325std::string
11326Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11327 const TemplateArgumentList &Args) {
11328 return getTemplateArgumentBindingsText(Params, Args: Args.data(), NumArgs: Args.size());
11329}
11330
11331std::string
11332Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11333 const TemplateArgument *Args,
11334 unsigned NumArgs) {
11335 SmallString<128> Str;
11336 llvm::raw_svector_ostream Out(Str);
11337
11338 if (!Params || Params->size() == 0 || NumArgs == 0)
11339 return std::string();
11340
11341 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11342 if (I >= NumArgs)
11343 break;
11344
11345 if (I == 0)
11346 Out << "[with ";
11347 else
11348 Out << ", ";
11349
11350 if (const IdentifierInfo *Id = Params->getParam(Idx: I)->getIdentifier()) {
11351 Out << Id->getName();
11352 } else {
11353 Out << '$' << I;
11354 }
11355
11356 Out << " = ";
11357 Args[I].print(Policy: getPrintingPolicy(), Out,
11358 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
11359 Policy: getPrintingPolicy(), TPL: Params, Idx: I));
11360 }
11361
11362 Out << ']';
11363 return std::string(Out.str());
11364}
11365
11366void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11367 CachedTokens &Toks) {
11368 if (!FD)
11369 return;
11370
11371 auto LPT = std::make_unique<LateParsedTemplate>();
11372
11373 // Take tokens to avoid allocations
11374 LPT->Toks.swap(RHS&: Toks);
11375 LPT->D = FnD;
11376 LPT->FPO = getCurFPFeatures();
11377 LateParsedTemplateMap.insert(KV: std::make_pair(x&: FD, y: std::move(LPT)));
11378
11379 FD->setLateTemplateParsed(true);
11380}
11381
11382void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11383 if (!FD)
11384 return;
11385 FD->setLateTemplateParsed(false);
11386}
11387
11388bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11389 DeclContext *DC = CurContext;
11390
11391 while (DC) {
11392 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
11393 const FunctionDecl *FD = RD->isLocalClass();
11394 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11395 } else if (DC->isTranslationUnit() || DC->isNamespace())
11396 return false;
11397
11398 DC = DC->getParent();
11399 }
11400 return false;
11401}
11402
11403namespace {
11404/// Walk the path from which a declaration was instantiated, and check
11405/// that every explicit specialization along that path is visible. This enforces
11406/// C++ [temp.expl.spec]/6:
11407///
11408/// If a template, a member template or a member of a class template is
11409/// explicitly specialized then that specialization shall be declared before
11410/// the first use of that specialization that would cause an implicit
11411/// instantiation to take place, in every translation unit in which such a
11412/// use occurs; no diagnostic is required.
11413///
11414/// and also C++ [temp.class.spec]/1:
11415///
11416/// A partial specialization shall be declared before the first use of a
11417/// class template specialization that would make use of the partial
11418/// specialization as the result of an implicit or explicit instantiation
11419/// in every translation unit in which such a use occurs; no diagnostic is
11420/// required.
11421class ExplicitSpecializationVisibilityChecker {
11422 Sema &S;
11423 SourceLocation Loc;
11424 llvm::SmallVector<Module *, 8> Modules;
11425 Sema::AcceptableKind Kind;
11426
11427public:
11428 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11429 Sema::AcceptableKind Kind)
11430 : S(S), Loc(Loc), Kind(Kind) {}
11431
11432 void check(NamedDecl *ND) {
11433 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
11434 return checkImpl(Spec: FD);
11435 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
11436 return checkImpl(Spec: RD);
11437 if (auto *VD = dyn_cast<VarDecl>(Val: ND))
11438 return checkImpl(Spec: VD);
11439 if (auto *ED = dyn_cast<EnumDecl>(Val: ND))
11440 return checkImpl(Spec: ED);
11441 }
11442
11443private:
11444 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11445 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11446 : Sema::MissingImportKind::ExplicitSpecialization;
11447 const bool Recover = true;
11448
11449 // If we got a custom set of modules (because only a subset of the
11450 // declarations are interesting), use them, otherwise let
11451 // diagnoseMissingImport intelligently pick some.
11452 if (Modules.empty())
11453 S.diagnoseMissingImport(Loc, Decl: D, MIK: Kind, Recover);
11454 else
11455 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11456 }
11457
11458 bool CheckMemberSpecialization(const NamedDecl *D) {
11459 return Kind == Sema::AcceptableKind::Visible
11460 ? S.hasVisibleMemberSpecialization(D)
11461 : S.hasReachableMemberSpecialization(D);
11462 }
11463
11464 bool CheckExplicitSpecialization(const NamedDecl *D) {
11465 return Kind == Sema::AcceptableKind::Visible
11466 ? S.hasVisibleExplicitSpecialization(D)
11467 : S.hasReachableExplicitSpecialization(D);
11468 }
11469
11470 bool CheckDeclaration(const NamedDecl *D) {
11471 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11472 : S.hasReachableDeclaration(D);
11473 }
11474
11475 // Check a specific declaration. There are three problematic cases:
11476 //
11477 // 1) The declaration is an explicit specialization of a template
11478 // specialization.
11479 // 2) The declaration is an explicit specialization of a member of an
11480 // templated class.
11481 // 3) The declaration is an instantiation of a template, and that template
11482 // is an explicit specialization of a member of a templated class.
11483 //
11484 // We don't need to go any deeper than that, as the instantiation of the
11485 // surrounding class / etc is not triggered by whatever triggered this
11486 // instantiation, and thus should be checked elsewhere.
11487 template<typename SpecDecl>
11488 void checkImpl(SpecDecl *Spec) {
11489 bool IsHiddenExplicitSpecialization = false;
11490 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11491 // Some invalid friend declarations are written as specializations but are
11492 // instantiated implicitly.
11493 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11494 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11495 if (SpecKind == TSK_ExplicitSpecialization) {
11496 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11497 ? !CheckMemberSpecialization(D: Spec)
11498 : !CheckExplicitSpecialization(D: Spec);
11499 } else {
11500 checkInstantiated(Spec);
11501 }
11502
11503 if (IsHiddenExplicitSpecialization)
11504 diagnose(D: Spec->getMostRecentDecl(), IsPartialSpec: false);
11505 }
11506
11507 void checkInstantiated(FunctionDecl *FD) {
11508 if (auto *TD = FD->getPrimaryTemplate())
11509 checkTemplate(TD);
11510 }
11511
11512 void checkInstantiated(CXXRecordDecl *RD) {
11513 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD);
11514 if (!SD)
11515 return;
11516
11517 auto From = SD->getSpecializedTemplateOrPartial();
11518 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11519 checkTemplate(TD);
11520 else if (auto *TD =
11521 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11522 if (!CheckDeclaration(TD))
11523 diagnose(TD, true);
11524 checkTemplate(TD);
11525 }
11526 }
11527
11528 void checkInstantiated(VarDecl *RD) {
11529 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(Val: RD);
11530 if (!SD)
11531 return;
11532
11533 auto From = SD->getSpecializedTemplateOrPartial();
11534 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11535 checkTemplate(TD);
11536 else if (auto *TD =
11537 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11538 if (!CheckDeclaration(TD))
11539 diagnose(TD, true);
11540 checkTemplate(TD);
11541 }
11542 }
11543
11544 void checkInstantiated(EnumDecl *FD) {}
11545
11546 template<typename TemplDecl>
11547 void checkTemplate(TemplDecl *TD) {
11548 if (TD->isMemberSpecialization()) {
11549 if (!CheckMemberSpecialization(D: TD))
11550 diagnose(D: TD->getMostRecentDecl(), IsPartialSpec: false);
11551 }
11552 }
11553};
11554} // end anonymous namespace
11555
11556void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11557 if (!getLangOpts().Modules)
11558 return;
11559
11560 ExplicitSpecializationVisibilityChecker(*this, Loc,
11561 Sema::AcceptableKind::Visible)
11562 .check(ND: Spec);
11563}
11564
11565void Sema::checkSpecializationReachability(SourceLocation Loc,
11566 NamedDecl *Spec) {
11567 if (!getLangOpts().CPlusPlusModules)
11568 return checkSpecializationVisibility(Loc, Spec);
11569
11570 ExplicitSpecializationVisibilityChecker(*this, Loc,
11571 Sema::AcceptableKind::Reachable)
11572 .check(ND: Spec);
11573}
11574
11575SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
11576 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11577 return N->getLocation();
11578 if (const auto *FD = dyn_cast<FunctionDecl>(Val: N)) {
11579 if (!FD->isFunctionTemplateSpecialization())
11580 return FD->getLocation();
11581 } else if (!isa<ClassTemplateSpecializationDecl,
11582 VarTemplateSpecializationDecl>(Val: N)) {
11583 return N->getLocation();
11584 }
11585 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11586 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11587 continue;
11588 return CSC.PointOfInstantiation;
11589 }
11590 return N->getLocation();
11591}
11592

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

source code of clang/lib/Sema/SemaTemplate.cpp