xref: /llvm-project/clang/lib/Sema/SemaTemplate.cpp (revision ada6372e52547ba0090f52a2e9e9d95d7eca28d3)
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/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/RecursiveASTVisitor.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/Stack.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/EnterExpressionEvaluationContext.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Overload.h"
34 #include "clang/Sema/ParsedTemplate.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/SemaCUDA.h"
37 #include "clang/Sema/SemaInternal.h"
38 #include "clang/Sema/Template.h"
39 #include "clang/Sema/TemplateDeduction.h"
40 #include "llvm/ADT/BitVector.h"
41 #include "llvm/ADT/SmallBitVector.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/StringExtras.h"
44 
45 #include <iterator>
46 #include <optional>
47 using namespace clang;
48 using namespace sema;
49 
50 // Exported for use by Parser.
51 SourceRange
52 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
53                               unsigned N) {
54   if (!N) return SourceRange();
55   return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
56 }
57 
58 unsigned Sema::getTemplateDepth(Scope *S) const {
59   unsigned Depth = 0;
60 
61   // Each template parameter scope represents one level of template parameter
62   // depth.
63   for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
64        TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
65     ++Depth;
66   }
67 
68   // Note that there are template parameters with the given depth.
69   auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
70 
71   // Look for parameters of an enclosing generic lambda. We don't create a
72   // template parameter scope for these.
73   for (FunctionScopeInfo *FSI : getFunctionScopes()) {
74     if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
75       if (!LSI->TemplateParams.empty()) {
76         ParamsAtDepth(LSI->AutoTemplateParameterDepth);
77         break;
78       }
79       if (LSI->GLTemplateParameterList) {
80         ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
81         break;
82       }
83     }
84   }
85 
86   // Look for parameters of an enclosing terse function template. We don't
87   // create a template parameter scope for these either.
88   for (const InventedTemplateParameterInfo &Info :
89        getInventedParameterInfos()) {
90     if (!Info.TemplateParams.empty()) {
91       ParamsAtDepth(Info.AutoTemplateParameterDepth);
92       break;
93     }
94   }
95 
96   return Depth;
97 }
98 
99 /// \brief Determine whether the declaration found is acceptable as the name
100 /// of a template and, if so, return that template declaration. Otherwise,
101 /// returns null.
102 ///
103 /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
104 /// is true. In all other cases it will return a TemplateDecl (or null).
105 NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
106                                        bool AllowFunctionTemplates,
107                                        bool AllowDependent) {
108   D = D->getUnderlyingDecl();
109 
110   if (isa<TemplateDecl>(D)) {
111     if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
112       return nullptr;
113 
114     return D;
115   }
116 
117   if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
118     // C++ [temp.local]p1:
119     //   Like normal (non-template) classes, class templates have an
120     //   injected-class-name (Clause 9). The injected-class-name
121     //   can be used with or without a template-argument-list. When
122     //   it is used without a template-argument-list, it is
123     //   equivalent to the injected-class-name followed by the
124     //   template-parameters of the class template enclosed in
125     //   <>. When it is used with a template-argument-list, it
126     //   refers to the specified class template specialization,
127     //   which could be the current specialization or another
128     //   specialization.
129     if (Record->isInjectedClassName()) {
130       Record = cast<CXXRecordDecl>(Record->getDeclContext());
131       if (Record->getDescribedClassTemplate())
132         return Record->getDescribedClassTemplate();
133 
134       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
135         return Spec->getSpecializedTemplate();
136     }
137 
138     return nullptr;
139   }
140 
141   // 'using Dependent::foo;' can resolve to a template name.
142   // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
143   // injected-class-name).
144   if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
145     return D;
146 
147   return nullptr;
148 }
149 
150 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
151                                          bool AllowFunctionTemplates,
152                                          bool AllowDependent) {
153   LookupResult::Filter filter = R.makeFilter();
154   while (filter.hasNext()) {
155     NamedDecl *Orig = filter.next();
156     if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
157       filter.erase();
158   }
159   filter.done();
160 }
161 
162 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
163                                          bool AllowFunctionTemplates,
164                                          bool AllowDependent,
165                                          bool AllowNonTemplateFunctions) {
166   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
167     if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
168       return true;
169     if (AllowNonTemplateFunctions &&
170         isa<FunctionDecl>((*I)->getUnderlyingDecl()))
171       return true;
172   }
173 
174   return false;
175 }
176 
177 TemplateNameKind Sema::isTemplateName(Scope *S,
178                                       CXXScopeSpec &SS,
179                                       bool hasTemplateKeyword,
180                                       const UnqualifiedId &Name,
181                                       ParsedType ObjectTypePtr,
182                                       bool EnteringContext,
183                                       TemplateTy &TemplateResult,
184                                       bool &MemberOfUnknownSpecialization,
185                                       bool Disambiguation) {
186   assert(getLangOpts().CPlusPlus && "No template names in C!");
187 
188   DeclarationName TName;
189   MemberOfUnknownSpecialization = false;
190 
191   switch (Name.getKind()) {
192   case UnqualifiedIdKind::IK_Identifier:
193     TName = DeclarationName(Name.Identifier);
194     break;
195 
196   case UnqualifiedIdKind::IK_OperatorFunctionId:
197     TName = Context.DeclarationNames.getCXXOperatorName(
198                                               Name.OperatorFunctionId.Operator);
199     break;
200 
201   case UnqualifiedIdKind::IK_LiteralOperatorId:
202     TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
203     break;
204 
205   default:
206     return TNK_Non_template;
207   }
208 
209   QualType ObjectType = ObjectTypePtr.get();
210 
211   AssumedTemplateKind AssumedTemplate;
212   LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
213   if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
214                          /*RequiredTemplate=*/SourceLocation(),
215                          &AssumedTemplate,
216                          /*AllowTypoCorrection=*/!Disambiguation))
217     return TNK_Non_template;
218   MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
219 
220   if (AssumedTemplate != AssumedTemplateKind::None) {
221     TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
222     // Let the parser know whether we found nothing or found functions; if we
223     // found nothing, we want to more carefully check whether this is actually
224     // a function template name versus some other kind of undeclared identifier.
225     return AssumedTemplate == AssumedTemplateKind::FoundNothing
226                ? TNK_Undeclared_template
227                : TNK_Function_template;
228   }
229 
230   if (R.empty())
231     return TNK_Non_template;
232 
233   NamedDecl *D = nullptr;
234   UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
235   if (R.isAmbiguous()) {
236     // If we got an ambiguity involving a non-function template, treat this
237     // as a template name, and pick an arbitrary template for error recovery.
238     bool AnyFunctionTemplates = false;
239     for (NamedDecl *FoundD : R) {
240       if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
241         if (isa<FunctionTemplateDecl>(FoundTemplate))
242           AnyFunctionTemplates = true;
243         else {
244           D = FoundTemplate;
245           FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
246           break;
247         }
248       }
249     }
250 
251     // If we didn't find any templates at all, this isn't a template name.
252     // Leave the ambiguity for a later lookup to diagnose.
253     if (!D && !AnyFunctionTemplates) {
254       R.suppressDiagnostics();
255       return TNK_Non_template;
256     }
257 
258     // If the only templates were function templates, filter out the rest.
259     // We'll diagnose the ambiguity later.
260     if (!D)
261       FilterAcceptableTemplateNames(R);
262   }
263 
264   // At this point, we have either picked a single template name declaration D
265   // or we have a non-empty set of results R containing either one template name
266   // declaration or a set of function templates.
267 
268   TemplateName Template;
269   TemplateNameKind TemplateKind;
270 
271   unsigned ResultCount = R.end() - R.begin();
272   if (!D && ResultCount > 1) {
273     // We assume that we'll preserve the qualifier from a function
274     // template name in other ways.
275     Template = Context.getOverloadedTemplateName(R.begin(), R.end());
276     TemplateKind = TNK_Function_template;
277 
278     // We'll do this lookup again later.
279     R.suppressDiagnostics();
280   } else {
281     if (!D) {
282       D = getAsTemplateNameDecl(*R.begin());
283       assert(D && "unambiguous result is not a template name");
284     }
285 
286     if (isa<UnresolvedUsingValueDecl>(D)) {
287       // We don't yet know whether this is a template-name or not.
288       MemberOfUnknownSpecialization = true;
289       return TNK_Non_template;
290     }
291 
292     TemplateDecl *TD = cast<TemplateDecl>(D);
293     Template =
294         FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
295     assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
296     if (!SS.isInvalid()) {
297       NestedNameSpecifier *Qualifier = SS.getScopeRep();
298       Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
299                                                   Template);
300     }
301 
302     if (isa<FunctionTemplateDecl>(TD)) {
303       TemplateKind = TNK_Function_template;
304 
305       // We'll do this lookup again later.
306       R.suppressDiagnostics();
307     } else {
308       assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
309              isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
310              isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
311       TemplateKind =
312           isa<VarTemplateDecl>(TD) ? TNK_Var_template :
313           isa<ConceptDecl>(TD) ? TNK_Concept_template :
314           TNK_Type_template;
315     }
316   }
317 
318   TemplateResult = TemplateTy::make(Template);
319   return TemplateKind;
320 }
321 
322 bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
323                                 SourceLocation NameLoc, CXXScopeSpec &SS,
324                                 ParsedTemplateTy *Template /*=nullptr*/) {
325   // We could use redeclaration lookup here, but we don't need to: the
326   // syntactic form of a deduction guide is enough to identify it even
327   // if we can't look up the template name at all.
328   LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
329   if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
330                          /*EnteringContext*/ false))
331     return false;
332 
333   if (R.empty()) return false;
334   if (R.isAmbiguous()) {
335     // FIXME: Diagnose an ambiguity if we find at least one template.
336     R.suppressDiagnostics();
337     return false;
338   }
339 
340   // We only treat template-names that name type templates as valid deduction
341   // guide names.
342   TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
343   if (!TD || !getAsTypeTemplateDecl(TD))
344     return false;
345 
346   if (Template) {
347     TemplateName Name = Context.getQualifiedTemplateName(
348         SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
349     *Template = TemplateTy::make(Name);
350   }
351   return true;
352 }
353 
354 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
355                                        SourceLocation IILoc,
356                                        Scope *S,
357                                        const CXXScopeSpec *SS,
358                                        TemplateTy &SuggestedTemplate,
359                                        TemplateNameKind &SuggestedKind) {
360   // We can't recover unless there's a dependent scope specifier preceding the
361   // template name.
362   // FIXME: Typo correction?
363   if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
364       computeDeclContext(*SS))
365     return false;
366 
367   // The code is missing a 'template' keyword prior to the dependent template
368   // name.
369   NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
370   Diag(IILoc, diag::err_template_kw_missing)
371     << Qualifier << II.getName()
372     << FixItHint::CreateInsertion(IILoc, "template ");
373   SuggestedTemplate
374     = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
375   SuggestedKind = TNK_Dependent_template_name;
376   return true;
377 }
378 
379 bool Sema::LookupTemplateName(LookupResult &Found, Scope *S, CXXScopeSpec &SS,
380                               QualType ObjectType, bool EnteringContext,
381                               RequiredTemplateKind RequiredTemplate,
382                               AssumedTemplateKind *ATK,
383                               bool AllowTypoCorrection) {
384   if (ATK)
385     *ATK = AssumedTemplateKind::None;
386 
387   if (SS.isInvalid())
388     return true;
389 
390   Found.setTemplateNameLookup(true);
391 
392   // Determine where to perform name lookup
393   DeclContext *LookupCtx = nullptr;
394   bool IsDependent = false;
395   if (!ObjectType.isNull()) {
396     // This nested-name-specifier occurs in a member access expression, e.g.,
397     // x->B::f, and we are looking into the type of the object.
398     assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
399     LookupCtx = computeDeclContext(ObjectType);
400     IsDependent = !LookupCtx && ObjectType->isDependentType();
401     assert((IsDependent || !ObjectType->isIncompleteType() ||
402             !ObjectType->getAs<TagType>() ||
403             ObjectType->castAs<TagType>()->isBeingDefined()) &&
404            "Caller should have completed object type");
405 
406     // Template names cannot appear inside an Objective-C class or object type
407     // or a vector type.
408     //
409     // FIXME: This is wrong. For example:
410     //
411     //   template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
412     //   Vec<int> vi;
413     //   vi.Vec<int>::~Vec<int>();
414     //
415     // ... should be accepted but we will not treat 'Vec' as a template name
416     // here. The right thing to do would be to check if the name is a valid
417     // vector component name, and look up a template name if not. And similarly
418     // for lookups into Objective-C class and object types, where the same
419     // problem can arise.
420     if (ObjectType->isObjCObjectOrInterfaceType() ||
421         ObjectType->isVectorType()) {
422       Found.clear();
423       return false;
424     }
425   } else if (SS.isNotEmpty()) {
426     // This nested-name-specifier occurs after another nested-name-specifier,
427     // so long into the context associated with the prior nested-name-specifier.
428     LookupCtx = computeDeclContext(SS, EnteringContext);
429     IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
430 
431     // The declaration context must be complete.
432     if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
433       return true;
434   }
435 
436   bool ObjectTypeSearchedInScope = false;
437   bool AllowFunctionTemplatesInLookup = true;
438   if (LookupCtx) {
439     // Perform "qualified" name lookup into the declaration context we
440     // computed, which is either the type of the base of a member access
441     // expression or the declaration context associated with a prior
442     // nested-name-specifier.
443     LookupQualifiedName(Found, LookupCtx);
444 
445     // FIXME: The C++ standard does not clearly specify what happens in the
446     // case where the object type is dependent, and implementations vary. In
447     // Clang, we treat a name after a . or -> as a template-name if lookup
448     // finds a non-dependent member or member of the current instantiation that
449     // is a type template, or finds no such members and lookup in the context
450     // of the postfix-expression finds a type template. In the latter case, the
451     // name is nonetheless dependent, and we may resolve it to a member of an
452     // unknown specialization when we come to instantiate the template.
453     IsDependent |= Found.wasNotFoundInCurrentInstantiation();
454   }
455 
456   if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
457     // C++ [basic.lookup.classref]p1:
458     //   In a class member access expression (5.2.5), if the . or -> token is
459     //   immediately followed by an identifier followed by a <, the
460     //   identifier must be looked up to determine whether the < is the
461     //   beginning of a template argument list (14.2) or a less-than operator.
462     //   The identifier is first looked up in the class of the object
463     //   expression. If the identifier is not found, it is then looked up in
464     //   the context of the entire postfix-expression and shall name a class
465     //   template.
466     if (S)
467       LookupName(Found, S);
468 
469     if (!ObjectType.isNull()) {
470       //  FIXME: We should filter out all non-type templates here, particularly
471       //  variable templates and concepts. But the exclusion of alias templates
472       //  and template template parameters is a wording defect.
473       AllowFunctionTemplatesInLookup = false;
474       ObjectTypeSearchedInScope = true;
475     }
476 
477     IsDependent |= Found.wasNotFoundInCurrentInstantiation();
478   }
479 
480   if (Found.isAmbiguous())
481     return false;
482 
483   if (ATK && SS.isEmpty() && ObjectType.isNull() &&
484       !RequiredTemplate.hasTemplateKeyword()) {
485     // C++2a [temp.names]p2:
486     //   A name is also considered to refer to a template if it is an
487     //   unqualified-id followed by a < and name lookup finds either one or more
488     //   functions or finds nothing.
489     //
490     // To keep our behavior consistent, we apply the "finds nothing" part in
491     // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
492     // successfully form a call to an undeclared template-id.
493     bool AllFunctions =
494         getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
495           return isa<FunctionDecl>(ND->getUnderlyingDecl());
496         });
497     if (AllFunctions || (Found.empty() && !IsDependent)) {
498       // If lookup found any functions, or if this is a name that can only be
499       // used for a function, then strongly assume this is a function
500       // template-id.
501       *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
502                  ? AssumedTemplateKind::FoundNothing
503                  : AssumedTemplateKind::FoundFunctions;
504       Found.clear();
505       return false;
506     }
507   }
508 
509   if (Found.empty() && !IsDependent && AllowTypoCorrection) {
510     // If we did not find any names, and this is not a disambiguation, attempt
511     // to correct any typos.
512     DeclarationName Name = Found.getLookupName();
513     Found.clear();
514     // Simple filter callback that, for keywords, only accepts the C++ *_cast
515     DefaultFilterCCC FilterCCC{};
516     FilterCCC.WantTypeSpecifiers = false;
517     FilterCCC.WantExpressionKeywords = false;
518     FilterCCC.WantRemainingKeywords = false;
519     FilterCCC.WantCXXNamedCasts = true;
520     if (TypoCorrection Corrected =
521             CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
522                         &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
523       if (auto *ND = Corrected.getFoundDecl())
524         Found.addDecl(ND);
525       FilterAcceptableTemplateNames(Found);
526       if (Found.isAmbiguous()) {
527         Found.clear();
528       } else if (!Found.empty()) {
529         Found.setLookupName(Corrected.getCorrection());
530         if (LookupCtx) {
531           std::string CorrectedStr(Corrected.getAsString(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(Found, 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(FoundOuter, S);
581     // FIXME: We silently accept an ambiguous lookup here, in violation of
582     // [basic.lookup]/1.
583     FilterAcceptableTemplateNames(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(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(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 
622 void 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>(TemplateName.get())) {
638     NameInfo = DRE->getNameInfo();
639     SS.Adopt(DRE->getQualifierLoc());
640     LookupKind = LookupOrdinaryName;
641     Found = DRE->getFoundDecl();
642   } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
643     NameInfo = ME->getMemberNameInfo();
644     SS.Adopt(ME->getQualifierLoc());
645     LookupKind = LookupMemberName;
646     LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
647     Found = ME->getMemberDecl();
648   } else if (auto *DSDRE =
649                  dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
650     NameInfo = DSDRE->getNameInfo();
651     SS.Adopt(DSDRE->getQualifierLoc());
652     MissingTemplateKeyword = true;
653   } else if (auto *DSME =
654                  dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
655     NameInfo = DSME->getMemberNameInfo();
656     SS.Adopt(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().getAsString() << 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(ND);
682       return Candidate.isKeyword();
683     }
684 
685     std::unique_ptr<CorrectionCandidateCallback> clone() override {
686       return std::make_unique<TemplateCandidateFilter>(*this);
687     }
688   };
689 
690   DeclarationName Name = NameInfo.getName();
691   TemplateCandidateFilter CCC(*this);
692   if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
693                                              CTK_ErrorRecovery, LookupCtx)) {
694     auto *ND = Corrected.getFoundDecl();
695     if (ND)
696       ND = getAsTemplateNameDecl(ND);
697     if (ND || Corrected.isKeyword()) {
698       if (LookupCtx) {
699         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
700         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
701                                 Name.getAsString() == CorrectedStr;
702         diagnoseTypo(Corrected,
703                      PDiag(diag::err_non_template_in_member_template_id_suggest)
704                          << Name << LookupCtx << DroppedSpecifier
705                          << SS.getRange(), false);
706       } else {
707         diagnoseTypo(Corrected,
708                      PDiag(diag::err_non_template_in_template_id_suggest)
709                          << Name, false);
710       }
711       if (Found)
712         Diag(Found->getLocation(),
713              diag::note_non_template_in_template_id_found);
714       return;
715     }
716   }
717 
718   Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
719     << Name << SourceRange(Less, Greater);
720   if (Found)
721     Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
722 }
723 
724 ExprResult
725 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
726                                  SourceLocation TemplateKWLoc,
727                                  const DeclarationNameInfo &NameInfo,
728                                  bool isAddressOfOperand,
729                            const TemplateArgumentListInfo *TemplateArgs) {
730   if (SS.isEmpty()) {
731     // FIXME: This codepath is only used by dependent unqualified names
732     // (e.g. a dependent conversion-function-id, or operator= once we support
733     // it). It doesn't quite do the right thing, and it will silently fail if
734     // getCurrentThisType() returns null.
735     QualType ThisType = getCurrentThisType();
736     if (ThisType.isNull())
737       return ExprError();
738 
739     return CXXDependentScopeMemberExpr::Create(
740         Context, /*Base=*/nullptr, ThisType,
741         /*IsArrow=*/!Context.getLangOpts().HLSL,
742         /*OperatorLoc=*/SourceLocation(),
743         /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
744         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
745   }
746   return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
747 }
748 
749 ExprResult
750 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
751                                 SourceLocation TemplateKWLoc,
752                                 const DeclarationNameInfo &NameInfo,
753                                 const TemplateArgumentListInfo *TemplateArgs) {
754   // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
755   if (!SS.isValid())
756     return CreateRecoveryExpr(
757         SS.getBeginLoc(),
758         TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
759 
760   return DependentScopeDeclRefExpr::Create(
761       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
762       TemplateArgs);
763 }
764 
765 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
766                                           NamedDecl *Instantiation,
767                                           bool InstantiatedFromMember,
768                                           const NamedDecl *Pattern,
769                                           const NamedDecl *PatternDef,
770                                           TemplateSpecializationKind TSK,
771                                           bool Complain /*= true*/) {
772   assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
773          isa<VarDecl>(Instantiation));
774 
775   bool IsEntityBeingDefined = false;
776   if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
777     IsEntityBeingDefined = TD->isBeingDefined();
778 
779   if (PatternDef && !IsEntityBeingDefined) {
780     NamedDecl *SuggestedDef = nullptr;
781     if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
782                                 &SuggestedDef,
783                                 /*OnlyNeedComplete*/ false)) {
784       // If we're allowed to diagnose this and recover, do so.
785       bool Recover = Complain && !isSFINAEContext();
786       if (Complain)
787         diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
788                               Sema::MissingImportKind::Definition, Recover);
789       return !Recover;
790     }
791     return false;
792   }
793 
794   if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
795     return true;
796 
797   QualType InstantiationTy;
798   if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
799     InstantiationTy = Context.getTypeDeclType(TD);
800   if (PatternDef) {
801     Diag(PointOfInstantiation,
802          diag::err_template_instantiate_within_definition)
803       << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
804       << InstantiationTy;
805     // Not much point in noting the template declaration here, since
806     // we're lexically inside it.
807     Instantiation->setInvalidDecl();
808   } else if (InstantiatedFromMember) {
809     if (isa<FunctionDecl>(Instantiation)) {
810       Diag(PointOfInstantiation,
811            diag::err_explicit_instantiation_undefined_member)
812         << /*member function*/ 1 << Instantiation->getDeclName()
813         << Instantiation->getDeclContext();
814       Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
815     } else {
816       assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
817       Diag(PointOfInstantiation,
818            diag::err_implicit_instantiate_member_undefined)
819         << InstantiationTy;
820       Diag(Pattern->getLocation(), diag::note_member_declared_at);
821     }
822   } else {
823     if (isa<FunctionDecl>(Instantiation)) {
824       Diag(PointOfInstantiation,
825            diag::err_explicit_instantiation_undefined_func_template)
826         << Pattern;
827       Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
828     } else if (isa<TagDecl>(Instantiation)) {
829       Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
830         << (TSK != TSK_ImplicitInstantiation)
831         << InstantiationTy;
832       NoteTemplateLocation(*Pattern);
833     } else {
834       assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
835       if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
836         Diag(PointOfInstantiation,
837              diag::err_explicit_instantiation_undefined_var_template)
838           << Instantiation;
839         Instantiation->setInvalidDecl();
840       } else
841         Diag(PointOfInstantiation,
842              diag::err_explicit_instantiation_undefined_member)
843           << /*static data member*/ 2 << Instantiation->getDeclName()
844           << Instantiation->getDeclContext();
845       Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
846     }
847   }
848 
849   // In general, Instantiation isn't marked invalid to get more than one
850   // error for multiple undefined instantiations. But the code that does
851   // explicit declaration -> explicit definition conversion can't handle
852   // invalid declarations, so mark as invalid in that case.
853   if (TSK == TSK_ExplicitInstantiationDeclaration)
854     Instantiation->setInvalidDecl();
855   return true;
856 }
857 
858 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
859                                            bool SupportedForCompatibility) {
860   assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
861 
862   // C++23 [temp.local]p6:
863   //   The name of a template-parameter shall not be bound to any following.
864   //   declaration whose locus is contained by the scope to which the
865   //   template-parameter belongs.
866   //
867   // When MSVC compatibility is enabled, the diagnostic is always a warning
868   // by default. Otherwise, it an error unless SupportedForCompatibility is
869   // true, in which case it is a default-to-error warning.
870   unsigned DiagId =
871       getLangOpts().MSVCCompat
872           ? diag::ext_template_param_shadow
873           : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
874                                        : diag::err_template_param_shadow);
875   const auto *ND = cast<NamedDecl>(PrevDecl);
876   Diag(Loc, DiagId) << ND->getDeclName();
877   NoteTemplateParameterLocation(*ND);
878 }
879 
880 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
881   if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
882     D = Temp->getTemplatedDecl();
883     return Temp;
884   }
885   return nullptr;
886 }
887 
888 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
889                                              SourceLocation EllipsisLoc) const {
890   assert(Kind == Template &&
891          "Only template template arguments can be pack expansions here");
892   assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
893          "Template template argument pack expansion without packs");
894   ParsedTemplateArgument Result(*this);
895   Result.EllipsisLoc = EllipsisLoc;
896   return Result;
897 }
898 
899 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
900                                             const ParsedTemplateArgument &Arg) {
901 
902   switch (Arg.getKind()) {
903   case ParsedTemplateArgument::Type: {
904     TypeSourceInfo *DI;
905     QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
906     if (!DI)
907       DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
908     return TemplateArgumentLoc(TemplateArgument(T), DI);
909   }
910 
911   case ParsedTemplateArgument::NonType: {
912     Expr *E = static_cast<Expr *>(Arg.getAsExpr());
913     return TemplateArgumentLoc(TemplateArgument(E), E);
914   }
915 
916   case ParsedTemplateArgument::Template: {
917     TemplateName Template = Arg.getAsTemplate().get();
918     TemplateArgument TArg;
919     if (Arg.getEllipsisLoc().isValid())
920       TArg = TemplateArgument(Template, std::optional<unsigned int>());
921     else
922       TArg = Template;
923     return TemplateArgumentLoc(
924         SemaRef.Context, TArg,
925         Arg.getScopeSpec().getWithLocInContext(SemaRef.Context),
926         Arg.getLocation(), Arg.getEllipsisLoc());
927   }
928   }
929 
930   llvm_unreachable("Unhandled parsed template argument");
931 }
932 
933 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
934                                       TemplateArgumentListInfo &TemplateArgs) {
935  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
936    TemplateArgs.addArgument(translateTemplateArgument(*this,
937                                                       TemplateArgsIn[I]));
938 }
939 
940 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
941                                                  SourceLocation Loc,
942                                                  const IdentifierInfo *Name) {
943   NamedDecl *PrevDecl =
944       SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
945                                RedeclarationKind::ForVisibleRedeclaration);
946   if (PrevDecl && PrevDecl->isTemplateParameter())
947     SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
948 }
949 
950 ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
951   TypeSourceInfo *TInfo;
952   QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
953   if (T.isNull())
954     return ParsedTemplateArgument();
955   assert(TInfo && "template argument with no location");
956 
957   // If we might have formed a deduced template specialization type, convert
958   // it to a template template argument.
959   if (getLangOpts().CPlusPlus17) {
960     TypeLoc TL = TInfo->getTypeLoc();
961     SourceLocation EllipsisLoc;
962     if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
963       EllipsisLoc = PET.getEllipsisLoc();
964       TL = PET.getPatternLoc();
965     }
966 
967     CXXScopeSpec SS;
968     if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
969       SS.Adopt(ET.getQualifierLoc());
970       TL = ET.getNamedTypeLoc();
971     }
972 
973     if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
974       TemplateName Name = DTST.getTypePtr()->getTemplateName();
975       ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
976                                     DTST.getTemplateNameLoc());
977       if (EllipsisLoc.isValid())
978         Result = Result.getTemplatePackExpansion(EllipsisLoc);
979       return Result;
980     }
981   }
982 
983   // This is a normal type template argument. Note, if the type template
984   // argument is an injected-class-name for a template, it has a dual nature
985   // and can be used as either a type or a template. We handle that in
986   // convertTypeTemplateArgumentToTemplate.
987   return ParsedTemplateArgument(ParsedTemplateArgument::Type,
988                                 ParsedType.get().getAsOpaquePtr(),
989                                 TInfo->getTypeLoc().getBeginLoc());
990 }
991 
992 NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
993                                     SourceLocation EllipsisLoc,
994                                     SourceLocation KeyLoc,
995                                     IdentifierInfo *ParamName,
996                                     SourceLocation ParamNameLoc,
997                                     unsigned Depth, unsigned Position,
998                                     SourceLocation EqualLoc,
999                                     ParsedType DefaultArg,
1000                                     bool HasTypeConstraint) {
1001   assert(S->isTemplateParamScope() &&
1002          "Template type parameter not in template parameter scope!");
1003 
1004   bool IsParameterPack = EllipsisLoc.isValid();
1005   TemplateTypeParmDecl *Param
1006     = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1007                                    KeyLoc, ParamNameLoc, Depth, Position,
1008                                    ParamName, Typename, IsParameterPack,
1009                                    HasTypeConstraint);
1010   Param->setAccess(AS_public);
1011 
1012   if (Param->isParameterPack())
1013     if (auto *LSI = getEnclosingLambda())
1014       LSI->LocalPacks.push_back(Param);
1015 
1016   if (ParamName) {
1017     maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1018 
1019     // Add the template parameter into the current scope.
1020     S->AddDecl(Param);
1021     IdResolver.AddDecl(Param);
1022   }
1023 
1024   // C++0x [temp.param]p9:
1025   //   A default template-argument may be specified for any kind of
1026   //   template-parameter that is not a template parameter pack.
1027   if (DefaultArg && IsParameterPack) {
1028     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1029     DefaultArg = nullptr;
1030   }
1031 
1032   // Handle the default argument, if provided.
1033   if (DefaultArg) {
1034     TypeSourceInfo *DefaultTInfo;
1035     GetTypeFromParser(DefaultArg, &DefaultTInfo);
1036 
1037     assert(DefaultTInfo && "expected source information for type");
1038 
1039     // Check for unexpanded parameter packs.
1040     if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1041                                         UPPC_DefaultArgument))
1042       return Param;
1043 
1044     // Check the template argument itself.
1045     if (CheckTemplateArgument(DefaultTInfo)) {
1046       Param->setInvalidDecl();
1047       return Param;
1048     }
1049 
1050     Param->setDefaultArgument(
1051         Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1052   }
1053 
1054   return Param;
1055 }
1056 
1057 /// Convert the parser's template argument list representation into our form.
1058 static TemplateArgumentListInfo
1059 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1060   TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1061                                         TemplateId.RAngleLoc);
1062   ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1063                                      TemplateId.NumArgs);
1064   S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1065   return TemplateArgs;
1066 }
1067 
1068 bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1069 
1070   TemplateName TN = TypeConstr->Template.get();
1071   ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1072 
1073   // C++2a [temp.param]p4:
1074   //     [...] The concept designated by a type-constraint shall be a type
1075   //     concept ([temp.concept]).
1076   if (!CD->isTypeConcept()) {
1077     Diag(TypeConstr->TemplateNameLoc,
1078          diag::err_type_constraint_non_type_concept);
1079     return true;
1080   }
1081 
1082   if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1083     return true;
1084 
1085   bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1086 
1087   if (!WereArgsSpecified &&
1088       CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1089     Diag(TypeConstr->TemplateNameLoc,
1090          diag::err_type_constraint_missing_arguments)
1091         << CD;
1092     return true;
1093   }
1094   return false;
1095 }
1096 
1097 bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1098                                TemplateIdAnnotation *TypeConstr,
1099                                TemplateTypeParmDecl *ConstrainedParameter,
1100                                SourceLocation EllipsisLoc) {
1101   return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1102                              false);
1103 }
1104 
1105 bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1106                                TemplateIdAnnotation *TypeConstr,
1107                                TemplateTypeParmDecl *ConstrainedParameter,
1108                                SourceLocation EllipsisLoc,
1109                                bool AllowUnexpandedPack) {
1110 
1111   if (CheckTypeConstraint(TypeConstr))
1112     return true;
1113 
1114   TemplateName TN = TypeConstr->Template.get();
1115   ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1116   UsingShadowDecl *USD = TN.getAsUsingShadowDecl();
1117 
1118   DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1119                                   TypeConstr->TemplateNameLoc);
1120 
1121   TemplateArgumentListInfo TemplateArgs;
1122   if (TypeConstr->LAngleLoc.isValid()) {
1123     TemplateArgs =
1124         makeTemplateArgumentListInfo(*this, *TypeConstr);
1125 
1126     if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1127       for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1128         if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint))
1129           return true;
1130       }
1131     }
1132   }
1133   return AttachTypeConstraint(
1134       SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1135       ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1136       TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1137       ConstrainedParameter, Context.getTypeDeclType(ConstrainedParameter),
1138       EllipsisLoc);
1139 }
1140 
1141 template <typename ArgumentLocAppender>
1142 static ExprResult formImmediatelyDeclaredConstraint(
1143     Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1144     ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1145     SourceLocation RAngleLoc, QualType ConstrainedType,
1146     SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1147     SourceLocation EllipsisLoc) {
1148 
1149   TemplateArgumentListInfo ConstraintArgs;
1150   ConstraintArgs.addArgument(
1151     S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1152                                     /*NTTPType=*/QualType(), ParamNameLoc));
1153 
1154   ConstraintArgs.setRAngleLoc(RAngleLoc);
1155   ConstraintArgs.setLAngleLoc(LAngleLoc);
1156   Appender(ConstraintArgs);
1157 
1158   // C++2a [temp.param]p4:
1159   //     [...] This constraint-expression E is called the immediately-declared
1160   //     constraint of T. [...]
1161   CXXScopeSpec SS;
1162   SS.Adopt(NS);
1163   ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1164       SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1165       /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, NamedConcept,
1166       &ConstraintArgs);
1167   if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1168     return ImmediatelyDeclaredConstraint;
1169 
1170   // C++2a [temp.param]p4:
1171   //     [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1172   //
1173   // We have the following case:
1174   //
1175   // template<typename T> concept C1 = true;
1176   // template<C1... T> struct s1;
1177   //
1178   // The constraint: (C1<T> && ...)
1179   //
1180   // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1181   // any unqualified lookups for 'operator&&' here.
1182   return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1183                             /*LParenLoc=*/SourceLocation(),
1184                             ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1185                             EllipsisLoc, /*RHS=*/nullptr,
1186                             /*RParenLoc=*/SourceLocation(),
1187                             /*NumExpansions=*/std::nullopt);
1188 }
1189 
1190 bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1191                                 DeclarationNameInfo NameInfo,
1192                                 ConceptDecl *NamedConcept, NamedDecl *FoundDecl,
1193                                 const TemplateArgumentListInfo *TemplateArgs,
1194                                 TemplateTypeParmDecl *ConstrainedParameter,
1195                                 QualType ConstrainedType,
1196                                 SourceLocation EllipsisLoc) {
1197   // C++2a [temp.param]p4:
1198   //     [...] If Q is of the form C<A1, ..., An>, then let E' be
1199   //     C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1200   const ASTTemplateArgumentListInfo *ArgsAsWritten =
1201     TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1202                                                        *TemplateArgs) : nullptr;
1203 
1204   QualType ParamAsArgument = ConstrainedType;
1205 
1206   ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1207       *this, NS, NameInfo, NamedConcept, FoundDecl,
1208       TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1209       TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1210       ParamAsArgument, ConstrainedParameter->getLocation(),
1211       [&](TemplateArgumentListInfo &ConstraintArgs) {
1212         if (TemplateArgs)
1213           for (const auto &ArgLoc : TemplateArgs->arguments())
1214             ConstraintArgs.addArgument(ArgLoc);
1215       },
1216       EllipsisLoc);
1217   if (ImmediatelyDeclaredConstraint.isInvalid())
1218     return true;
1219 
1220   auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1221                                       /*TemplateKWLoc=*/SourceLocation{},
1222                                       /*ConceptNameInfo=*/NameInfo,
1223                                       /*FoundDecl=*/FoundDecl,
1224                                       /*NamedConcept=*/NamedConcept,
1225                                       /*ArgsWritten=*/ArgsAsWritten);
1226   ConstrainedParameter->setTypeConstraint(CL,
1227                                           ImmediatelyDeclaredConstraint.get());
1228   return false;
1229 }
1230 
1231 bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1232                                 NonTypeTemplateParmDecl *NewConstrainedParm,
1233                                 NonTypeTemplateParmDecl *OrigConstrainedParm,
1234                                 SourceLocation EllipsisLoc) {
1235   if (NewConstrainedParm->getType() != TL.getType() ||
1236       TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1237     Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1238          diag::err_unsupported_placeholder_constraint)
1239         << NewConstrainedParm->getTypeSourceInfo()
1240                ->getTypeLoc()
1241                .getSourceRange();
1242     return true;
1243   }
1244   // FIXME: Concepts: This should be the type of the placeholder, but this is
1245   // unclear in the wording right now.
1246   DeclRefExpr *Ref =
1247       BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1248                        VK_PRValue, OrigConstrainedParm->getLocation());
1249   if (!Ref)
1250     return true;
1251   ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1252       *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
1253       TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1254       TL.getRAngleLoc(), BuildDecltypeType(Ref),
1255       OrigConstrainedParm->getLocation(),
1256       [&](TemplateArgumentListInfo &ConstraintArgs) {
1257         for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1258           ConstraintArgs.addArgument(TL.getArgLoc(I));
1259       },
1260       EllipsisLoc);
1261   if (ImmediatelyDeclaredConstraint.isInvalid() ||
1262       !ImmediatelyDeclaredConstraint.isUsable())
1263     return true;
1264 
1265   NewConstrainedParm->setPlaceholderTypeConstraint(
1266       ImmediatelyDeclaredConstraint.get());
1267   return false;
1268 }
1269 
1270 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1271                                                  SourceLocation Loc) {
1272   if (TSI->getType()->isUndeducedType()) {
1273     // C++17 [temp.dep.expr]p3:
1274     //   An id-expression is type-dependent if it contains
1275     //    - an identifier associated by name lookup with a non-type
1276     //      template-parameter declared with a type that contains a
1277     //      placeholder type (7.1.7.4),
1278     TSI = SubstAutoTypeSourceInfoDependent(TSI);
1279   }
1280 
1281   return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1282 }
1283 
1284 bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1285   if (T->isDependentType())
1286     return false;
1287 
1288   if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1289     return true;
1290 
1291   if (T->isStructuralType())
1292     return false;
1293 
1294   // Structural types are required to be object types or lvalue references.
1295   if (T->isRValueReferenceType()) {
1296     Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1297     return true;
1298   }
1299 
1300   // Don't mention structural types in our diagnostic prior to C++20. Also,
1301   // there's not much more we can say about non-scalar non-class types --
1302   // because we can't see functions or arrays here, those can only be language
1303   // extensions.
1304   if (!getLangOpts().CPlusPlus20 ||
1305       (!T->isScalarType() && !T->isRecordType())) {
1306     Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1307     return true;
1308   }
1309 
1310   // Structural types are required to be literal types.
1311   if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1312     return true;
1313 
1314   Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1315 
1316   // Drill down into the reason why the class is non-structural.
1317   while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1318     // All members are required to be public and non-mutable, and can't be of
1319     // rvalue reference type. Check these conditions first to prefer a "local"
1320     // reason over a more distant one.
1321     for (const FieldDecl *FD : RD->fields()) {
1322       if (FD->getAccess() != AS_public) {
1323         Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1324         return true;
1325       }
1326       if (FD->isMutable()) {
1327         Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1328         return true;
1329       }
1330       if (FD->getType()->isRValueReferenceType()) {
1331         Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1332             << T;
1333         return true;
1334       }
1335     }
1336 
1337     // All bases are required to be public.
1338     for (const auto &BaseSpec : RD->bases()) {
1339       if (BaseSpec.getAccessSpecifier() != AS_public) {
1340         Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1341             << T << 1;
1342         return true;
1343       }
1344     }
1345 
1346     // All subobjects are required to be of structural types.
1347     SourceLocation SubLoc;
1348     QualType SubType;
1349     int Kind = -1;
1350 
1351     for (const FieldDecl *FD : RD->fields()) {
1352       QualType T = Context.getBaseElementType(FD->getType());
1353       if (!T->isStructuralType()) {
1354         SubLoc = FD->getLocation();
1355         SubType = T;
1356         Kind = 0;
1357         break;
1358       }
1359     }
1360 
1361     if (Kind == -1) {
1362       for (const auto &BaseSpec : RD->bases()) {
1363         QualType T = BaseSpec.getType();
1364         if (!T->isStructuralType()) {
1365           SubLoc = BaseSpec.getBaseTypeLoc();
1366           SubType = T;
1367           Kind = 1;
1368           break;
1369         }
1370       }
1371     }
1372 
1373     assert(Kind != -1 && "couldn't find reason why type is not structural");
1374     Diag(SubLoc, diag::note_not_structural_subobject)
1375         << T << Kind << SubType;
1376     T = SubType;
1377     RD = T->getAsCXXRecordDecl();
1378   }
1379 
1380   return true;
1381 }
1382 
1383 QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1384                                                  SourceLocation Loc) {
1385   // We don't allow variably-modified types as the type of non-type template
1386   // parameters.
1387   if (T->isVariablyModifiedType()) {
1388     Diag(Loc, diag::err_variably_modified_nontype_template_param)
1389       << T;
1390     return QualType();
1391   }
1392 
1393   // C++ [temp.param]p4:
1394   //
1395   // A non-type template-parameter shall have one of the following
1396   // (optionally cv-qualified) types:
1397   //
1398   //       -- integral or enumeration type,
1399   if (T->isIntegralOrEnumerationType() ||
1400       //   -- pointer to object or pointer to function,
1401       T->isPointerType() ||
1402       //   -- lvalue reference to object or lvalue reference to function,
1403       T->isLValueReferenceType() ||
1404       //   -- pointer to member,
1405       T->isMemberPointerType() ||
1406       //   -- std::nullptr_t, or
1407       T->isNullPtrType() ||
1408       //   -- a type that contains a placeholder type.
1409       T->isUndeducedType()) {
1410     // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1411     // are ignored when determining its type.
1412     return T.getUnqualifiedType();
1413   }
1414 
1415   // C++ [temp.param]p8:
1416   //
1417   //   A non-type template-parameter of type "array of T" or
1418   //   "function returning T" is adjusted to be of type "pointer to
1419   //   T" or "pointer to function returning T", respectively.
1420   if (T->isArrayType() || T->isFunctionType())
1421     return Context.getDecayedType(T);
1422 
1423   // If T is a dependent type, we can't do the check now, so we
1424   // assume that it is well-formed. Note that stripping off the
1425   // qualifiers here is not really correct if T turns out to be
1426   // an array type, but we'll recompute the type everywhere it's
1427   // used during instantiation, so that should be OK. (Using the
1428   // qualified type is equally wrong.)
1429   if (T->isDependentType())
1430     return T.getUnqualifiedType();
1431 
1432   // C++20 [temp.param]p6:
1433   //   -- a structural type
1434   if (RequireStructuralType(T, Loc))
1435     return QualType();
1436 
1437   if (!getLangOpts().CPlusPlus20) {
1438     // FIXME: Consider allowing structural types as an extension in C++17. (In
1439     // earlier language modes, the template argument evaluation rules are too
1440     // inflexible.)
1441     Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1442     return QualType();
1443   }
1444 
1445   Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1446   return T.getUnqualifiedType();
1447 }
1448 
1449 NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1450                                           unsigned Depth,
1451                                           unsigned Position,
1452                                           SourceLocation EqualLoc,
1453                                           Expr *Default) {
1454   TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1455 
1456   // Check that we have valid decl-specifiers specified.
1457   auto CheckValidDeclSpecifiers = [this, &D] {
1458     // C++ [temp.param]
1459     // p1
1460     //   template-parameter:
1461     //     ...
1462     //     parameter-declaration
1463     // p2
1464     //   ... A storage class shall not be specified in a template-parameter
1465     //   declaration.
1466     // [dcl.typedef]p1:
1467     //   The typedef specifier [...] shall not be used in the decl-specifier-seq
1468     //   of a parameter-declaration
1469     const DeclSpec &DS = D.getDeclSpec();
1470     auto EmitDiag = [this](SourceLocation Loc) {
1471       Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1472           << FixItHint::CreateRemoval(Loc);
1473     };
1474     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1475       EmitDiag(DS.getStorageClassSpecLoc());
1476 
1477     if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1478       EmitDiag(DS.getThreadStorageClassSpecLoc());
1479 
1480     // [dcl.inline]p1:
1481     //   The inline specifier can be applied only to the declaration or
1482     //   definition of a variable or function.
1483 
1484     if (DS.isInlineSpecified())
1485       EmitDiag(DS.getInlineSpecLoc());
1486 
1487     // [dcl.constexpr]p1:
1488     //   The constexpr specifier shall be applied only to the definition of a
1489     //   variable or variable template or the declaration of a function or
1490     //   function template.
1491 
1492     if (DS.hasConstexprSpecifier())
1493       EmitDiag(DS.getConstexprSpecLoc());
1494 
1495     // [dcl.fct.spec]p1:
1496     //   Function-specifiers can be used only in function declarations.
1497 
1498     if (DS.isVirtualSpecified())
1499       EmitDiag(DS.getVirtualSpecLoc());
1500 
1501     if (DS.hasExplicitSpecifier())
1502       EmitDiag(DS.getExplicitSpecLoc());
1503 
1504     if (DS.isNoreturnSpecified())
1505       EmitDiag(DS.getNoreturnSpecLoc());
1506   };
1507 
1508   CheckValidDeclSpecifiers();
1509 
1510   if (const auto *T = TInfo->getType()->getContainedDeducedType())
1511     if (isa<AutoType>(T))
1512       Diag(D.getIdentifierLoc(),
1513            diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1514           << QualType(TInfo->getType()->getContainedAutoType(), 0);
1515 
1516   assert(S->isTemplateParamScope() &&
1517          "Non-type template parameter not in template parameter scope!");
1518   bool Invalid = false;
1519 
1520   QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1521   if (T.isNull()) {
1522     T = Context.IntTy; // Recover with an 'int' type.
1523     Invalid = true;
1524   }
1525 
1526   CheckFunctionOrTemplateParamDeclarator(S, D);
1527 
1528   const IdentifierInfo *ParamName = D.getIdentifier();
1529   bool IsParameterPack = D.hasEllipsis();
1530   NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1531       Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1532       D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1533       TInfo);
1534   Param->setAccess(AS_public);
1535 
1536   if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1537     if (TL.isConstrained())
1538       if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1539         Invalid = true;
1540 
1541   if (Invalid)
1542     Param->setInvalidDecl();
1543 
1544   if (Param->isParameterPack())
1545     if (auto *LSI = getEnclosingLambda())
1546       LSI->LocalPacks.push_back(Param);
1547 
1548   if (ParamName) {
1549     maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1550                                          ParamName);
1551 
1552     // Add the template parameter into the current scope.
1553     S->AddDecl(Param);
1554     IdResolver.AddDecl(Param);
1555   }
1556 
1557   // C++0x [temp.param]p9:
1558   //   A default template-argument may be specified for any kind of
1559   //   template-parameter that is not a template parameter pack.
1560   if (Default && IsParameterPack) {
1561     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1562     Default = nullptr;
1563   }
1564 
1565   // Check the well-formedness of the default template argument, if provided.
1566   if (Default) {
1567     // Check for unexpanded parameter packs.
1568     if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1569       return Param;
1570 
1571     Param->setDefaultArgument(
1572         Context, getTrivialTemplateArgumentLoc(TemplateArgument(Default),
1573                                                QualType(), SourceLocation()));
1574   }
1575 
1576   return Param;
1577 }
1578 
1579 NamedDecl *Sema::ActOnTemplateTemplateParameter(
1580     Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
1581     bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *Name,
1582     SourceLocation NameLoc, unsigned Depth, unsigned Position,
1583     SourceLocation EqualLoc, ParsedTemplateArgument Default) {
1584   assert(S->isTemplateParamScope() &&
1585          "Template template parameter not in template parameter scope!");
1586 
1587   // Construct the parameter object.
1588   bool IsParameterPack = EllipsisLoc.isValid();
1589   TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(
1590       Context, Context.getTranslationUnitDecl(),
1591       NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1592       Name, Typename, Params);
1593   Param->setAccess(AS_public);
1594 
1595   if (Param->isParameterPack())
1596     if (auto *LSI = getEnclosingLambda())
1597       LSI->LocalPacks.push_back(Param);
1598 
1599   // If the template template parameter has a name, then link the identifier
1600   // into the scope and lookup mechanisms.
1601   if (Name) {
1602     maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1603 
1604     S->AddDecl(Param);
1605     IdResolver.AddDecl(Param);
1606   }
1607 
1608   if (Params->size() == 0) {
1609     Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1610     << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1611     Param->setInvalidDecl();
1612   }
1613 
1614   // C++0x [temp.param]p9:
1615   //   A default template-argument may be specified for any kind of
1616   //   template-parameter that is not a template parameter pack.
1617   if (IsParameterPack && !Default.isInvalid()) {
1618     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1619     Default = ParsedTemplateArgument();
1620   }
1621 
1622   if (!Default.isInvalid()) {
1623     // Check only that we have a template template argument. We don't want to
1624     // try to check well-formedness now, because our template template parameter
1625     // might have dependent types in its template parameters, which we wouldn't
1626     // be able to match now.
1627     //
1628     // If none of the template template parameter's template arguments mention
1629     // other template parameters, we could actually perform more checking here.
1630     // However, it isn't worth doing.
1631     TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1632     if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1633       Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1634         << DefaultArg.getSourceRange();
1635       return Param;
1636     }
1637 
1638     // Check for unexpanded parameter packs.
1639     if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1640                                         DefaultArg.getArgument().getAsTemplate(),
1641                                         UPPC_DefaultArgument))
1642       return Param;
1643 
1644     Param->setDefaultArgument(Context, DefaultArg);
1645   }
1646 
1647   return Param;
1648 }
1649 
1650 namespace {
1651 class ConstraintRefersToContainingTemplateChecker
1652     : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1653   bool Result = false;
1654   const FunctionDecl *Friend = nullptr;
1655   unsigned TemplateDepth = 0;
1656 
1657   // Check a record-decl that we've seen to see if it is a lexical parent of the
1658   // Friend, likely because it was referred to without its template arguments.
1659   void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1660     CheckingRD = CheckingRD->getMostRecentDecl();
1661     if (!CheckingRD->isTemplated())
1662       return;
1663 
1664     for (const DeclContext *DC = Friend->getLexicalDeclContext();
1665          DC && !DC->isFileContext(); DC = DC->getParent())
1666       if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1667         if (CheckingRD == RD->getMostRecentDecl())
1668           Result = true;
1669   }
1670 
1671   void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1672     if (D->getDepth() < TemplateDepth)
1673       Result = true;
1674 
1675     // Necessary because the type of the NTTP might be what refers to the parent
1676     // constriant.
1677     TransformType(D->getType());
1678   }
1679 
1680 public:
1681   using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>;
1682 
1683   ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1684                                               const FunctionDecl *Friend,
1685                                               unsigned TemplateDepth)
1686       : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1687   bool getResult() const { return Result; }
1688 
1689   // This should be the only template parm type that we have to deal with.
1690   // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1691   // FunctionParmPackExpr are all partially substituted, which cannot happen
1692   // with concepts at this point in translation.
1693   using inherited::TransformTemplateTypeParmType;
1694   QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1695                                          TemplateTypeParmTypeLoc TL, bool) {
1696     if (TL.getDecl()->getDepth() < TemplateDepth)
1697       Result = true;
1698     return inherited::TransformTemplateTypeParmType(
1699         TLB, TL,
1700         /*SuppressObjCLifetime=*/false);
1701   }
1702 
1703   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1704     if (!D)
1705       return D;
1706     // FIXME : This is possibly an incomplete list, but it is unclear what other
1707     // Decl kinds could be used to refer to the template parameters.  This is a
1708     // best guess so far based on examples currently available, but the
1709     // unreachable should catch future instances/cases.
1710     if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1711       TransformType(TD->getUnderlyingType());
1712     else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1713       CheckNonTypeTemplateParmDecl(NTTPD);
1714     else if (auto *VD = dyn_cast<ValueDecl>(D))
1715       TransformType(VD->getType());
1716     else if (auto *TD = dyn_cast<TemplateDecl>(D))
1717       TransformTemplateParameterList(TD->getTemplateParameters());
1718     else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1719       CheckIfContainingRecord(RD);
1720     else if (isa<NamedDecl>(D)) {
1721       // No direct types to visit here I believe.
1722     } else
1723       llvm_unreachable("Don't know how to handle this declaration type yet");
1724     return D;
1725   }
1726 };
1727 } // namespace
1728 
1729 bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1730     const FunctionDecl *Friend, unsigned TemplateDepth,
1731     const Expr *Constraint) {
1732   assert(Friend->getFriendObjectKind() && "Only works on a friend");
1733   ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1734                                                       TemplateDepth);
1735   Checker.TransformExpr(const_cast<Expr *>(Constraint));
1736   return Checker.getResult();
1737 }
1738 
1739 TemplateParameterList *
1740 Sema::ActOnTemplateParameterList(unsigned Depth,
1741                                  SourceLocation ExportLoc,
1742                                  SourceLocation TemplateLoc,
1743                                  SourceLocation LAngleLoc,
1744                                  ArrayRef<NamedDecl *> Params,
1745                                  SourceLocation RAngleLoc,
1746                                  Expr *RequiresClause) {
1747   if (ExportLoc.isValid())
1748     Diag(ExportLoc, diag::warn_template_export_unsupported);
1749 
1750   for (NamedDecl *P : Params)
1751     warnOnReservedIdentifier(P);
1752 
1753   return TemplateParameterList::Create(
1754       Context, TemplateLoc, LAngleLoc,
1755       llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1756 }
1757 
1758 static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1759                                    const CXXScopeSpec &SS) {
1760   if (SS.isSet())
1761     T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1762 }
1763 
1764 // Returns the template parameter list with all default template argument
1765 // information.
1766 TemplateParameterList *Sema::GetTemplateParameterList(TemplateDecl *TD) {
1767   // Make sure we get the template parameter list from the most
1768   // recent declaration, since that is the only one that is guaranteed to
1769   // have all the default template argument information.
1770   Decl *D = TD->getMostRecentDecl();
1771   // C++11 N3337 [temp.param]p12:
1772   // A default template argument shall not be specified in a friend class
1773   // template declaration.
1774   //
1775   // Skip past friend *declarations* because they are not supposed to contain
1776   // default template arguments. Moreover, these declarations may introduce
1777   // template parameters living in different template depths than the
1778   // corresponding template parameters in TD, causing unmatched constraint
1779   // substitution.
1780   //
1781   // FIXME: Diagnose such cases within a class template:
1782   //  template <class T>
1783   //  struct S {
1784   //    template <class = void> friend struct C;
1785   //  };
1786   //  template struct S<int>;
1787   while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1788          D->getPreviousDecl())
1789     D = D->getPreviousDecl();
1790   return cast<TemplateDecl>(D)->getTemplateParameters();
1791 }
1792 
1793 DeclResult Sema::CheckClassTemplate(
1794     Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1795     CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1796     const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1797     AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1798     SourceLocation FriendLoc,
1799     ArrayRef<TemplateParameterList *> OuterTemplateParamLists,
1800     bool IsMemberSpecialization, SkipBodyInfo *SkipBody) {
1801   assert(TemplateParams && TemplateParams->size() > 0 &&
1802          "No template parameters");
1803   assert(TUK != TagUseKind::Reference &&
1804          "Can only declare or define class templates");
1805   bool Invalid = false;
1806 
1807   // Check that we can declare a template here.
1808   if (CheckTemplateDeclScope(S, TemplateParams))
1809     return true;
1810 
1811   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1812   assert(Kind != TagTypeKind::Enum &&
1813          "can't build template of enumerated type");
1814 
1815   // There is no such thing as an unnamed class template.
1816   if (!Name) {
1817     Diag(KWLoc, diag::err_template_unnamed_class);
1818     return true;
1819   }
1820 
1821   // Find any previous declaration with this name. For a friend with no
1822   // scope explicitly specified, we only look for tag declarations (per
1823   // C++11 [basic.lookup.elab]p2).
1824   DeclContext *SemanticContext;
1825   LookupResult Previous(*this, Name, NameLoc,
1826                         (SS.isEmpty() && TUK == TagUseKind::Friend)
1827                             ? LookupTagName
1828                             : LookupOrdinaryName,
1829                         forRedeclarationInCurContext());
1830   if (SS.isNotEmpty() && !SS.isInvalid()) {
1831     SemanticContext = computeDeclContext(SS, true);
1832     if (!SemanticContext) {
1833       // FIXME: Horrible, horrible hack! We can't currently represent this
1834       // in the AST, and historically we have just ignored such friend
1835       // class templates, so don't complain here.
1836       Diag(NameLoc, TUK == TagUseKind::Friend
1837                         ? diag::warn_template_qualified_friend_ignored
1838                         : diag::err_template_qualified_declarator_no_match)
1839           << SS.getScopeRep() << SS.getRange();
1840       return TUK != TagUseKind::Friend;
1841     }
1842 
1843     if (RequireCompleteDeclContext(SS, SemanticContext))
1844       return true;
1845 
1846     // If we're adding a template to a dependent context, we may need to
1847     // rebuilding some of the types used within the template parameter list,
1848     // now that we know what the current instantiation is.
1849     if (SemanticContext->isDependentContext()) {
1850       ContextRAII SavedContext(*this, SemanticContext);
1851       if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1852         Invalid = true;
1853     }
1854 
1855     if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1856       diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1857                                    /*TemplateId-*/ nullptr,
1858                                    /*IsMemberSpecialization*/ false);
1859 
1860     LookupQualifiedName(Previous, SemanticContext);
1861   } else {
1862     SemanticContext = CurContext;
1863 
1864     // C++14 [class.mem]p14:
1865     //   If T is the name of a class, then each of the following shall have a
1866     //   name different from T:
1867     //    -- every member template of class T
1868     if (TUK != TagUseKind::Friend &&
1869         DiagnoseClassNameShadow(SemanticContext,
1870                                 DeclarationNameInfo(Name, NameLoc)))
1871       return true;
1872 
1873     LookupName(Previous, S);
1874   }
1875 
1876   if (Previous.isAmbiguous())
1877     return true;
1878 
1879   // Let the template parameter scope enter the lookup chain of the current
1880   // class template. For example, given
1881   //
1882   //  namespace ns {
1883   //    template <class> bool Param = false;
1884   //    template <class T> struct N;
1885   //  }
1886   //
1887   //  template <class Param> struct ns::N { void foo(Param); };
1888   //
1889   // When we reference Param inside the function parameter list, our name lookup
1890   // chain for it should be like:
1891   //  FunctionScope foo
1892   //  -> RecordScope N
1893   //  -> TemplateParamScope (where we will find Param)
1894   //  -> NamespaceScope ns
1895   //
1896   // See also CppLookupName().
1897   if (S->isTemplateParamScope())
1898     EnterTemplatedContext(S, SemanticContext);
1899 
1900   NamedDecl *PrevDecl = nullptr;
1901   if (Previous.begin() != Previous.end())
1902     PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1903 
1904   if (PrevDecl && PrevDecl->isTemplateParameter()) {
1905     // Maybe we will complain about the shadowed template parameter.
1906     DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1907     // Just pretend that we didn't see the previous declaration.
1908     PrevDecl = nullptr;
1909   }
1910 
1911   // If there is a previous declaration with the same name, check
1912   // whether this is a valid redeclaration.
1913   ClassTemplateDecl *PrevClassTemplate =
1914       dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1915 
1916   // We may have found the injected-class-name of a class template,
1917   // class template partial specialization, or class template specialization.
1918   // In these cases, grab the template that is being defined or specialized.
1919   if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
1920       cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1921     PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1922     PrevClassTemplate
1923       = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1924     if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1925       PrevClassTemplate
1926         = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1927             ->getSpecializedTemplate();
1928     }
1929   }
1930 
1931   if (TUK == TagUseKind::Friend) {
1932     // C++ [namespace.memdef]p3:
1933     //   [...] When looking for a prior declaration of a class or a function
1934     //   declared as a friend, and when the name of the friend class or
1935     //   function is neither a qualified name nor a template-id, scopes outside
1936     //   the innermost enclosing namespace scope are not considered.
1937     if (!SS.isSet()) {
1938       DeclContext *OutermostContext = CurContext;
1939       while (!OutermostContext->isFileContext())
1940         OutermostContext = OutermostContext->getLookupParent();
1941 
1942       if (PrevDecl &&
1943           (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1944            OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1945         SemanticContext = PrevDecl->getDeclContext();
1946       } else {
1947         // Declarations in outer scopes don't matter. However, the outermost
1948         // context we computed is the semantic context for our new
1949         // declaration.
1950         PrevDecl = PrevClassTemplate = nullptr;
1951         SemanticContext = OutermostContext;
1952 
1953         // Check that the chosen semantic context doesn't already contain a
1954         // declaration of this name as a non-tag type.
1955         Previous.clear(LookupOrdinaryName);
1956         DeclContext *LookupContext = SemanticContext;
1957         while (LookupContext->isTransparentContext())
1958           LookupContext = LookupContext->getLookupParent();
1959         LookupQualifiedName(Previous, LookupContext);
1960 
1961         if (Previous.isAmbiguous())
1962           return true;
1963 
1964         if (Previous.begin() != Previous.end())
1965           PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1966       }
1967     }
1968   } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
1969                                         SemanticContext, S, SS.isValid()))
1970     PrevDecl = PrevClassTemplate = nullptr;
1971 
1972   if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1973           PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1974     if (SS.isEmpty() &&
1975         !(PrevClassTemplate &&
1976           PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1977               SemanticContext->getRedeclContext()))) {
1978       Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1979       Diag(Shadow->getTargetDecl()->getLocation(),
1980            diag::note_using_decl_target);
1981       Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1982       // Recover by ignoring the old declaration.
1983       PrevDecl = PrevClassTemplate = nullptr;
1984     }
1985   }
1986 
1987   if (PrevClassTemplate) {
1988     // C++ [temp.class]p4:
1989     //   In a redeclaration, partial specialization, explicit
1990     //   specialization or explicit instantiation of a class template,
1991     //   the class-key shall agree in kind with the original class
1992     //   template declaration (7.1.5.3).
1993     RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1994     if (!isAcceptableTagRedeclaration(
1995             PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
1996       Diag(KWLoc, diag::err_use_with_wrong_tag)
1997         << Name
1998         << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1999       Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2000       Kind = PrevRecordDecl->getTagKind();
2001     }
2002   } else if (PrevDecl) {
2003     // C++ [temp]p5:
2004     //   A class template shall not have the same name as any other
2005     //   template, class, function, object, enumeration, enumerator,
2006     //   namespace, or type in the same scope (3.3), except as specified
2007     //   in (14.5.4).
2008     Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2009     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2010     return true;
2011   }
2012 
2013   if (SS.isSet()) {
2014     // If the name of the template was qualified, we must be defining the
2015     // template out-of-line.
2016     if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2017       Diag(NameLoc, TUK == TagUseKind::Friend
2018                         ? diag::err_friend_decl_does_not_match
2019                         : diag::err_member_decl_does_not_match)
2020           << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2021       Invalid = true;
2022     }
2023   }
2024 
2025   // If this is a templated friend in a dependent context we should not put it
2026   // on the redecl chain. In some cases, the templated friend can be the most
2027   // recent declaration tricking the template instantiator to make substitutions
2028   // there.
2029   // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2030   bool ShouldAddRedecl =
2031       !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2032 
2033   CXXRecordDecl *NewClass =
2034     CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2035                           PrevClassTemplate && ShouldAddRedecl ?
2036                             PrevClassTemplate->getTemplatedDecl() : nullptr,
2037                           /*DelayTypeCreation=*/true);
2038   SetNestedNameSpecifier(*this, NewClass, SS);
2039   if (!OuterTemplateParamLists.empty())
2040     NewClass->setTemplateParameterListsInfo(Context, OuterTemplateParamLists);
2041 
2042   // Add alignment attributes if necessary; these attributes are checked when
2043   // the ASTContext lays out the structure.
2044   if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2045     AddAlignmentAttributesForRecord(NewClass);
2046     AddMsStructLayoutForRecord(NewClass);
2047   }
2048 
2049   ClassTemplateDecl *NewTemplate
2050     = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2051                                 DeclarationName(Name), TemplateParams,
2052                                 NewClass);
2053   // If we are providing an explicit specialization of a member that is a
2054   // class template, make a note of that.
2055   if (IsMemberSpecialization)
2056     NewTemplate->setMemberSpecialization();
2057   if (ShouldAddRedecl)
2058     NewTemplate->setPreviousDecl(PrevClassTemplate);
2059 
2060   NewClass->setDescribedClassTemplate(NewTemplate);
2061 
2062   if (ModulePrivateLoc.isValid())
2063     NewTemplate->setModulePrivate();
2064 
2065   // Build the type for the class template declaration now.
2066   QualType T = NewTemplate->getInjectedClassNameSpecialization();
2067   T = Context.getInjectedClassNameType(NewClass, T);
2068   assert(T->isDependentType() && "Class template type is not dependent?");
2069   (void)T;
2070 
2071   // Set the access specifier.
2072   if (!Invalid && TUK != TagUseKind::Friend &&
2073       NewTemplate->getDeclContext()->isRecord())
2074     SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2075 
2076   // Set the lexical context of these templates
2077   NewClass->setLexicalDeclContext(CurContext);
2078   NewTemplate->setLexicalDeclContext(CurContext);
2079 
2080   // Ensure that the template parameter lists are compatible. Skip this check
2081   // for a friend in a dependent context: the template parameter list itself
2082   // could be dependent.
2083   if (ShouldAddRedecl && PrevClassTemplate &&
2084       !TemplateParameterListsAreEqual(
2085           NewTemplate, TemplateParams, PrevClassTemplate,
2086           PrevClassTemplate->getTemplateParameters(),
2087           /*Complain=*/true, TPL_TemplateMatch))
2088     return true;
2089 
2090   // Check the template parameter list of this declaration, possibly
2091   // merging in the template parameter list from the previous class
2092   // template declaration. Skip this check for a friend in a dependent
2093   // context, because the template parameter list might be dependent.
2094   if (ShouldAddRedecl &&
2095       CheckTemplateParameterList(
2096           TemplateParams,
2097           PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
2098                             : nullptr,
2099           (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2100            SemanticContext->isDependentContext())
2101               ? TPC_ClassTemplateMember
2102           : TUK == TagUseKind::Friend ? TPC_FriendClassTemplate
2103                                       : TPC_ClassTemplate,
2104           SkipBody))
2105     Invalid = true;
2106 
2107   if (TUK == TagUseKind::Definition) {
2108     if (PrevClassTemplate) {
2109       // Check for redefinition of this class template.
2110       if (TagDecl *Def =
2111               PrevClassTemplate->getTemplatedDecl()->getDefinition()) {
2112         // If we have a prior definition that is not visible, treat this as
2113         // simply making that previous definition visible.
2114         NamedDecl *Hidden = nullptr;
2115         if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2116           SkipBody->ShouldSkip = true;
2117           SkipBody->Previous = Def;
2118           auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2119           assert(Tmpl && "original definition of a class template is not a "
2120                          "class template?");
2121           makeMergedDefinitionVisible(Hidden);
2122           makeMergedDefinitionVisible(Tmpl);
2123         } else {
2124           Diag(NameLoc, diag::err_redefinition) << Name;
2125           Diag(Def->getLocation(), diag::note_previous_definition);
2126           // FIXME: Would it make sense to try to "forget" the previous
2127           // definition, as part of error recovery?
2128           return true;
2129         }
2130       }
2131     }
2132 
2133     if (!SkipBody || !SkipBody->ShouldSkip)
2134       NewClass->startDefinition();
2135   }
2136 
2137   ProcessDeclAttributeList(S, NewClass, Attr);
2138   ProcessAPINotes(NewClass);
2139 
2140   if (PrevClassTemplate)
2141     mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2142 
2143   AddPushedVisibilityAttribute(NewClass);
2144   inferGslOwnerPointerAttribute(NewClass);
2145   inferNullableClassAttribute(NewClass);
2146 
2147   if (TUK != TagUseKind::Friend) {
2148     // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2149     Scope *Outer = S;
2150     while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2151       Outer = Outer->getParent();
2152     PushOnScopeChains(NewTemplate, Outer);
2153   } else {
2154     if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2155       NewTemplate->setAccess(PrevClassTemplate->getAccess());
2156       NewClass->setAccess(PrevClassTemplate->getAccess());
2157     }
2158 
2159     NewTemplate->setObjectOfFriendDecl();
2160 
2161     // Friend templates are visible in fairly strange ways.
2162     if (!CurContext->isDependentContext()) {
2163       DeclContext *DC = SemanticContext->getRedeclContext();
2164       DC->makeDeclVisibleInContext(NewTemplate);
2165       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2166         PushOnScopeChains(NewTemplate, EnclosingScope,
2167                           /* AddToContext = */ false);
2168     }
2169 
2170     FriendDecl *Friend = FriendDecl::Create(
2171         Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2172     Friend->setAccess(AS_public);
2173     CurContext->addDecl(Friend);
2174   }
2175 
2176   if (PrevClassTemplate)
2177     CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2178 
2179   if (Invalid) {
2180     NewTemplate->setInvalidDecl();
2181     NewClass->setInvalidDecl();
2182   }
2183 
2184   ActOnDocumentableDecl(NewTemplate);
2185 
2186   if (SkipBody && SkipBody->ShouldSkip)
2187     return SkipBody->Previous;
2188 
2189   return NewTemplate;
2190 }
2191 
2192 /// Diagnose the presence of a default template argument on a
2193 /// template parameter, which is ill-formed in certain contexts.
2194 ///
2195 /// \returns true if the default template argument should be dropped.
2196 static bool DiagnoseDefaultTemplateArgument(Sema &S,
2197                                             Sema::TemplateParamListContext TPC,
2198                                             SourceLocation ParamLoc,
2199                                             SourceRange DefArgRange) {
2200   switch (TPC) {
2201   case Sema::TPC_ClassTemplate:
2202   case Sema::TPC_VarTemplate:
2203   case Sema::TPC_TypeAliasTemplate:
2204     return false;
2205 
2206   case Sema::TPC_FunctionTemplate:
2207   case Sema::TPC_FriendFunctionTemplateDefinition:
2208     // C++ [temp.param]p9:
2209     //   A default template-argument shall not be specified in a
2210     //   function template declaration or a function template
2211     //   definition [...]
2212     //   If a friend function template declaration specifies a default
2213     //   template-argument, that declaration shall be a definition and shall be
2214     //   the only declaration of the function template in the translation unit.
2215     // (C++98/03 doesn't have this wording; see DR226).
2216     S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2217          diag::warn_cxx98_compat_template_parameter_default_in_function_template
2218            : diag::ext_template_parameter_default_in_function_template)
2219       << DefArgRange;
2220     return false;
2221 
2222   case Sema::TPC_ClassTemplateMember:
2223     // C++0x [temp.param]p9:
2224     //   A default template-argument shall not be specified in the
2225     //   template-parameter-lists of the definition of a member of a
2226     //   class template that appears outside of the member's class.
2227     S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2228       << DefArgRange;
2229     return true;
2230 
2231   case Sema::TPC_FriendClassTemplate:
2232   case Sema::TPC_FriendFunctionTemplate:
2233     // C++ [temp.param]p9:
2234     //   A default template-argument shall not be specified in a
2235     //   friend template declaration.
2236     S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2237       << DefArgRange;
2238     return true;
2239 
2240     // FIXME: C++0x [temp.param]p9 allows default template-arguments
2241     // for friend function templates if there is only a single
2242     // declaration (and it is a definition). Strange!
2243   }
2244 
2245   llvm_unreachable("Invalid TemplateParamListContext!");
2246 }
2247 
2248 /// Check for unexpanded parameter packs within the template parameters
2249 /// of a template template parameter, recursively.
2250 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2251                                              TemplateTemplateParmDecl *TTP) {
2252   // A template template parameter which is a parameter pack is also a pack
2253   // expansion.
2254   if (TTP->isParameterPack())
2255     return false;
2256 
2257   TemplateParameterList *Params = TTP->getTemplateParameters();
2258   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2259     NamedDecl *P = Params->getParam(I);
2260     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2261       if (!TTP->isParameterPack())
2262         if (const TypeConstraint *TC = TTP->getTypeConstraint())
2263           if (TC->hasExplicitTemplateArgs())
2264             for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2265               if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2266                                                     Sema::UPPC_TypeConstraint))
2267                 return true;
2268       continue;
2269     }
2270 
2271     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2272       if (!NTTP->isParameterPack() &&
2273           S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2274                                             NTTP->getTypeSourceInfo(),
2275                                       Sema::UPPC_NonTypeTemplateParameterType))
2276         return true;
2277 
2278       continue;
2279     }
2280 
2281     if (TemplateTemplateParmDecl *InnerTTP
2282                                         = dyn_cast<TemplateTemplateParmDecl>(P))
2283       if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2284         return true;
2285   }
2286 
2287   return false;
2288 }
2289 
2290 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2291                                       TemplateParameterList *OldParams,
2292                                       TemplateParamListContext TPC,
2293                                       SkipBodyInfo *SkipBody) {
2294   bool Invalid = false;
2295 
2296   // C++ [temp.param]p10:
2297   //   The set of default template-arguments available for use with a
2298   //   template declaration or definition is obtained by merging the
2299   //   default arguments from the definition (if in scope) and all
2300   //   declarations in scope in the same way default function
2301   //   arguments are (8.3.6).
2302   bool SawDefaultArgument = false;
2303   SourceLocation PreviousDefaultArgLoc;
2304 
2305   // Dummy initialization to avoid warnings.
2306   TemplateParameterList::iterator OldParam = NewParams->end();
2307   if (OldParams)
2308     OldParam = OldParams->begin();
2309 
2310   bool RemoveDefaultArguments = false;
2311   for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2312                                     NewParamEnd = NewParams->end();
2313        NewParam != NewParamEnd; ++NewParam) {
2314     // Whether we've seen a duplicate default argument in the same translation
2315     // unit.
2316     bool RedundantDefaultArg = false;
2317     // Whether we've found inconsis inconsitent default arguments in different
2318     // translation unit.
2319     bool InconsistentDefaultArg = false;
2320     // The name of the module which contains the inconsistent default argument.
2321     std::string PrevModuleName;
2322 
2323     SourceLocation OldDefaultLoc;
2324     SourceLocation NewDefaultLoc;
2325 
2326     // Variable used to diagnose missing default arguments
2327     bool MissingDefaultArg = false;
2328 
2329     // Variable used to diagnose non-final parameter packs
2330     bool SawParameterPack = false;
2331 
2332     if (TemplateTypeParmDecl *NewTypeParm
2333           = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2334       // Check the presence of a default argument here.
2335       if (NewTypeParm->hasDefaultArgument() &&
2336           DiagnoseDefaultTemplateArgument(
2337               *this, TPC, NewTypeParm->getLocation(),
2338               NewTypeParm->getDefaultArgument().getSourceRange()))
2339         NewTypeParm->removeDefaultArgument();
2340 
2341       // Merge default arguments for template type parameters.
2342       TemplateTypeParmDecl *OldTypeParm
2343           = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2344       if (NewTypeParm->isParameterPack()) {
2345         assert(!NewTypeParm->hasDefaultArgument() &&
2346                "Parameter packs can't have a default argument!");
2347         SawParameterPack = true;
2348       } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2349                  NewTypeParm->hasDefaultArgument() &&
2350                  (!SkipBody || !SkipBody->ShouldSkip)) {
2351         OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2352         NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2353         SawDefaultArgument = true;
2354 
2355         if (!OldTypeParm->getOwningModule())
2356           RedundantDefaultArg = true;
2357         else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2358                                                                 NewTypeParm)) {
2359           InconsistentDefaultArg = true;
2360           PrevModuleName =
2361               OldTypeParm->getImportedOwningModule()->getFullModuleName();
2362         }
2363         PreviousDefaultArgLoc = NewDefaultLoc;
2364       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2365         // Merge the default argument from the old declaration to the
2366         // new declaration.
2367         NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2368         PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2369       } else if (NewTypeParm->hasDefaultArgument()) {
2370         SawDefaultArgument = true;
2371         PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2372       } else if (SawDefaultArgument)
2373         MissingDefaultArg = true;
2374     } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2375                = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2376       // Check for unexpanded parameter packs.
2377       if (!NewNonTypeParm->isParameterPack() &&
2378           DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2379                                           NewNonTypeParm->getTypeSourceInfo(),
2380                                           UPPC_NonTypeTemplateParameterType)) {
2381         Invalid = true;
2382         continue;
2383       }
2384 
2385       // Check the presence of a default argument here.
2386       if (NewNonTypeParm->hasDefaultArgument() &&
2387           DiagnoseDefaultTemplateArgument(
2388               *this, TPC, NewNonTypeParm->getLocation(),
2389               NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2390         NewNonTypeParm->removeDefaultArgument();
2391       }
2392 
2393       // Merge default arguments for non-type template parameters
2394       NonTypeTemplateParmDecl *OldNonTypeParm
2395         = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2396       if (NewNonTypeParm->isParameterPack()) {
2397         assert(!NewNonTypeParm->hasDefaultArgument() &&
2398                "Parameter packs can't have a default argument!");
2399         if (!NewNonTypeParm->isPackExpansion())
2400           SawParameterPack = true;
2401       } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2402                  NewNonTypeParm->hasDefaultArgument() &&
2403                  (!SkipBody || !SkipBody->ShouldSkip)) {
2404         OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2405         NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2406         SawDefaultArgument = true;
2407         if (!OldNonTypeParm->getOwningModule())
2408           RedundantDefaultArg = true;
2409         else if (!getASTContext().isSameDefaultTemplateArgument(
2410                      OldNonTypeParm, NewNonTypeParm)) {
2411           InconsistentDefaultArg = true;
2412           PrevModuleName =
2413               OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2414         }
2415         PreviousDefaultArgLoc = NewDefaultLoc;
2416       } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2417         // Merge the default argument from the old declaration to the
2418         // new declaration.
2419         NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2420         PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2421       } else if (NewNonTypeParm->hasDefaultArgument()) {
2422         SawDefaultArgument = true;
2423         PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2424       } else if (SawDefaultArgument)
2425         MissingDefaultArg = true;
2426     } else {
2427       TemplateTemplateParmDecl *NewTemplateParm
2428         = cast<TemplateTemplateParmDecl>(*NewParam);
2429 
2430       // Check for unexpanded parameter packs, recursively.
2431       if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2432         Invalid = true;
2433         continue;
2434       }
2435 
2436       // Check the presence of a default argument here.
2437       if (NewTemplateParm->hasDefaultArgument() &&
2438           DiagnoseDefaultTemplateArgument(*this, TPC,
2439                                           NewTemplateParm->getLocation(),
2440                      NewTemplateParm->getDefaultArgument().getSourceRange()))
2441         NewTemplateParm->removeDefaultArgument();
2442 
2443       // Merge default arguments for template template parameters
2444       TemplateTemplateParmDecl *OldTemplateParm
2445         = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2446       if (NewTemplateParm->isParameterPack()) {
2447         assert(!NewTemplateParm->hasDefaultArgument() &&
2448                "Parameter packs can't have a default argument!");
2449         if (!NewTemplateParm->isPackExpansion())
2450           SawParameterPack = true;
2451       } else if (OldTemplateParm &&
2452                  hasVisibleDefaultArgument(OldTemplateParm) &&
2453                  NewTemplateParm->hasDefaultArgument() &&
2454                  (!SkipBody || !SkipBody->ShouldSkip)) {
2455         OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2456         NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2457         SawDefaultArgument = true;
2458         if (!OldTemplateParm->getOwningModule())
2459           RedundantDefaultArg = true;
2460         else if (!getASTContext().isSameDefaultTemplateArgument(
2461                      OldTemplateParm, NewTemplateParm)) {
2462           InconsistentDefaultArg = true;
2463           PrevModuleName =
2464               OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2465         }
2466         PreviousDefaultArgLoc = NewDefaultLoc;
2467       } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2468         // Merge the default argument from the old declaration to the
2469         // new declaration.
2470         NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2471         PreviousDefaultArgLoc
2472           = OldTemplateParm->getDefaultArgument().getLocation();
2473       } else if (NewTemplateParm->hasDefaultArgument()) {
2474         SawDefaultArgument = true;
2475         PreviousDefaultArgLoc
2476           = NewTemplateParm->getDefaultArgument().getLocation();
2477       } else if (SawDefaultArgument)
2478         MissingDefaultArg = true;
2479     }
2480 
2481     // C++11 [temp.param]p11:
2482     //   If a template parameter of a primary class template or alias template
2483     //   is a template parameter pack, it shall be the last template parameter.
2484     if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2485         (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2486          TPC == TPC_TypeAliasTemplate)) {
2487       Diag((*NewParam)->getLocation(),
2488            diag::err_template_param_pack_must_be_last_template_parameter);
2489       Invalid = true;
2490     }
2491 
2492     // [basic.def.odr]/13:
2493     //     There can be more than one definition of a
2494     //     ...
2495     //     default template argument
2496     //     ...
2497     //     in a program provided that each definition appears in a different
2498     //     translation unit and the definitions satisfy the [same-meaning
2499     //     criteria of the ODR].
2500     //
2501     // Simply, the design of modules allows the definition of template default
2502     // argument to be repeated across translation unit. Note that the ODR is
2503     // checked elsewhere. But it is still not allowed to repeat template default
2504     // argument in the same translation unit.
2505     if (RedundantDefaultArg) {
2506       Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2507       Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2508       Invalid = true;
2509     } else if (InconsistentDefaultArg) {
2510       // We could only diagnose about the case that the OldParam is imported.
2511       // The case NewParam is imported should be handled in ASTReader.
2512       Diag(NewDefaultLoc,
2513            diag::err_template_param_default_arg_inconsistent_redefinition);
2514       Diag(OldDefaultLoc,
2515            diag::note_template_param_prev_default_arg_in_other_module)
2516           << PrevModuleName;
2517       Invalid = true;
2518     } else if (MissingDefaultArg &&
2519                (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
2520                 TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
2521       // C++ 23[temp.param]p14:
2522       // If a template-parameter of a class template, variable template, or
2523       // alias template has a default template argument, each subsequent
2524       // template-parameter shall either have a default template argument
2525       // supplied or be a template parameter pack.
2526       Diag((*NewParam)->getLocation(),
2527            diag::err_template_param_default_arg_missing);
2528       Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2529       Invalid = true;
2530       RemoveDefaultArguments = true;
2531     }
2532 
2533     // If we have an old template parameter list that we're merging
2534     // in, move on to the next parameter.
2535     if (OldParams)
2536       ++OldParam;
2537   }
2538 
2539   // We were missing some default arguments at the end of the list, so remove
2540   // all of the default arguments.
2541   if (RemoveDefaultArguments) {
2542     for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2543                                       NewParamEnd = NewParams->end();
2544          NewParam != NewParamEnd; ++NewParam) {
2545       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2546         TTP->removeDefaultArgument();
2547       else if (NonTypeTemplateParmDecl *NTTP
2548                                 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2549         NTTP->removeDefaultArgument();
2550       else
2551         cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2552     }
2553   }
2554 
2555   return Invalid;
2556 }
2557 
2558 namespace {
2559 
2560 /// A class which looks for a use of a certain level of template
2561 /// parameter.
2562 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2563   typedef RecursiveASTVisitor<DependencyChecker> super;
2564 
2565   unsigned Depth;
2566 
2567   // Whether we're looking for a use of a template parameter that makes the
2568   // overall construct type-dependent / a dependent type. This is strictly
2569   // best-effort for now; we may fail to match at all for a dependent type
2570   // in some cases if this is set.
2571   bool IgnoreNonTypeDependent;
2572 
2573   bool Match;
2574   SourceLocation MatchLoc;
2575 
2576   DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2577       : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2578         Match(false) {}
2579 
2580   DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2581       : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2582     NamedDecl *ND = Params->getParam(0);
2583     if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2584       Depth = PD->getDepth();
2585     } else if (NonTypeTemplateParmDecl *PD =
2586                  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2587       Depth = PD->getDepth();
2588     } else {
2589       Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2590     }
2591   }
2592 
2593   bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2594     if (ParmDepth >= Depth) {
2595       Match = true;
2596       MatchLoc = Loc;
2597       return true;
2598     }
2599     return false;
2600   }
2601 
2602   bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2603     // Prune out non-type-dependent expressions if requested. This can
2604     // sometimes result in us failing to find a template parameter reference
2605     // (if a value-dependent expression creates a dependent type), but this
2606     // mode is best-effort only.
2607     if (auto *E = dyn_cast_or_null<Expr>(S))
2608       if (IgnoreNonTypeDependent && !E->isTypeDependent())
2609         return true;
2610     return super::TraverseStmt(S, Q);
2611   }
2612 
2613   bool TraverseTypeLoc(TypeLoc TL) {
2614     if (IgnoreNonTypeDependent && !TL.isNull() &&
2615         !TL.getType()->isDependentType())
2616       return true;
2617     return super::TraverseTypeLoc(TL);
2618   }
2619 
2620   bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2621     return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2622   }
2623 
2624   bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2625     // For a best-effort search, keep looking until we find a location.
2626     return IgnoreNonTypeDependent || !Matches(T->getDepth());
2627   }
2628 
2629   bool TraverseTemplateName(TemplateName N) {
2630     if (TemplateTemplateParmDecl *PD =
2631           dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2632       if (Matches(PD->getDepth()))
2633         return false;
2634     return super::TraverseTemplateName(N);
2635   }
2636 
2637   bool VisitDeclRefExpr(DeclRefExpr *E) {
2638     if (NonTypeTemplateParmDecl *PD =
2639           dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2640       if (Matches(PD->getDepth(), E->getExprLoc()))
2641         return false;
2642     return super::VisitDeclRefExpr(E);
2643   }
2644 
2645   bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2646     return TraverseType(T->getReplacementType());
2647   }
2648 
2649   bool
2650   VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2651     return TraverseTemplateArgument(T->getArgumentPack());
2652   }
2653 
2654   bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2655     return TraverseType(T->getInjectedSpecializationType());
2656   }
2657 };
2658 } // end anonymous namespace
2659 
2660 /// Determines whether a given type depends on the given parameter
2661 /// list.
2662 static bool
2663 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2664   if (!Params->size())
2665     return false;
2666 
2667   DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2668   Checker.TraverseType(T);
2669   return Checker.Match;
2670 }
2671 
2672 // Find the source range corresponding to the named type in the given
2673 // nested-name-specifier, if any.
2674 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2675                                                        QualType T,
2676                                                        const CXXScopeSpec &SS) {
2677   NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2678   while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2679     if (const Type *CurType = NNS->getAsType()) {
2680       if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2681         return NNSLoc.getTypeLoc().getSourceRange();
2682     } else
2683       break;
2684 
2685     NNSLoc = NNSLoc.getPrefix();
2686   }
2687 
2688   return SourceRange();
2689 }
2690 
2691 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2692     SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2693     TemplateIdAnnotation *TemplateId,
2694     ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2695     bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2696   IsMemberSpecialization = false;
2697   Invalid = false;
2698 
2699   // The sequence of nested types to which we will match up the template
2700   // parameter lists. We first build this list by starting with the type named
2701   // by the nested-name-specifier and walking out until we run out of types.
2702   SmallVector<QualType, 4> NestedTypes;
2703   QualType T;
2704   if (SS.getScopeRep()) {
2705     if (CXXRecordDecl *Record
2706               = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2707       T = Context.getTypeDeclType(Record);
2708     else
2709       T = QualType(SS.getScopeRep()->getAsType(), 0);
2710   }
2711 
2712   // If we found an explicit specialization that prevents us from needing
2713   // 'template<>' headers, this will be set to the location of that
2714   // explicit specialization.
2715   SourceLocation ExplicitSpecLoc;
2716 
2717   while (!T.isNull()) {
2718     NestedTypes.push_back(T);
2719 
2720     // Retrieve the parent of a record type.
2721     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2722       // If this type is an explicit specialization, we're done.
2723       if (ClassTemplateSpecializationDecl *Spec
2724           = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2725         if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2726             Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2727           ExplicitSpecLoc = Spec->getLocation();
2728           break;
2729         }
2730       } else if (Record->getTemplateSpecializationKind()
2731                                                 == TSK_ExplicitSpecialization) {
2732         ExplicitSpecLoc = Record->getLocation();
2733         break;
2734       }
2735 
2736       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2737         T = Context.getTypeDeclType(Parent);
2738       else
2739         T = QualType();
2740       continue;
2741     }
2742 
2743     if (const TemplateSpecializationType *TST
2744                                      = T->getAs<TemplateSpecializationType>()) {
2745       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2746         if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2747           T = Context.getTypeDeclType(Parent);
2748         else
2749           T = QualType();
2750         continue;
2751       }
2752     }
2753 
2754     // Look one step prior in a dependent template specialization type.
2755     if (const DependentTemplateSpecializationType *DependentTST
2756                           = T->getAs<DependentTemplateSpecializationType>()) {
2757       if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2758         T = QualType(NNS->getAsType(), 0);
2759       else
2760         T = QualType();
2761       continue;
2762     }
2763 
2764     // Look one step prior in a dependent name type.
2765     if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2766       if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2767         T = QualType(NNS->getAsType(), 0);
2768       else
2769         T = QualType();
2770       continue;
2771     }
2772 
2773     // Retrieve the parent of an enumeration type.
2774     if (const EnumType *EnumT = T->getAs<EnumType>()) {
2775       // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2776       // check here.
2777       EnumDecl *Enum = EnumT->getDecl();
2778 
2779       // Get to the parent type.
2780       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2781         T = Context.getTypeDeclType(Parent);
2782       else
2783         T = QualType();
2784       continue;
2785     }
2786 
2787     T = QualType();
2788   }
2789   // Reverse the nested types list, since we want to traverse from the outermost
2790   // to the innermost while checking template-parameter-lists.
2791   std::reverse(NestedTypes.begin(), NestedTypes.end());
2792 
2793   // C++0x [temp.expl.spec]p17:
2794   //   A member or a member template may be nested within many
2795   //   enclosing class templates. In an explicit specialization for
2796   //   such a member, the member declaration shall be preceded by a
2797   //   template<> for each enclosing class template that is
2798   //   explicitly specialized.
2799   bool SawNonEmptyTemplateParameterList = false;
2800 
2801   auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2802     if (SawNonEmptyTemplateParameterList) {
2803       if (!SuppressDiagnostic)
2804         Diag(DeclLoc, diag::err_specialize_member_of_template)
2805           << !Recovery << Range;
2806       Invalid = true;
2807       IsMemberSpecialization = false;
2808       return true;
2809     }
2810 
2811     return false;
2812   };
2813 
2814   auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2815     // Check that we can have an explicit specialization here.
2816     if (CheckExplicitSpecialization(Range, true))
2817       return true;
2818 
2819     // We don't have a template header, but we should.
2820     SourceLocation ExpectedTemplateLoc;
2821     if (!ParamLists.empty())
2822       ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2823     else
2824       ExpectedTemplateLoc = DeclStartLoc;
2825 
2826     if (!SuppressDiagnostic)
2827       Diag(DeclLoc, diag::err_template_spec_needs_header)
2828         << Range
2829         << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2830     return false;
2831   };
2832 
2833   unsigned ParamIdx = 0;
2834   for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2835        ++TypeIdx) {
2836     T = NestedTypes[TypeIdx];
2837 
2838     // Whether we expect a 'template<>' header.
2839     bool NeedEmptyTemplateHeader = false;
2840 
2841     // Whether we expect a template header with parameters.
2842     bool NeedNonemptyTemplateHeader = false;
2843 
2844     // For a dependent type, the set of template parameters that we
2845     // expect to see.
2846     TemplateParameterList *ExpectedTemplateParams = nullptr;
2847 
2848     // C++0x [temp.expl.spec]p15:
2849     //   A member or a member template may be nested within many enclosing
2850     //   class templates. In an explicit specialization for such a member, the
2851     //   member declaration shall be preceded by a template<> for each
2852     //   enclosing class template that is explicitly specialized.
2853     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2854       if (ClassTemplatePartialSpecializationDecl *Partial
2855             = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2856         ExpectedTemplateParams = Partial->getTemplateParameters();
2857         NeedNonemptyTemplateHeader = true;
2858       } else if (Record->isDependentType()) {
2859         if (Record->getDescribedClassTemplate()) {
2860           ExpectedTemplateParams = Record->getDescribedClassTemplate()
2861                                                       ->getTemplateParameters();
2862           NeedNonemptyTemplateHeader = true;
2863         }
2864       } else if (ClassTemplateSpecializationDecl *Spec
2865                      = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2866         // C++0x [temp.expl.spec]p4:
2867         //   Members of an explicitly specialized class template are defined
2868         //   in the same manner as members of normal classes, and not using
2869         //   the template<> syntax.
2870         if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2871           NeedEmptyTemplateHeader = true;
2872         else
2873           continue;
2874       } else if (Record->getTemplateSpecializationKind()) {
2875         if (Record->getTemplateSpecializationKind()
2876                                                 != TSK_ExplicitSpecialization &&
2877             TypeIdx == NumTypes - 1)
2878           IsMemberSpecialization = true;
2879 
2880         continue;
2881       }
2882     } else if (const TemplateSpecializationType *TST
2883                                      = T->getAs<TemplateSpecializationType>()) {
2884       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2885         ExpectedTemplateParams = Template->getTemplateParameters();
2886         NeedNonemptyTemplateHeader = true;
2887       }
2888     } else if (T->getAs<DependentTemplateSpecializationType>()) {
2889       // FIXME:  We actually could/should check the template arguments here
2890       // against the corresponding template parameter list.
2891       NeedNonemptyTemplateHeader = false;
2892     }
2893 
2894     // C++ [temp.expl.spec]p16:
2895     //   In an explicit specialization declaration for a member of a class
2896     //   template or a member template that appears in namespace scope, the
2897     //   member template and some of its enclosing class templates may remain
2898     //   unspecialized, except that the declaration shall not explicitly
2899     //   specialize a class member template if its enclosing class templates
2900     //   are not explicitly specialized as well.
2901     if (ParamIdx < ParamLists.size()) {
2902       if (ParamLists[ParamIdx]->size() == 0) {
2903         if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2904                                         false))
2905           return nullptr;
2906       } else
2907         SawNonEmptyTemplateParameterList = true;
2908     }
2909 
2910     if (NeedEmptyTemplateHeader) {
2911       // If we're on the last of the types, and we need a 'template<>' header
2912       // here, then it's a member specialization.
2913       if (TypeIdx == NumTypes - 1)
2914         IsMemberSpecialization = true;
2915 
2916       if (ParamIdx < ParamLists.size()) {
2917         if (ParamLists[ParamIdx]->size() > 0) {
2918           // The header has template parameters when it shouldn't. Complain.
2919           if (!SuppressDiagnostic)
2920             Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2921                  diag::err_template_param_list_matches_nontemplate)
2922               << T
2923               << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2924                              ParamLists[ParamIdx]->getRAngleLoc())
2925               << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2926           Invalid = true;
2927           return nullptr;
2928         }
2929 
2930         // Consume this template header.
2931         ++ParamIdx;
2932         continue;
2933       }
2934 
2935       if (!IsFriend)
2936         if (DiagnoseMissingExplicitSpecialization(
2937                 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2938           return nullptr;
2939 
2940       continue;
2941     }
2942 
2943     if (NeedNonemptyTemplateHeader) {
2944       // In friend declarations we can have template-ids which don't
2945       // depend on the corresponding template parameter lists.  But
2946       // assume that empty parameter lists are supposed to match this
2947       // template-id.
2948       if (IsFriend && T->isDependentType()) {
2949         if (ParamIdx < ParamLists.size() &&
2950             DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2951           ExpectedTemplateParams = nullptr;
2952         else
2953           continue;
2954       }
2955 
2956       if (ParamIdx < ParamLists.size()) {
2957         // Check the template parameter list, if we can.
2958         if (ExpectedTemplateParams &&
2959             !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2960                                             ExpectedTemplateParams,
2961                                             !SuppressDiagnostic, TPL_TemplateMatch))
2962           Invalid = true;
2963 
2964         if (!Invalid &&
2965             CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2966                                        TPC_ClassTemplateMember))
2967           Invalid = true;
2968 
2969         ++ParamIdx;
2970         continue;
2971       }
2972 
2973       if (!SuppressDiagnostic)
2974         Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2975           << T
2976           << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2977       Invalid = true;
2978       continue;
2979     }
2980   }
2981 
2982   // If there were at least as many template-ids as there were template
2983   // parameter lists, then there are no template parameter lists remaining for
2984   // the declaration itself.
2985   if (ParamIdx >= ParamLists.size()) {
2986     if (TemplateId && !IsFriend) {
2987       // We don't have a template header for the declaration itself, but we
2988       // should.
2989       DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2990                                                         TemplateId->RAngleLoc));
2991 
2992       // Fabricate an empty template parameter list for the invented header.
2993       return TemplateParameterList::Create(Context, SourceLocation(),
2994                                            SourceLocation(), std::nullopt,
2995                                            SourceLocation(), nullptr);
2996     }
2997 
2998     return nullptr;
2999   }
3000 
3001   // If there were too many template parameter lists, complain about that now.
3002   if (ParamIdx < ParamLists.size() - 1) {
3003     bool HasAnyExplicitSpecHeader = false;
3004     bool AllExplicitSpecHeaders = true;
3005     for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3006       if (ParamLists[I]->size() == 0)
3007         HasAnyExplicitSpecHeader = true;
3008       else
3009         AllExplicitSpecHeaders = false;
3010     }
3011 
3012     if (!SuppressDiagnostic)
3013       Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3014            AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3015                                   : diag::err_template_spec_extra_headers)
3016           << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3017                          ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3018 
3019     // If there was a specialization somewhere, such that 'template<>' is
3020     // not required, and there were any 'template<>' headers, note where the
3021     // specialization occurred.
3022     if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3023         !SuppressDiagnostic)
3024       Diag(ExplicitSpecLoc,
3025            diag::note_explicit_template_spec_does_not_need_header)
3026         << NestedTypes.back();
3027 
3028     // We have a template parameter list with no corresponding scope, which
3029     // means that the resulting template declaration can't be instantiated
3030     // properly (we'll end up with dependent nodes when we shouldn't).
3031     if (!AllExplicitSpecHeaders)
3032       Invalid = true;
3033   }
3034 
3035   // C++ [temp.expl.spec]p16:
3036   //   In an explicit specialization declaration for a member of a class
3037   //   template or a member template that ap- pears in namespace scope, the
3038   //   member template and some of its enclosing class templates may remain
3039   //   unspecialized, except that the declaration shall not explicitly
3040   //   specialize a class member template if its en- closing class templates
3041   //   are not explicitly specialized as well.
3042   if (ParamLists.back()->size() == 0 &&
3043       CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3044                                   false))
3045     return nullptr;
3046 
3047   // Return the last template parameter list, which corresponds to the
3048   // entity being declared.
3049   return ParamLists.back();
3050 }
3051 
3052 void Sema::NoteAllFoundTemplates(TemplateName Name) {
3053   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3054     Diag(Template->getLocation(), diag::note_template_declared_here)
3055         << (isa<FunctionTemplateDecl>(Template)
3056                 ? 0
3057                 : isa<ClassTemplateDecl>(Template)
3058                       ? 1
3059                       : isa<VarTemplateDecl>(Template)
3060                             ? 2
3061                             : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3062         << Template->getDeclName();
3063     return;
3064   }
3065 
3066   if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3067     for (OverloadedTemplateStorage::iterator I = OST->begin(),
3068                                           IEnd = OST->end();
3069          I != IEnd; ++I)
3070       Diag((*I)->getLocation(), diag::note_template_declared_here)
3071         << 0 << (*I)->getDeclName();
3072 
3073     return;
3074   }
3075 }
3076 
3077 static QualType builtinCommonTypeImpl(Sema &S, TemplateName BaseTemplate,
3078                                       SourceLocation TemplateLoc,
3079                                       ArrayRef<TemplateArgument> Ts) {
3080   auto lookUpCommonType = [&](TemplateArgument T1,
3081                               TemplateArgument T2) -> QualType {
3082     // Don't bother looking for other specializations if both types are
3083     // builtins - users aren't allowed to specialize for them
3084     if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3085       return builtinCommonTypeImpl(S, BaseTemplate, TemplateLoc, {T1, T2});
3086 
3087     TemplateArgumentListInfo Args;
3088     Args.addArgument(TemplateArgumentLoc(
3089         T1, S.Context.getTrivialTypeSourceInfo(T1.getAsType())));
3090     Args.addArgument(TemplateArgumentLoc(
3091         T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3092 
3093     EnterExpressionEvaluationContext UnevaluatedContext(
3094         S, Sema::ExpressionEvaluationContext::Unevaluated);
3095     Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3096     Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3097 
3098     QualType BaseTemplateInst =
3099         S.CheckTemplateIdType(BaseTemplate, TemplateLoc, Args);
3100 
3101     if (SFINAE.hasErrorOccurred())
3102       return QualType();
3103 
3104     return BaseTemplateInst;
3105   };
3106 
3107   // Note A: For the common_type trait applied to a template parameter pack T of
3108   // types, the member type shall be either defined or not present as follows:
3109   switch (Ts.size()) {
3110 
3111   // If sizeof...(T) is zero, there shall be no member type.
3112   case 0:
3113     return QualType();
3114 
3115   // If sizeof...(T) is one, let T0 denote the sole type constituting the
3116   // pack T. The member typedef-name type shall denote the same type, if any, as
3117   // common_type_t<T0, T0>; otherwise there shall be no member type.
3118   case 1:
3119     return lookUpCommonType(Ts[0], Ts[0]);
3120 
3121   // If sizeof...(T) is two, let the first and second types constituting T be
3122   // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3123   // as decay_t<T1> and decay_t<T2>, respectively.
3124   case 2: {
3125     QualType T1 = Ts[0].getAsType();
3126     QualType T2 = Ts[1].getAsType();
3127     QualType D1 = S.BuiltinDecay(T1, {});
3128     QualType D2 = S.BuiltinDecay(T2, {});
3129 
3130     // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3131     // the same type, if any, as common_type_t<D1, D2>.
3132     if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3133       return lookUpCommonType(D1, D2);
3134 
3135     // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3136     // denotes a valid type, let C denote that type.
3137     {
3138       auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3139         EnterExpressionEvaluationContext UnevaluatedContext(
3140             S, Sema::ExpressionEvaluationContext::Unevaluated);
3141         Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3142         Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3143 
3144         // false
3145         OpaqueValueExpr CondExpr(SourceLocation(), S.Context.BoolTy,
3146                                  VK_PRValue);
3147         ExprResult Cond = &CondExpr;
3148 
3149         auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3150         if (ConstRefQual) {
3151           D1.addConst();
3152           D2.addConst();
3153         }
3154 
3155         // declval<D1>()
3156         OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3157         ExprResult LHS = &LHSExpr;
3158 
3159         // declval<D2>()
3160         OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3161         ExprResult RHS = &RHSExpr;
3162 
3163         ExprValueKind VK = VK_PRValue;
3164         ExprObjectKind OK = OK_Ordinary;
3165 
3166         // decltype(false ? declval<D1>() : declval<D2>())
3167         QualType Result =
3168             S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3169 
3170         if (Result.isNull() || SFINAE.hasErrorOccurred())
3171           return QualType();
3172 
3173         // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3174         return S.BuiltinDecay(Result, TemplateLoc);
3175       };
3176 
3177       if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3178         return Res;
3179 
3180       // Let:
3181       // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3182       // COND-RES(X, Y) be
3183       //   decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3184 
3185       // C++20 only
3186       // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3187       // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3188       if (!S.Context.getLangOpts().CPlusPlus20)
3189         return QualType();
3190       return CheckConditionalOperands(true);
3191     }
3192   }
3193 
3194   // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3195   // denote the first, second, and (pack of) remaining types constituting T. Let
3196   // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3197   // a type C, the member typedef-name type shall denote the same type, if any,
3198   // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3199   default: {
3200     QualType Result = Ts.front().getAsType();
3201     for (auto T : llvm::drop_begin(Ts)) {
3202       Result = lookUpCommonType(Result, T.getAsType());
3203       if (Result.isNull())
3204         return QualType();
3205     }
3206     return Result;
3207   }
3208   }
3209 }
3210 
3211 static QualType
3212 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3213                            ArrayRef<TemplateArgument> Converted,
3214                            SourceLocation TemplateLoc,
3215                            TemplateArgumentListInfo &TemplateArgs) {
3216   ASTContext &Context = SemaRef.getASTContext();
3217 
3218   switch (BTD->getBuiltinTemplateKind()) {
3219   case BTK__make_integer_seq: {
3220     // Specializations of __make_integer_seq<S, T, N> are treated like
3221     // S<T, 0, ..., N-1>.
3222 
3223     QualType OrigType = Converted[1].getAsType();
3224     // C++14 [inteseq.intseq]p1:
3225     //   T shall be an integer type.
3226     if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3227       SemaRef.Diag(TemplateArgs[1].getLocation(),
3228                    diag::err_integer_sequence_integral_element_type);
3229       return QualType();
3230     }
3231 
3232     TemplateArgument NumArgsArg = Converted[2];
3233     if (NumArgsArg.isDependent())
3234       return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3235                                                             Converted);
3236 
3237     TemplateArgumentListInfo SyntheticTemplateArgs;
3238     // The type argument, wrapped in substitution sugar, gets reused as the
3239     // first template argument in the synthetic template argument list.
3240     SyntheticTemplateArgs.addArgument(
3241         TemplateArgumentLoc(TemplateArgument(OrigType),
3242                             SemaRef.Context.getTrivialTypeSourceInfo(
3243                                 OrigType, TemplateArgs[1].getLocation())));
3244 
3245     if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3246       // Expand N into 0 ... N-1.
3247       for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3248            I < NumArgs; ++I) {
3249         TemplateArgument TA(Context, I, OrigType);
3250         SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3251             TA, OrigType, TemplateArgs[2].getLocation()));
3252       }
3253     } else {
3254       // C++14 [inteseq.make]p1:
3255       //   If N is negative the program is ill-formed.
3256       SemaRef.Diag(TemplateArgs[2].getLocation(),
3257                    diag::err_integer_sequence_negative_length);
3258       return QualType();
3259     }
3260 
3261     // The first template argument will be reused as the template decl that
3262     // our synthetic template arguments will be applied to.
3263     return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3264                                        TemplateLoc, SyntheticTemplateArgs);
3265   }
3266 
3267   case BTK__type_pack_element: {
3268     // Specializations of
3269     //    __type_pack_element<Index, T_1, ..., T_N>
3270     // are treated like T_Index.
3271     assert(Converted.size() == 2 &&
3272       "__type_pack_element should be given an index and a parameter pack");
3273 
3274     TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3275     if (IndexArg.isDependent() || Ts.isDependent())
3276       return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3277                                                             Converted);
3278 
3279     llvm::APSInt Index = IndexArg.getAsIntegral();
3280     assert(Index >= 0 && "the index used with __type_pack_element should be of "
3281                          "type std::size_t, and hence be non-negative");
3282     // If the Index is out of bounds, the program is ill-formed.
3283     if (Index >= Ts.pack_size()) {
3284       SemaRef.Diag(TemplateArgs[0].getLocation(),
3285                    diag::err_type_pack_element_out_of_bounds);
3286       return QualType();
3287     }
3288 
3289     // We simply return the type at index `Index`.
3290     int64_t N = Index.getExtValue();
3291     return Ts.getPackAsArray()[N].getAsType();
3292   }
3293 
3294   case BTK__builtin_common_type: {
3295     assert(Converted.size() == 4);
3296     if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3297       return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3298                                                             Converted);
3299 
3300     TemplateName BaseTemplate = Converted[0].getAsTemplate();
3301     TemplateName HasTypeMember = Converted[1].getAsTemplate();
3302     QualType HasNoTypeMember = Converted[2].getAsType();
3303     ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3304     if (auto CT = builtinCommonTypeImpl(SemaRef, BaseTemplate, TemplateLoc, Ts);
3305         !CT.isNull()) {
3306       TemplateArgumentListInfo TAs;
3307       TAs.addArgument(TemplateArgumentLoc(
3308           TemplateArgument(CT), SemaRef.Context.getTrivialTypeSourceInfo(
3309                                     CT, TemplateArgs[1].getLocation())));
3310 
3311       return SemaRef.CheckTemplateIdType(HasTypeMember, TemplateLoc, TAs);
3312     }
3313     return HasNoTypeMember;
3314   }
3315   }
3316   llvm_unreachable("unexpected BuiltinTemplateDecl!");
3317 }
3318 
3319 /// Determine whether this alias template is "enable_if_t".
3320 /// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3321 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3322   return AliasTemplate->getName() == "enable_if_t" ||
3323          AliasTemplate->getName() == "__enable_if_t";
3324 }
3325 
3326 /// Collect all of the separable terms in the given condition, which
3327 /// might be a conjunction.
3328 ///
3329 /// FIXME: The right answer is to convert the logical expression into
3330 /// disjunctive normal form, so we can find the first failed term
3331 /// within each possible clause.
3332 static void collectConjunctionTerms(Expr *Clause,
3333                                     SmallVectorImpl<Expr *> &Terms) {
3334   if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3335     if (BinOp->getOpcode() == BO_LAnd) {
3336       collectConjunctionTerms(BinOp->getLHS(), Terms);
3337       collectConjunctionTerms(BinOp->getRHS(), Terms);
3338       return;
3339     }
3340   }
3341 
3342   Terms.push_back(Clause);
3343 }
3344 
3345 // The ranges-v3 library uses an odd pattern of a top-level "||" with
3346 // a left-hand side that is value-dependent but never true. Identify
3347 // the idiom and ignore that term.
3348 static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3349   // Top-level '||'.
3350   auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3351   if (!BinOp) return Cond;
3352 
3353   if (BinOp->getOpcode() != BO_LOr) return Cond;
3354 
3355   // With an inner '==' that has a literal on the right-hand side.
3356   Expr *LHS = BinOp->getLHS();
3357   auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3358   if (!InnerBinOp) return Cond;
3359 
3360   if (InnerBinOp->getOpcode() != BO_EQ ||
3361       !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3362     return Cond;
3363 
3364   // If the inner binary operation came from a macro expansion named
3365   // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3366   // of the '||', which is the real, user-provided condition.
3367   SourceLocation Loc = InnerBinOp->getExprLoc();
3368   if (!Loc.isMacroID()) return Cond;
3369 
3370   StringRef MacroName = PP.getImmediateMacroName(Loc);
3371   if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3372     return BinOp->getRHS();
3373 
3374   return Cond;
3375 }
3376 
3377 namespace {
3378 
3379 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3380 // within failing boolean expression, such as substituting template parameters
3381 // for actual types.
3382 class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3383 public:
3384   explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3385       : Policy(P) {}
3386 
3387   bool handledStmt(Stmt *E, raw_ostream &OS) override {
3388     const auto *DR = dyn_cast<DeclRefExpr>(E);
3389     if (DR && DR->getQualifier()) {
3390       // If this is a qualified name, expand the template arguments in nested
3391       // qualifiers.
3392       DR->getQualifier()->print(OS, Policy, true);
3393       // Then print the decl itself.
3394       const ValueDecl *VD = DR->getDecl();
3395       OS << VD->getName();
3396       if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3397         // This is a template variable, print the expanded template arguments.
3398         printTemplateArgumentList(
3399             OS, IV->getTemplateArgs().asArray(), Policy,
3400             IV->getSpecializedTemplate()->getTemplateParameters());
3401       }
3402       return true;
3403     }
3404     return false;
3405   }
3406 
3407 private:
3408   const PrintingPolicy Policy;
3409 };
3410 
3411 } // end anonymous namespace
3412 
3413 std::pair<Expr *, std::string>
3414 Sema::findFailedBooleanCondition(Expr *Cond) {
3415   Cond = lookThroughRangesV3Condition(PP, Cond);
3416 
3417   // Separate out all of the terms in a conjunction.
3418   SmallVector<Expr *, 4> Terms;
3419   collectConjunctionTerms(Cond, Terms);
3420 
3421   // Determine which term failed.
3422   Expr *FailedCond = nullptr;
3423   for (Expr *Term : Terms) {
3424     Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3425 
3426     // Literals are uninteresting.
3427     if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3428         isa<IntegerLiteral>(TermAsWritten))
3429       continue;
3430 
3431     // The initialization of the parameter from the argument is
3432     // a constant-evaluated context.
3433     EnterExpressionEvaluationContext ConstantEvaluated(
3434       *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3435 
3436     bool Succeeded;
3437     if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3438         !Succeeded) {
3439       FailedCond = TermAsWritten;
3440       break;
3441     }
3442   }
3443   if (!FailedCond)
3444     FailedCond = Cond->IgnoreParenImpCasts();
3445 
3446   std::string Description;
3447   {
3448     llvm::raw_string_ostream Out(Description);
3449     PrintingPolicy Policy = getPrintingPolicy();
3450     Policy.PrintCanonicalTypes = true;
3451     FailedBooleanConditionPrinterHelper Helper(Policy);
3452     FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3453   }
3454   return { FailedCond, Description };
3455 }
3456 
3457 QualType Sema::CheckTemplateIdType(TemplateName Name,
3458                                    SourceLocation TemplateLoc,
3459                                    TemplateArgumentListInfo &TemplateArgs) {
3460   DependentTemplateName *DTN =
3461       Name.getUnderlying().getAsDependentTemplateName();
3462   if (DTN && DTN->isIdentifier())
3463     // When building a template-id where the template-name is dependent,
3464     // assume the template is a type template. Either our assumption is
3465     // correct, or the code is ill-formed and will be diagnosed when the
3466     // dependent name is substituted.
3467     return Context.getDependentTemplateSpecializationType(
3468         ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3469         TemplateArgs.arguments());
3470 
3471   if (Name.getAsAssumedTemplateName() &&
3472       resolveAssumedTemplateNameAsType(/*Scope=*/nullptr, Name, TemplateLoc))
3473     return QualType();
3474 
3475   auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3476 
3477   if (!Template || isa<FunctionTemplateDecl>(Template) ||
3478       isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3479     // We might have a substituted template template parameter pack. If so,
3480     // build a template specialization type for it.
3481     if (Name.getAsSubstTemplateTemplateParmPack())
3482       return Context.getTemplateSpecializationType(Name,
3483                                                    TemplateArgs.arguments());
3484 
3485     Diag(TemplateLoc, diag::err_template_id_not_a_type)
3486       << Name;
3487     NoteAllFoundTemplates(Name);
3488     return QualType();
3489   }
3490 
3491   // Check that the template argument list is well-formed for this
3492   // template.
3493   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3494   if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3495                                 DefaultArgs, false, SugaredConverted,
3496                                 CanonicalConverted,
3497                                 /*UpdateArgsWithConversions=*/true))
3498     return QualType();
3499 
3500   QualType CanonType;
3501 
3502   if (TypeAliasTemplateDecl *AliasTemplate =
3503           dyn_cast<TypeAliasTemplateDecl>(Template)) {
3504 
3505     // Find the canonical type for this type alias template specialization.
3506     TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3507     if (Pattern->isInvalidDecl())
3508       return QualType();
3509 
3510     // Only substitute for the innermost template argument list.  NOTE: Some
3511     // external resugarers rely on leaving a Subst* node here.  Make the
3512     // substitution non-final in that case.  Note that these external resugarers
3513     // will still miss some information in this representation, because we don't
3514     // provide enough context in the Subst* nodes in order to tell different
3515     // template type alias specializations apart.
3516     MultiLevelTemplateArgumentList TemplateArgLists;
3517     TemplateArgLists.addOuterTemplateArguments(
3518         Template, SugaredConverted,
3519         /*Final=*/!getLangOpts().RetainSubstTemplateTypeParmTypeAstNodes);
3520     TemplateArgLists.addOuterRetainedLevels(
3521         AliasTemplate->getTemplateParameters()->getDepth());
3522 
3523     LocalInstantiationScope Scope(*this);
3524     InstantiatingTemplate Inst(
3525         *this, /*PointOfInstantiation=*/TemplateLoc,
3526         /*Entity=*/AliasTemplate,
3527         /*TemplateArgs=*/TemplateArgLists.getInnermost());
3528 
3529     // Diagnose uses of this alias.
3530     (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3531 
3532     if (Inst.isInvalid())
3533       return QualType();
3534 
3535     std::optional<ContextRAII> SavedContext;
3536     if (!AliasTemplate->getDeclContext()->isFileContext())
3537       SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3538 
3539     CanonType =
3540         SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3541                   AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3542     if (CanonType.isNull()) {
3543       // If this was enable_if and we failed to find the nested type
3544       // within enable_if in a SFINAE context, dig out the specific
3545       // enable_if condition that failed and present that instead.
3546       if (isEnableIfAliasTemplate(AliasTemplate)) {
3547         if (auto DeductionInfo = isSFINAEContext()) {
3548           if (*DeductionInfo &&
3549               (*DeductionInfo)->hasSFINAEDiagnostic() &&
3550               (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3551                 diag::err_typename_nested_not_found_enable_if &&
3552               TemplateArgs[0].getArgument().getKind()
3553                 == TemplateArgument::Expression) {
3554             Expr *FailedCond;
3555             std::string FailedDescription;
3556             std::tie(FailedCond, FailedDescription) =
3557               findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3558 
3559             // Remove the old SFINAE diagnostic.
3560             PartialDiagnosticAt OldDiag =
3561               {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3562             (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3563 
3564             // Add a new SFINAE diagnostic specifying which condition
3565             // failed.
3566             (*DeductionInfo)->addSFINAEDiagnostic(
3567               OldDiag.first,
3568               PDiag(diag::err_typename_nested_not_found_requirement)
3569                 << FailedDescription
3570                 << FailedCond->getSourceRange());
3571           }
3572         }
3573       }
3574 
3575       return QualType();
3576     }
3577   } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3578     CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
3579                                            TemplateLoc, TemplateArgs);
3580   } else if (Name.isDependent() ||
3581              TemplateSpecializationType::anyDependentTemplateArguments(
3582                  TemplateArgs, CanonicalConverted)) {
3583     // This class template specialization is a dependent
3584     // type. Therefore, its canonical type is another class template
3585     // specialization type that contains all of the converted
3586     // arguments in canonical form. This ensures that, e.g., A<T> and
3587     // A<T, T> have identical types when A is declared as:
3588     //
3589     //   template<typename T, typename U = T> struct A;
3590     CanonType = Context.getCanonicalTemplateSpecializationType(
3591         Name, CanonicalConverted);
3592 
3593     // This might work out to be a current instantiation, in which
3594     // case the canonical type needs to be the InjectedClassNameType.
3595     //
3596     // TODO: in theory this could be a simple hashtable lookup; most
3597     // changes to CurContext don't change the set of current
3598     // instantiations.
3599     if (isa<ClassTemplateDecl>(Template)) {
3600       for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3601         // If we get out to a namespace, we're done.
3602         if (Ctx->isFileContext()) break;
3603 
3604         // If this isn't a record, keep looking.
3605         CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3606         if (!Record) continue;
3607 
3608         // Look for one of the two cases with InjectedClassNameTypes
3609         // and check whether it's the same template.
3610         if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3611             !Record->getDescribedClassTemplate())
3612           continue;
3613 
3614         // Fetch the injected class name type and check whether its
3615         // injected type is equal to the type we just built.
3616         QualType ICNT = Context.getTypeDeclType(Record);
3617         QualType Injected = cast<InjectedClassNameType>(ICNT)
3618           ->getInjectedSpecializationType();
3619 
3620         if (CanonType != Injected->getCanonicalTypeInternal())
3621           continue;
3622 
3623         // If so, the canonical type of this TST is the injected
3624         // class name type of the record we just found.
3625         assert(ICNT.isCanonical());
3626         CanonType = ICNT;
3627         break;
3628       }
3629     }
3630   } else if (ClassTemplateDecl *ClassTemplate =
3631                  dyn_cast<ClassTemplateDecl>(Template)) {
3632     // Find the class template specialization declaration that
3633     // corresponds to these arguments.
3634     void *InsertPos = nullptr;
3635     ClassTemplateSpecializationDecl *Decl =
3636         ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3637     if (!Decl) {
3638       // This is the first time we have referenced this class template
3639       // specialization. Create the canonical declaration and add it to
3640       // the set of specializations.
3641       Decl = ClassTemplateSpecializationDecl::Create(
3642           Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3643           ClassTemplate->getDeclContext(),
3644           ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3645           ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
3646           nullptr);
3647       ClassTemplate->AddSpecialization(Decl, InsertPos);
3648       if (ClassTemplate->isOutOfLine())
3649         Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3650     }
3651 
3652     if (Decl->getSpecializationKind() == TSK_Undeclared &&
3653         ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3654       InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3655       if (!Inst.isInvalid()) {
3656         MultiLevelTemplateArgumentList TemplateArgLists(Template,
3657                                                         CanonicalConverted,
3658                                                         /*Final=*/false);
3659         InstantiateAttrsForDecl(TemplateArgLists,
3660                                 ClassTemplate->getTemplatedDecl(), Decl);
3661       }
3662     }
3663 
3664     // Diagnose uses of this specialization.
3665     (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3666 
3667     CanonType = Context.getTypeDeclType(Decl);
3668     assert(isa<RecordType>(CanonType) &&
3669            "type of non-dependent specialization is not a RecordType");
3670   } else {
3671     llvm_unreachable("Unhandled template kind");
3672   }
3673 
3674   // Build the fully-sugared type for this class template
3675   // specialization, which refers back to the class template
3676   // specialization we created or found.
3677   return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
3678                                                CanonType);
3679 }
3680 
3681 void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3682                                            TemplateNameKind &TNK,
3683                                            SourceLocation NameLoc,
3684                                            IdentifierInfo *&II) {
3685   assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3686 
3687   TemplateName Name = ParsedName.get();
3688   auto *ATN = Name.getAsAssumedTemplateName();
3689   assert(ATN && "not an assumed template name");
3690   II = ATN->getDeclName().getAsIdentifierInfo();
3691 
3692   if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3693     // Resolved to a type template name.
3694     ParsedName = TemplateTy::make(Name);
3695     TNK = TNK_Type_template;
3696   }
3697 }
3698 
3699 bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3700                                             SourceLocation NameLoc,
3701                                             bool Diagnose) {
3702   // We assumed this undeclared identifier to be an (ADL-only) function
3703   // template name, but it was used in a context where a type was required.
3704   // Try to typo-correct it now.
3705   AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3706   assert(ATN && "not an assumed template name");
3707 
3708   LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3709   struct CandidateCallback : CorrectionCandidateCallback {
3710     bool ValidateCandidate(const TypoCorrection &TC) override {
3711       return TC.getCorrectionDecl() &&
3712              getAsTypeTemplateDecl(TC.getCorrectionDecl());
3713     }
3714     std::unique_ptr<CorrectionCandidateCallback> clone() override {
3715       return std::make_unique<CandidateCallback>(*this);
3716     }
3717   } FilterCCC;
3718 
3719   TypoCorrection Corrected =
3720       CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3721                   FilterCCC, CTK_ErrorRecovery);
3722   if (Corrected && Corrected.getFoundDecl()) {
3723     diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3724                                 << ATN->getDeclName());
3725     Name = Context.getQualifiedTemplateName(
3726         /*NNS=*/nullptr, /*TemplateKeyword=*/false,
3727         TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()));
3728     return false;
3729   }
3730 
3731   if (Diagnose)
3732     Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3733   return true;
3734 }
3735 
3736 TypeResult Sema::ActOnTemplateIdType(
3737     Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3738     TemplateTy TemplateD, const IdentifierInfo *TemplateII,
3739     SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3740     ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3741     bool IsCtorOrDtorName, bool IsClassName,
3742     ImplicitTypenameContext AllowImplicitTypename) {
3743   if (SS.isInvalid())
3744     return true;
3745 
3746   if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3747     DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3748 
3749     // C++ [temp.res]p3:
3750     //   A qualified-id that refers to a type and in which the
3751     //   nested-name-specifier depends on a template-parameter (14.6.2)
3752     //   shall be prefixed by the keyword typename to indicate that the
3753     //   qualified-id denotes a type, forming an
3754     //   elaborated-type-specifier (7.1.5.3).
3755     if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3756       // C++2a relaxes some of those restrictions in [temp.res]p5.
3757       if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3758         if (getLangOpts().CPlusPlus20)
3759           Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
3760         else
3761           Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
3762               << SS.getScopeRep() << TemplateII->getName()
3763               << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
3764       } else
3765         Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3766             << SS.getScopeRep() << TemplateII->getName();
3767 
3768       // FIXME: This is not quite correct recovery as we don't transform SS
3769       // into the corresponding dependent form (and we don't diagnose missing
3770       // 'template' keywords within SS as a result).
3771       return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3772                                TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3773                                TemplateArgsIn, RAngleLoc);
3774     }
3775 
3776     // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3777     // it's not actually allowed to be used as a type in most cases. Because
3778     // we annotate it before we know whether it's valid, we have to check for
3779     // this case here.
3780     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3781     if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3782       Diag(TemplateIILoc,
3783            TemplateKWLoc.isInvalid()
3784                ? diag::err_out_of_line_qualified_id_type_names_constructor
3785                : diag::ext_out_of_line_qualified_id_type_names_constructor)
3786         << TemplateII << 0 /*injected-class-name used as template name*/
3787         << 1 /*if any keyword was present, it was 'template'*/;
3788     }
3789   }
3790 
3791   TemplateName Template = TemplateD.get();
3792   if (Template.getAsAssumedTemplateName() &&
3793       resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3794     return true;
3795 
3796   // Translate the parser's template argument list in our AST format.
3797   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3798   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3799 
3800   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3801     assert(SS.getScopeRep() == DTN->getQualifier());
3802     QualType T = Context.getDependentTemplateSpecializationType(
3803         ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3804         TemplateArgs.arguments());
3805     // Build type-source information.
3806     TypeLocBuilder TLB;
3807     DependentTemplateSpecializationTypeLoc SpecTL
3808       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3809     SpecTL.setElaboratedKeywordLoc(SourceLocation());
3810     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3811     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3812     SpecTL.setTemplateNameLoc(TemplateIILoc);
3813     SpecTL.setLAngleLoc(LAngleLoc);
3814     SpecTL.setRAngleLoc(RAngleLoc);
3815     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3816       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3817     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3818   }
3819 
3820   QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3821   if (SpecTy.isNull())
3822     return true;
3823 
3824   // Build type-source information.
3825   TypeLocBuilder TLB;
3826   TemplateSpecializationTypeLoc SpecTL =
3827       TLB.push<TemplateSpecializationTypeLoc>(SpecTy);
3828   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3829   SpecTL.setTemplateNameLoc(TemplateIILoc);
3830   SpecTL.setLAngleLoc(LAngleLoc);
3831   SpecTL.setRAngleLoc(RAngleLoc);
3832   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3833     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3834 
3835   // Create an elaborated-type-specifier containing the nested-name-specifier.
3836   QualType ElTy =
3837       getElaboratedType(ElaboratedTypeKeyword::None,
3838                         !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
3839   ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
3840   ElabTL.setElaboratedKeywordLoc(SourceLocation());
3841   if (!ElabTL.isEmpty())
3842     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3843   return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
3844 }
3845 
3846 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3847                                         TypeSpecifierType TagSpec,
3848                                         SourceLocation TagLoc,
3849                                         CXXScopeSpec &SS,
3850                                         SourceLocation TemplateKWLoc,
3851                                         TemplateTy TemplateD,
3852                                         SourceLocation TemplateLoc,
3853                                         SourceLocation LAngleLoc,
3854                                         ASTTemplateArgsPtr TemplateArgsIn,
3855                                         SourceLocation RAngleLoc) {
3856   if (SS.isInvalid())
3857     return TypeResult(true);
3858 
3859   TemplateName Template = TemplateD.get();
3860 
3861   // Translate the parser's template argument list in our AST format.
3862   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3863   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3864 
3865   // Determine the tag kind
3866   TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3867   ElaboratedTypeKeyword Keyword
3868     = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3869 
3870   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3871     assert(SS.getScopeRep() == DTN->getQualifier());
3872     QualType T = Context.getDependentTemplateSpecializationType(
3873         Keyword, DTN->getQualifier(), DTN->getIdentifier(),
3874         TemplateArgs.arguments());
3875 
3876     // Build type-source information.
3877     TypeLocBuilder TLB;
3878     DependentTemplateSpecializationTypeLoc SpecTL
3879       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3880     SpecTL.setElaboratedKeywordLoc(TagLoc);
3881     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3882     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3883     SpecTL.setTemplateNameLoc(TemplateLoc);
3884     SpecTL.setLAngleLoc(LAngleLoc);
3885     SpecTL.setRAngleLoc(RAngleLoc);
3886     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3887       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3888     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3889   }
3890 
3891   if (TypeAliasTemplateDecl *TAT =
3892         dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3893     // C++0x [dcl.type.elab]p2:
3894     //   If the identifier resolves to a typedef-name or the simple-template-id
3895     //   resolves to an alias template specialization, the
3896     //   elaborated-type-specifier is ill-formed.
3897     Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3898         << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
3899     Diag(TAT->getLocation(), diag::note_declared_at);
3900   }
3901 
3902   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3903   if (Result.isNull())
3904     return TypeResult(true);
3905 
3906   // Check the tag kind
3907   if (const RecordType *RT = Result->getAs<RecordType>()) {
3908     RecordDecl *D = RT->getDecl();
3909 
3910     IdentifierInfo *Id = D->getIdentifier();
3911     assert(Id && "templated class must have an identifier");
3912 
3913     if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TagUseKind::Definition,
3914                                       TagLoc, Id)) {
3915       Diag(TagLoc, diag::err_use_with_wrong_tag)
3916         << Result
3917         << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3918       Diag(D->getLocation(), diag::note_previous_use);
3919     }
3920   }
3921 
3922   // Provide source-location information for the template specialization.
3923   TypeLocBuilder TLB;
3924   TemplateSpecializationTypeLoc SpecTL
3925     = TLB.push<TemplateSpecializationTypeLoc>(Result);
3926   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3927   SpecTL.setTemplateNameLoc(TemplateLoc);
3928   SpecTL.setLAngleLoc(LAngleLoc);
3929   SpecTL.setRAngleLoc(RAngleLoc);
3930   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3931     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3932 
3933   // Construct an elaborated type containing the nested-name-specifier (if any)
3934   // and tag keyword.
3935   Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3936   ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3937   ElabTL.setElaboratedKeywordLoc(TagLoc);
3938   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3939   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3940 }
3941 
3942 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3943                                              NamedDecl *PrevDecl,
3944                                              SourceLocation Loc,
3945                                              bool IsPartialSpecialization);
3946 
3947 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3948 
3949 static bool isTemplateArgumentTemplateParameter(
3950     const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3951   switch (Arg.getKind()) {
3952   case TemplateArgument::Null:
3953   case TemplateArgument::NullPtr:
3954   case TemplateArgument::Integral:
3955   case TemplateArgument::Declaration:
3956   case TemplateArgument::StructuralValue:
3957   case TemplateArgument::Pack:
3958   case TemplateArgument::TemplateExpansion:
3959     return false;
3960 
3961   case TemplateArgument::Type: {
3962     QualType Type = Arg.getAsType();
3963     const TemplateTypeParmType *TPT =
3964         Arg.getAsType()->getAs<TemplateTypeParmType>();
3965     return TPT && !Type.hasQualifiers() &&
3966            TPT->getDepth() == Depth && TPT->getIndex() == Index;
3967   }
3968 
3969   case TemplateArgument::Expression: {
3970     DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3971     if (!DRE || !DRE->getDecl())
3972       return false;
3973     const NonTypeTemplateParmDecl *NTTP =
3974         dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3975     return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3976   }
3977 
3978   case TemplateArgument::Template:
3979     const TemplateTemplateParmDecl *TTP =
3980         dyn_cast_or_null<TemplateTemplateParmDecl>(
3981             Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3982     return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3983   }
3984   llvm_unreachable("unexpected kind of template argument");
3985 }
3986 
3987 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3988                                     ArrayRef<TemplateArgument> Args) {
3989   if (Params->size() != Args.size())
3990     return false;
3991 
3992   unsigned Depth = Params->getDepth();
3993 
3994   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3995     TemplateArgument Arg = Args[I];
3996 
3997     // If the parameter is a pack expansion, the argument must be a pack
3998     // whose only element is a pack expansion.
3999     if (Params->getParam(I)->isParameterPack()) {
4000       if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4001           !Arg.pack_begin()->isPackExpansion())
4002         return false;
4003       Arg = Arg.pack_begin()->getPackExpansionPattern();
4004     }
4005 
4006     if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4007       return false;
4008   }
4009 
4010   return true;
4011 }
4012 
4013 template<typename PartialSpecDecl>
4014 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4015   if (Partial->getDeclContext()->isDependentContext())
4016     return;
4017 
4018   // FIXME: Get the TDK from deduction in order to provide better diagnostics
4019   // for non-substitution-failure issues?
4020   TemplateDeductionInfo Info(Partial->getLocation());
4021   if (S.isMoreSpecializedThanPrimary(Partial, Info))
4022     return;
4023 
4024   auto *Template = Partial->getSpecializedTemplate();
4025   S.Diag(Partial->getLocation(),
4026          diag::ext_partial_spec_not_more_specialized_than_primary)
4027       << isa<VarTemplateDecl>(Template);
4028 
4029   if (Info.hasSFINAEDiagnostic()) {
4030     PartialDiagnosticAt Diag = {SourceLocation(),
4031                                 PartialDiagnostic::NullDiagnostic()};
4032     Info.takeSFINAEDiagnostic(Diag);
4033     SmallString<128> SFINAEArgString;
4034     Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4035     S.Diag(Diag.first,
4036            diag::note_partial_spec_not_more_specialized_than_primary)
4037       << SFINAEArgString;
4038   }
4039 
4040   S.NoteTemplateLocation(*Template);
4041   SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4042   Template->getAssociatedConstraints(TemplateAC);
4043   Partial->getAssociatedConstraints(PartialAC);
4044   S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4045                                                   TemplateAC);
4046 }
4047 
4048 static void
4049 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4050                            const llvm::SmallBitVector &DeducibleParams) {
4051   for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4052     if (!DeducibleParams[I]) {
4053       NamedDecl *Param = TemplateParams->getParam(I);
4054       if (Param->getDeclName())
4055         S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4056             << Param->getDeclName();
4057       else
4058         S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4059             << "(anonymous)";
4060     }
4061   }
4062 }
4063 
4064 
4065 template<typename PartialSpecDecl>
4066 static void checkTemplatePartialSpecialization(Sema &S,
4067                                                PartialSpecDecl *Partial) {
4068   // C++1z [temp.class.spec]p8: (DR1495)
4069   //   - The specialization shall be more specialized than the primary
4070   //     template (14.5.5.2).
4071   checkMoreSpecializedThanPrimary(S, Partial);
4072 
4073   // C++ [temp.class.spec]p8: (DR1315)
4074   //   - Each template-parameter shall appear at least once in the
4075   //     template-id outside a non-deduced context.
4076   // C++1z [temp.class.spec.match]p3 (P0127R2)
4077   //   If the template arguments of a partial specialization cannot be
4078   //   deduced because of the structure of its template-parameter-list
4079   //   and the template-id, the program is ill-formed.
4080   auto *TemplateParams = Partial->getTemplateParameters();
4081   llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4082   S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4083                                TemplateParams->getDepth(), DeducibleParams);
4084 
4085   if (!DeducibleParams.all()) {
4086     unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4087     S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4088       << isa<VarTemplatePartialSpecializationDecl>(Partial)
4089       << (NumNonDeducible > 1)
4090       << SourceRange(Partial->getLocation(),
4091                      Partial->getTemplateArgsAsWritten()->RAngleLoc);
4092     noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4093   }
4094 }
4095 
4096 void Sema::CheckTemplatePartialSpecialization(
4097     ClassTemplatePartialSpecializationDecl *Partial) {
4098   checkTemplatePartialSpecialization(*this, Partial);
4099 }
4100 
4101 void Sema::CheckTemplatePartialSpecialization(
4102     VarTemplatePartialSpecializationDecl *Partial) {
4103   checkTemplatePartialSpecialization(*this, Partial);
4104 }
4105 
4106 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4107   // C++1z [temp.param]p11:
4108   //   A template parameter of a deduction guide template that does not have a
4109   //   default-argument shall be deducible from the parameter-type-list of the
4110   //   deduction guide template.
4111   auto *TemplateParams = TD->getTemplateParameters();
4112   llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4113   MarkDeducedTemplateParameters(TD, DeducibleParams);
4114   for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4115     // A parameter pack is deducible (to an empty pack).
4116     auto *Param = TemplateParams->getParam(I);
4117     if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4118       DeducibleParams[I] = true;
4119   }
4120 
4121   if (!DeducibleParams.all()) {
4122     unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4123     Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4124       << (NumNonDeducible > 1);
4125     noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4126   }
4127 }
4128 
4129 DeclResult Sema::ActOnVarTemplateSpecialization(
4130     Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous,
4131     SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4132     StorageClass SC, bool IsPartialSpecialization,
4133     bool IsMemberSpecialization) {
4134   // D must be variable template id.
4135   assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4136          "Variable template specialization is declared with a template id.");
4137 
4138   TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4139   TemplateArgumentListInfo TemplateArgs =
4140       makeTemplateArgumentListInfo(*this, *TemplateId);
4141   SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4142   SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4143   SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4144 
4145   TemplateName Name = TemplateId->Template.get();
4146 
4147   // The template-id must name a variable template.
4148   VarTemplateDecl *VarTemplate =
4149       dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4150   if (!VarTemplate) {
4151     NamedDecl *FnTemplate;
4152     if (auto *OTS = Name.getAsOverloadedTemplate())
4153       FnTemplate = *OTS->begin();
4154     else
4155       FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4156     if (FnTemplate)
4157       return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4158                << FnTemplate->getDeclName();
4159     return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4160              << IsPartialSpecialization;
4161   }
4162 
4163   // Check for unexpanded parameter packs in any of the template arguments.
4164   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4165     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4166                                         IsPartialSpecialization
4167                                             ? UPPC_PartialSpecialization
4168                                             : UPPC_ExplicitSpecialization))
4169       return true;
4170 
4171   // Check that the template argument list is well-formed for this
4172   // template.
4173   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4174   if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4175                                 /*DefaultArgs=*/{}, false, SugaredConverted,
4176                                 CanonicalConverted,
4177                                 /*UpdateArgsWithConversions=*/true))
4178     return true;
4179 
4180   // Find the variable template (partial) specialization declaration that
4181   // corresponds to these arguments.
4182   if (IsPartialSpecialization) {
4183     if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4184                                                TemplateArgs.size(),
4185                                                CanonicalConverted))
4186       return true;
4187 
4188     // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4189     // also do them during instantiation.
4190     if (!Name.isDependent() &&
4191         !TemplateSpecializationType::anyDependentTemplateArguments(
4192             TemplateArgs, CanonicalConverted)) {
4193       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4194           << VarTemplate->getDeclName();
4195       IsPartialSpecialization = false;
4196     }
4197 
4198     if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4199                                 CanonicalConverted) &&
4200         (!Context.getLangOpts().CPlusPlus20 ||
4201          !TemplateParams->hasAssociatedConstraints())) {
4202       // C++ [temp.class.spec]p9b3:
4203       //
4204       //   -- The argument list of the specialization shall not be identical
4205       //      to the implicit argument list of the primary template.
4206       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4207         << /*variable template*/ 1
4208         << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4209         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4210       // FIXME: Recover from this by treating the declaration as a redeclaration
4211       // of the primary template.
4212       return true;
4213     }
4214   }
4215 
4216   void *InsertPos = nullptr;
4217   VarTemplateSpecializationDecl *PrevDecl = nullptr;
4218 
4219   if (IsPartialSpecialization)
4220     PrevDecl = VarTemplate->findPartialSpecialization(
4221         CanonicalConverted, TemplateParams, InsertPos);
4222   else
4223     PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4224 
4225   VarTemplateSpecializationDecl *Specialization = nullptr;
4226 
4227   // Check whether we can declare a variable template specialization in
4228   // the current scope.
4229   if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4230                                        TemplateNameLoc,
4231                                        IsPartialSpecialization))
4232     return true;
4233 
4234   if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4235     // Since the only prior variable template specialization with these
4236     // arguments was referenced but not declared,  reuse that
4237     // declaration node as our own, updating its source location and
4238     // the list of outer template parameters to reflect our new declaration.
4239     Specialization = PrevDecl;
4240     Specialization->setLocation(TemplateNameLoc);
4241     PrevDecl = nullptr;
4242   } else if (IsPartialSpecialization) {
4243     // Create a new class template partial specialization declaration node.
4244     VarTemplatePartialSpecializationDecl *PrevPartial =
4245         cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4246     VarTemplatePartialSpecializationDecl *Partial =
4247         VarTemplatePartialSpecializationDecl::Create(
4248             Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4249             TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4250             CanonicalConverted);
4251     // If we are providing an explicit specialization of a member variable
4252     // template specialization, make a note of that.
4253     if (IsMemberSpecialization)
4254       Partial->setMemberSpecialization();
4255     Partial->setTemplateArgsAsWritten(TemplateArgs);
4256 
4257     if (!PrevPartial)
4258       VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4259     Specialization = Partial;
4260 
4261     CheckTemplatePartialSpecialization(Partial);
4262   } else {
4263     // Create a new class template specialization declaration node for
4264     // this explicit specialization or friend declaration.
4265     Specialization = VarTemplateSpecializationDecl::Create(
4266         Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4267         VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4268     Specialization->setTemplateArgsAsWritten(TemplateArgs);
4269 
4270     if (!PrevDecl)
4271       VarTemplate->AddSpecialization(Specialization, InsertPos);
4272   }
4273 
4274   // C++ [temp.expl.spec]p6:
4275   //   If a template, a member template or the member of a class template is
4276   //   explicitly specialized then that specialization shall be declared
4277   //   before the first use of that specialization that would cause an implicit
4278   //   instantiation to take place, in every translation unit in which such a
4279   //   use occurs; no diagnostic is required.
4280   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4281     bool Okay = false;
4282     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4283       // Is there any previous explicit specialization declaration?
4284       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4285         Okay = true;
4286         break;
4287       }
4288     }
4289 
4290     if (!Okay) {
4291       SourceRange Range(TemplateNameLoc, RAngleLoc);
4292       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4293           << Name << Range;
4294 
4295       Diag(PrevDecl->getPointOfInstantiation(),
4296            diag::note_instantiation_required_here)
4297           << (PrevDecl->getTemplateSpecializationKind() !=
4298               TSK_ImplicitInstantiation);
4299       return true;
4300     }
4301   }
4302 
4303   Specialization->setLexicalDeclContext(CurContext);
4304 
4305   // Add the specialization into its lexical context, so that it can
4306   // be seen when iterating through the list of declarations in that
4307   // context. However, specializations are not found by name lookup.
4308   CurContext->addDecl(Specialization);
4309 
4310   // Note that this is an explicit specialization.
4311   Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4312 
4313   Previous.clear();
4314   if (PrevDecl)
4315     Previous.addDecl(PrevDecl);
4316   else if (Specialization->isStaticDataMember() &&
4317            Specialization->isOutOfLine())
4318     Specialization->setAccess(VarTemplate->getAccess());
4319 
4320   return Specialization;
4321 }
4322 
4323 namespace {
4324 /// A partial specialization whose template arguments have matched
4325 /// a given template-id.
4326 struct PartialSpecMatchResult {
4327   VarTemplatePartialSpecializationDecl *Partial;
4328   TemplateArgumentList *Args;
4329 };
4330 } // end anonymous namespace
4331 
4332 DeclResult
4333 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4334                          SourceLocation TemplateNameLoc,
4335                          const TemplateArgumentListInfo &TemplateArgs) {
4336   assert(Template && "A variable template id without template?");
4337 
4338   // Check that the template argument list is well-formed for this template.
4339   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4340   if (CheckTemplateArgumentList(
4341           Template, TemplateNameLoc,
4342           const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4343           /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
4344           /*UpdateArgsWithConversions=*/true))
4345     return true;
4346 
4347   // Produce a placeholder value if the specialization is dependent.
4348   if (Template->getDeclContext()->isDependentContext() ||
4349       TemplateSpecializationType::anyDependentTemplateArguments(
4350           TemplateArgs, CanonicalConverted))
4351     return DeclResult();
4352 
4353   // Find the variable template specialization declaration that
4354   // corresponds to these arguments.
4355   void *InsertPos = nullptr;
4356   if (VarTemplateSpecializationDecl *Spec =
4357           Template->findSpecialization(CanonicalConverted, InsertPos)) {
4358     checkSpecializationReachability(TemplateNameLoc, Spec);
4359     // If we already have a variable template specialization, return it.
4360     return Spec;
4361   }
4362 
4363   // This is the first time we have referenced this variable template
4364   // specialization. Create the canonical declaration and add it to
4365   // the set of specializations, based on the closest partial specialization
4366   // that it represents. That is,
4367   VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4368   const TemplateArgumentList *PartialSpecArgs = nullptr;
4369   bool AmbiguousPartialSpec = false;
4370   typedef PartialSpecMatchResult MatchResult;
4371   SmallVector<MatchResult, 4> Matched;
4372   SourceLocation PointOfInstantiation = TemplateNameLoc;
4373   TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4374                                             /*ForTakingAddress=*/false);
4375 
4376   // 1. Attempt to find the closest partial specialization that this
4377   // specializes, if any.
4378   // TODO: Unify with InstantiateClassTemplateSpecialization()?
4379   //       Perhaps better after unification of DeduceTemplateArguments() and
4380   //       getMoreSpecializedPartialSpecialization().
4381   SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4382   Template->getPartialSpecializations(PartialSpecs);
4383 
4384   for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4385     VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4386     TemplateDeductionInfo Info(FailedCandidates.getLocation());
4387 
4388     if (TemplateDeductionResult Result =
4389             DeduceTemplateArguments(Partial, SugaredConverted, Info);
4390         Result != TemplateDeductionResult::Success) {
4391       // Store the failed-deduction information for use in diagnostics, later.
4392       // TODO: Actually use the failed-deduction info?
4393       FailedCandidates.addCandidate().set(
4394           DeclAccessPair::make(Template, AS_public), Partial,
4395           MakeDeductionFailureInfo(Context, Result, Info));
4396       (void)Result;
4397     } else {
4398       Matched.push_back(PartialSpecMatchResult());
4399       Matched.back().Partial = Partial;
4400       Matched.back().Args = Info.takeSugared();
4401     }
4402   }
4403 
4404   if (Matched.size() >= 1) {
4405     SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4406     if (Matched.size() == 1) {
4407       //   -- If exactly one matching specialization is found, the
4408       //      instantiation is generated from that specialization.
4409       // We don't need to do anything for this.
4410     } else {
4411       //   -- If more than one matching specialization is found, the
4412       //      partial order rules (14.5.4.2) are used to determine
4413       //      whether one of the specializations is more specialized
4414       //      than the others. If none of the specializations is more
4415       //      specialized than all of the other matching
4416       //      specializations, then the use of the variable template is
4417       //      ambiguous and the program is ill-formed.
4418       for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4419                                                  PEnd = Matched.end();
4420            P != PEnd; ++P) {
4421         if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4422                                                     PointOfInstantiation) ==
4423             P->Partial)
4424           Best = P;
4425       }
4426 
4427       // Determine if the best partial specialization is more specialized than
4428       // the others.
4429       for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4430                                                  PEnd = Matched.end();
4431            P != PEnd; ++P) {
4432         if (P != Best && getMoreSpecializedPartialSpecialization(
4433                              P->Partial, Best->Partial,
4434                              PointOfInstantiation) != Best->Partial) {
4435           AmbiguousPartialSpec = true;
4436           break;
4437         }
4438       }
4439     }
4440 
4441     // Instantiate using the best variable template partial specialization.
4442     InstantiationPattern = Best->Partial;
4443     PartialSpecArgs = Best->Args;
4444   } else {
4445     //   -- If no match is found, the instantiation is generated
4446     //      from the primary template.
4447     // InstantiationPattern = Template->getTemplatedDecl();
4448   }
4449 
4450   // 2. Create the canonical declaration.
4451   // Note that we do not instantiate a definition until we see an odr-use
4452   // in DoMarkVarDeclReferenced().
4453   // FIXME: LateAttrs et al.?
4454   VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4455       Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
4456       CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4457   if (!Decl)
4458     return true;
4459 
4460   if (AmbiguousPartialSpec) {
4461     // Partial ordering did not produce a clear winner. Complain.
4462     Decl->setInvalidDecl();
4463     Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4464         << Decl;
4465 
4466     // Print the matching partial specializations.
4467     for (MatchResult P : Matched)
4468       Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4469           << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4470                                              *P.Args);
4471     return true;
4472   }
4473 
4474   if (VarTemplatePartialSpecializationDecl *D =
4475           dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4476     Decl->setInstantiationOf(D, PartialSpecArgs);
4477 
4478   checkSpecializationReachability(TemplateNameLoc, Decl);
4479 
4480   assert(Decl && "No variable template specialization?");
4481   return Decl;
4482 }
4483 
4484 ExprResult Sema::CheckVarTemplateId(
4485     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4486     VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4487     const TemplateArgumentListInfo *TemplateArgs) {
4488 
4489   DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4490                                        *TemplateArgs);
4491   if (Decl.isInvalid())
4492     return ExprError();
4493 
4494   if (!Decl.get())
4495     return ExprResult();
4496 
4497   VarDecl *Var = cast<VarDecl>(Decl.get());
4498   if (!Var->getTemplateSpecializationKind())
4499     Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4500                                        NameInfo.getLoc());
4501 
4502   // Build an ordinary singleton decl ref.
4503   return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4504 }
4505 
4506 void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4507                                             SourceLocation Loc) {
4508   Diag(Loc, diag::err_template_missing_args)
4509     << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4510   if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4511     NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4512   }
4513 }
4514 
4515 void Sema::diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
4516                                             bool TemplateKeyword,
4517                                             TemplateDecl *TD,
4518                                             SourceLocation Loc) {
4519   TemplateName Name = Context.getQualifiedTemplateName(
4520       SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4521   diagnoseMissingTemplateArguments(Name, Loc);
4522 }
4523 
4524 ExprResult
4525 Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4526                              SourceLocation TemplateKWLoc,
4527                              const DeclarationNameInfo &ConceptNameInfo,
4528                              NamedDecl *FoundDecl,
4529                              ConceptDecl *NamedConcept,
4530                              const TemplateArgumentListInfo *TemplateArgs) {
4531   assert(NamedConcept && "A concept template id without a template?");
4532 
4533   llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4534   if (CheckTemplateArgumentList(
4535           NamedConcept, ConceptNameInfo.getLoc(),
4536           const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4537           /*DefaultArgs=*/{},
4538           /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
4539           /*UpdateArgsWithConversions=*/false))
4540     return ExprError();
4541 
4542   DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4543 
4544   auto *CSD = ImplicitConceptSpecializationDecl::Create(
4545       Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4546       CanonicalConverted);
4547   ConstraintSatisfaction Satisfaction;
4548   bool AreArgsDependent =
4549       TemplateSpecializationType::anyDependentTemplateArguments(
4550           *TemplateArgs, CanonicalConverted);
4551   MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
4552                                        /*Final=*/false);
4553   LocalInstantiationScope Scope(*this);
4554 
4555   EnterExpressionEvaluationContext EECtx{
4556       *this, ExpressionEvaluationContext::Unevaluated, CSD};
4557 
4558   if (!AreArgsDependent &&
4559       CheckConstraintSatisfaction(
4560           NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
4561           SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4562                       TemplateArgs->getRAngleLoc()),
4563           Satisfaction))
4564     return ExprError();
4565   auto *CL = ConceptReference::Create(
4566       Context,
4567       SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4568       TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4569       ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs));
4570   return ConceptSpecializationExpr::Create(
4571       Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4572 }
4573 
4574 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4575                                      SourceLocation TemplateKWLoc,
4576                                      LookupResult &R,
4577                                      bool RequiresADL,
4578                                  const TemplateArgumentListInfo *TemplateArgs) {
4579   // FIXME: Can we do any checking at this point? I guess we could check the
4580   // template arguments that we have against the template name, if the template
4581   // name refers to a single template. That's not a terribly common case,
4582   // though.
4583   // foo<int> could identify a single function unambiguously
4584   // This approach does NOT work, since f<int>(1);
4585   // gets resolved prior to resorting to overload resolution
4586   // i.e., template<class T> void f(double);
4587   //       vs template<class T, class U> void f(U);
4588 
4589   // These should be filtered out by our callers.
4590   assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4591 
4592   // Non-function templates require a template argument list.
4593   if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4594     if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4595       diagnoseMissingTemplateArguments(
4596           SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4597       return ExprError();
4598     }
4599   }
4600   bool KnownDependent = false;
4601   // In C++1y, check variable template ids.
4602   if (R.getAsSingle<VarTemplateDecl>()) {
4603     ExprResult Res = CheckVarTemplateId(
4604         SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),
4605         R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4606     if (Res.isInvalid() || Res.isUsable())
4607       return Res;
4608     // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4609     KnownDependent = true;
4610   }
4611 
4612   if (R.getAsSingle<ConceptDecl>()) {
4613     return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4614                                   R.getRepresentativeDecl(),
4615                                   R.getAsSingle<ConceptDecl>(), TemplateArgs);
4616   }
4617 
4618   // We don't want lookup warnings at this point.
4619   R.suppressDiagnostics();
4620 
4621   UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
4622       Context, R.getNamingClass(), SS.getWithLocInContext(Context),
4623       TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4624       R.begin(), R.end(), KnownDependent,
4625       /*KnownInstantiationDependent=*/false);
4626 
4627   // Model the templates with UnresolvedTemplateTy. The expression should then
4628   // either be transformed in an instantiation or be diagnosed in
4629   // CheckPlaceholderExpr.
4630   if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4631       !R.getFoundDecl()->getAsFunction())
4632     ULE->setType(Context.UnresolvedTemplateTy);
4633 
4634   return ULE;
4635 }
4636 
4637 ExprResult Sema::BuildQualifiedTemplateIdExpr(
4638     CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4639     const DeclarationNameInfo &NameInfo,
4640     const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4641   assert(TemplateArgs || TemplateKWLoc.isValid());
4642 
4643   LookupResult R(*this, NameInfo, LookupOrdinaryName);
4644   if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4645                          /*EnteringContext=*/false, TemplateKWLoc))
4646     return ExprError();
4647 
4648   if (R.isAmbiguous())
4649     return ExprError();
4650 
4651   if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
4652     return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4653 
4654   if (R.empty()) {
4655     DeclContext *DC = computeDeclContext(SS);
4656     Diag(NameInfo.getLoc(), diag::err_no_member)
4657       << NameInfo.getName() << DC << SS.getRange();
4658     return ExprError();
4659   }
4660 
4661   // If necessary, build an implicit class member access.
4662   if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
4663     return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
4664                                            /*S=*/nullptr);
4665 
4666   return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
4667 }
4668 
4669 TemplateNameKind Sema::ActOnTemplateName(Scope *S,
4670                                          CXXScopeSpec &SS,
4671                                          SourceLocation TemplateKWLoc,
4672                                          const UnqualifiedId &Name,
4673                                          ParsedType ObjectType,
4674                                          bool EnteringContext,
4675                                          TemplateTy &Result,
4676                                          bool AllowInjectedClassName) {
4677   if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4678     Diag(TemplateKWLoc,
4679          getLangOpts().CPlusPlus11 ?
4680            diag::warn_cxx98_compat_template_outside_of_template :
4681            diag::ext_template_outside_of_template)
4682       << FixItHint::CreateRemoval(TemplateKWLoc);
4683 
4684   if (SS.isInvalid())
4685     return TNK_Non_template;
4686 
4687   // Figure out where isTemplateName is going to look.
4688   DeclContext *LookupCtx = nullptr;
4689   if (SS.isNotEmpty())
4690     LookupCtx = computeDeclContext(SS, EnteringContext);
4691   else if (ObjectType)
4692     LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
4693 
4694   // C++0x [temp.names]p5:
4695   //   If a name prefixed by the keyword template is not the name of
4696   //   a template, the program is ill-formed. [Note: the keyword
4697   //   template may not be applied to non-template members of class
4698   //   templates. -end note ] [ Note: as is the case with the
4699   //   typename prefix, the template prefix is allowed in cases
4700   //   where it is not strictly necessary; i.e., when the
4701   //   nested-name-specifier or the expression on the left of the ->
4702   //   or . is not dependent on a template-parameter, or the use
4703   //   does not appear in the scope of a template. -end note]
4704   //
4705   // Note: C++03 was more strict here, because it banned the use of
4706   // the "template" keyword prior to a template-name that was not a
4707   // dependent name. C++ DR468 relaxed this requirement (the
4708   // "template" keyword is now permitted). We follow the C++0x
4709   // rules, even in C++03 mode with a warning, retroactively applying the DR.
4710   bool MemberOfUnknownSpecialization;
4711   TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4712                                         ObjectType, EnteringContext, Result,
4713                                         MemberOfUnknownSpecialization);
4714   if (TNK != TNK_Non_template) {
4715     // We resolved this to a (non-dependent) template name. Return it.
4716     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4717     if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
4718         Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4719         Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4720       // C++14 [class.qual]p2:
4721       //   In a lookup in which function names are not ignored and the
4722       //   nested-name-specifier nominates a class C, if the name specified
4723       //   [...] is the injected-class-name of C, [...] the name is instead
4724       //   considered to name the constructor
4725       //
4726       // We don't get here if naming the constructor would be valid, so we
4727       // just reject immediately and recover by treating the
4728       // injected-class-name as naming the template.
4729       Diag(Name.getBeginLoc(),
4730            diag::ext_out_of_line_qualified_id_type_names_constructor)
4731           << Name.Identifier
4732           << 0 /*injected-class-name used as template name*/
4733           << TemplateKWLoc.isValid();
4734     }
4735     return TNK;
4736   }
4737 
4738   if (!MemberOfUnknownSpecialization) {
4739     // Didn't find a template name, and the lookup wasn't dependent.
4740     // Do the lookup again to determine if this is a "nothing found" case or
4741     // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4742     // need to do this.
4743     DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4744     LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4745                    LookupOrdinaryName);
4746     // Tell LookupTemplateName that we require a template so that it diagnoses
4747     // cases where it finds a non-template.
4748     RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4749                                    ? RequiredTemplateKind(TemplateKWLoc)
4750                                    : TemplateNameIsRequired;
4751     if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
4752                             /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
4753         !R.isAmbiguous()) {
4754       if (LookupCtx)
4755         Diag(Name.getBeginLoc(), diag::err_no_member)
4756             << DNI.getName() << LookupCtx << SS.getRange();
4757       else
4758         Diag(Name.getBeginLoc(), diag::err_undeclared_use)
4759             << DNI.getName() << SS.getRange();
4760     }
4761     return TNK_Non_template;
4762   }
4763 
4764   NestedNameSpecifier *Qualifier = SS.getScopeRep();
4765 
4766   switch (Name.getKind()) {
4767   case UnqualifiedIdKind::IK_Identifier:
4768     Result = TemplateTy::make(
4769         Context.getDependentTemplateName(Qualifier, Name.Identifier));
4770     return TNK_Dependent_template_name;
4771 
4772   case UnqualifiedIdKind::IK_OperatorFunctionId:
4773     Result = TemplateTy::make(Context.getDependentTemplateName(
4774         Qualifier, Name.OperatorFunctionId.Operator));
4775     return TNK_Function_template;
4776 
4777   case UnqualifiedIdKind::IK_LiteralOperatorId:
4778     // This is a kind of template name, but can never occur in a dependent
4779     // scope (literal operators can only be declared at namespace scope).
4780     break;
4781 
4782   default:
4783     break;
4784   }
4785 
4786   // This name cannot possibly name a dependent template. Diagnose this now
4787   // rather than building a dependent template name that can never be valid.
4788   Diag(Name.getBeginLoc(),
4789        diag::err_template_kw_refers_to_dependent_non_template)
4790       << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4791       << TemplateKWLoc.isValid() << TemplateKWLoc;
4792   return TNK_Non_template;
4793 }
4794 
4795 bool Sema::CheckTemplateTypeArgument(
4796     TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
4797     SmallVectorImpl<TemplateArgument> &SugaredConverted,
4798     SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
4799   const TemplateArgument &Arg = AL.getArgument();
4800   QualType ArgType;
4801   TypeSourceInfo *TSI = nullptr;
4802 
4803   // Check template type parameter.
4804   switch(Arg.getKind()) {
4805   case TemplateArgument::Type:
4806     // C++ [temp.arg.type]p1:
4807     //   A template-argument for a template-parameter which is a
4808     //   type shall be a type-id.
4809     ArgType = Arg.getAsType();
4810     TSI = AL.getTypeSourceInfo();
4811     break;
4812   case TemplateArgument::Template:
4813   case TemplateArgument::TemplateExpansion: {
4814     // We have a template type parameter but the template argument
4815     // is a template without any arguments.
4816     SourceRange SR = AL.getSourceRange();
4817     TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
4818     diagnoseMissingTemplateArguments(Name, SR.getEnd());
4819     return true;
4820   }
4821   case TemplateArgument::Expression: {
4822     // We have a template type parameter but the template argument is an
4823     // expression; see if maybe it is missing the "typename" keyword.
4824     CXXScopeSpec SS;
4825     DeclarationNameInfo NameInfo;
4826 
4827    if (DependentScopeDeclRefExpr *ArgExpr =
4828                dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4829       SS.Adopt(ArgExpr->getQualifierLoc());
4830       NameInfo = ArgExpr->getNameInfo();
4831     } else if (CXXDependentScopeMemberExpr *ArgExpr =
4832                dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4833       if (ArgExpr->isImplicitAccess()) {
4834         SS.Adopt(ArgExpr->getQualifierLoc());
4835         NameInfo = ArgExpr->getMemberNameInfo();
4836       }
4837     }
4838 
4839     if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4840       LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4841       LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
4842 
4843       if (Result.getAsSingle<TypeDecl>() ||
4844           Result.wasNotFoundInCurrentInstantiation()) {
4845         assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
4846         // Suggest that the user add 'typename' before the NNS.
4847         SourceLocation Loc = AL.getSourceRange().getBegin();
4848         Diag(Loc, getLangOpts().MSVCCompat
4849                       ? diag::ext_ms_template_type_arg_missing_typename
4850                       : diag::err_template_arg_must_be_type_suggest)
4851             << FixItHint::CreateInsertion(Loc, "typename ");
4852         NoteTemplateParameterLocation(*Param);
4853 
4854         // Recover by synthesizing a type using the location information that we
4855         // already have.
4856         ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::Typename,
4857                                                SS.getScopeRep(), II);
4858         TypeLocBuilder TLB;
4859         DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4860         TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4861         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4862         TL.setNameLoc(NameInfo.getLoc());
4863         TSI = TLB.getTypeSourceInfo(Context, ArgType);
4864 
4865         // Overwrite our input TemplateArgumentLoc so that we can recover
4866         // properly.
4867         AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4868                                  TemplateArgumentLocInfo(TSI));
4869 
4870         break;
4871       }
4872     }
4873     // fallthrough
4874     [[fallthrough]];
4875   }
4876   default: {
4877     // We allow instantiateing a template with template argument packs when
4878     // building deduction guides.
4879     if (Arg.getKind() == TemplateArgument::Pack &&
4880         CodeSynthesisContexts.back().Kind ==
4881             Sema::CodeSynthesisContext::BuildingDeductionGuides) {
4882       SugaredConverted.push_back(Arg);
4883       CanonicalConverted.push_back(Arg);
4884       return false;
4885     }
4886     // We have a template type parameter but the template argument
4887     // is not a type.
4888     SourceRange SR = AL.getSourceRange();
4889     Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4890     NoteTemplateParameterLocation(*Param);
4891 
4892     return true;
4893   }
4894   }
4895 
4896   if (CheckTemplateArgument(TSI))
4897     return true;
4898 
4899   // Objective-C ARC:
4900   //   If an explicitly-specified template argument type is a lifetime type
4901   //   with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4902   if (getLangOpts().ObjCAutoRefCount &&
4903       ArgType->isObjCLifetimeType() &&
4904       !ArgType.getObjCLifetime()) {
4905     Qualifiers Qs;
4906     Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4907     ArgType = Context.getQualifiedType(ArgType, Qs);
4908   }
4909 
4910   SugaredConverted.push_back(TemplateArgument(ArgType));
4911   CanonicalConverted.push_back(
4912       TemplateArgument(Context.getCanonicalType(ArgType)));
4913   return false;
4914 }
4915 
4916 /// Substitute template arguments into the default template argument for
4917 /// the given template type parameter.
4918 ///
4919 /// \param SemaRef the semantic analysis object for which we are performing
4920 /// the substitution.
4921 ///
4922 /// \param Template the template that we are synthesizing template arguments
4923 /// for.
4924 ///
4925 /// \param TemplateLoc the location of the template name that started the
4926 /// template-id we are checking.
4927 ///
4928 /// \param RAngleLoc the location of the right angle bracket ('>') that
4929 /// terminates the template-id.
4930 ///
4931 /// \param Param the template template parameter whose default we are
4932 /// substituting into.
4933 ///
4934 /// \param Converted the list of template arguments provided for template
4935 /// parameters that precede \p Param in the template parameter list.
4936 ///
4937 /// \param Output the resulting substituted template argument.
4938 ///
4939 /// \returns true if an error occurred.
4940 static bool SubstDefaultTemplateArgument(
4941     Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4942     SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
4943     ArrayRef<TemplateArgument> SugaredConverted,
4944     ArrayRef<TemplateArgument> CanonicalConverted,
4945     TemplateArgumentLoc &Output) {
4946   Output = Param->getDefaultArgument();
4947 
4948   // If the argument type is dependent, instantiate it now based
4949   // on the previously-computed template arguments.
4950   if (Output.getArgument().isInstantiationDependent()) {
4951     Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
4952                                      SugaredConverted,
4953                                      SourceRange(TemplateLoc, RAngleLoc));
4954     if (Inst.isInvalid())
4955       return true;
4956 
4957     // Only substitute for the innermost template argument list.
4958     MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4959                                                     /*Final=*/true);
4960     for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4961       TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4962 
4963     bool ForLambdaCallOperator = false;
4964     if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
4965       ForLambdaCallOperator = Rec->isLambda();
4966     Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
4967                                    !ForLambdaCallOperator);
4968 
4969     if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
4970                                       Param->getDefaultArgumentLoc(),
4971                                       Param->getDeclName()))
4972       return true;
4973   }
4974 
4975   return false;
4976 }
4977 
4978 /// Substitute template arguments into the default template argument for
4979 /// the given non-type template parameter.
4980 ///
4981 /// \param SemaRef the semantic analysis object for which we are performing
4982 /// the substitution.
4983 ///
4984 /// \param Template the template that we are synthesizing template arguments
4985 /// for.
4986 ///
4987 /// \param TemplateLoc the location of the template name that started the
4988 /// template-id we are checking.
4989 ///
4990 /// \param RAngleLoc the location of the right angle bracket ('>') that
4991 /// terminates the template-id.
4992 ///
4993 /// \param Param the non-type template parameter whose default we are
4994 /// substituting into.
4995 ///
4996 /// \param Converted the list of template arguments provided for template
4997 /// parameters that precede \p Param in the template parameter list.
4998 ///
4999 /// \returns the substituted template argument, or NULL if an error occurred.
5000 static bool SubstDefaultTemplateArgument(
5001     Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5002     SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5003     ArrayRef<TemplateArgument> SugaredConverted,
5004     ArrayRef<TemplateArgument> CanonicalConverted,
5005     TemplateArgumentLoc &Output) {
5006   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5007                                    SugaredConverted,
5008                                    SourceRange(TemplateLoc, RAngleLoc));
5009   if (Inst.isInvalid())
5010     return true;
5011 
5012   // Only substitute for the innermost template argument list.
5013   MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5014                                                   /*Final=*/true);
5015   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5016     TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5017 
5018   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5019   EnterExpressionEvaluationContext ConstantEvaluated(
5020       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5021   return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5022                                        TemplateArgLists, Output);
5023 }
5024 
5025 /// Substitute template arguments into the default template argument for
5026 /// the given template template parameter.
5027 ///
5028 /// \param SemaRef the semantic analysis object for which we are performing
5029 /// the substitution.
5030 ///
5031 /// \param Template the template that we are synthesizing template arguments
5032 /// for.
5033 ///
5034 /// \param TemplateLoc the location of the template name that started the
5035 /// template-id we are checking.
5036 ///
5037 /// \param RAngleLoc the location of the right angle bracket ('>') that
5038 /// terminates the template-id.
5039 ///
5040 /// \param Param the template template parameter whose default we are
5041 /// substituting into.
5042 ///
5043 /// \param Converted the list of template arguments provided for template
5044 /// parameters that precede \p Param in the template parameter list.
5045 ///
5046 /// \param QualifierLoc Will be set to the nested-name-specifier (with
5047 /// source-location information) that precedes the template name.
5048 ///
5049 /// \returns the substituted template argument, or NULL if an error occurred.
5050 static TemplateName SubstDefaultTemplateArgument(
5051     Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5052     SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
5053     ArrayRef<TemplateArgument> SugaredConverted,
5054     ArrayRef<TemplateArgument> CanonicalConverted,
5055     NestedNameSpecifierLoc &QualifierLoc) {
5056   Sema::InstantiatingTemplate Inst(
5057       SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5058       SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5059   if (Inst.isInvalid())
5060     return TemplateName();
5061 
5062   // Only substitute for the innermost template argument list.
5063   MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5064                                                   /*Final=*/true);
5065   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5066     TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5067 
5068   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5069   // Substitute into the nested-name-specifier first,
5070   QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5071   if (QualifierLoc) {
5072     QualifierLoc =
5073         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
5074     if (!QualifierLoc)
5075       return TemplateName();
5076   }
5077 
5078   return SemaRef.SubstTemplateName(
5079              QualifierLoc,
5080              Param->getDefaultArgument().getArgument().getAsTemplate(),
5081              Param->getDefaultArgument().getTemplateNameLoc(),
5082              TemplateArgLists);
5083 }
5084 
5085 TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5086     TemplateDecl *Template, SourceLocation TemplateLoc,
5087     SourceLocation RAngleLoc, Decl *Param,
5088     ArrayRef<TemplateArgument> SugaredConverted,
5089     ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5090   HasDefaultArg = false;
5091 
5092   if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5093     if (!hasReachableDefaultArgument(TypeParm))
5094       return TemplateArgumentLoc();
5095 
5096     HasDefaultArg = true;
5097     TemplateArgumentLoc Output;
5098     if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5099                                      TypeParm, SugaredConverted,
5100                                      CanonicalConverted, Output))
5101       return TemplateArgumentLoc();
5102     return Output;
5103   }
5104 
5105   if (NonTypeTemplateParmDecl *NonTypeParm
5106         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5107     if (!hasReachableDefaultArgument(NonTypeParm))
5108       return TemplateArgumentLoc();
5109 
5110     HasDefaultArg = true;
5111     TemplateArgumentLoc Output;
5112     if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5113                                      NonTypeParm, SugaredConverted,
5114                                      CanonicalConverted, Output))
5115       return TemplateArgumentLoc();
5116     return Output;
5117   }
5118 
5119   TemplateTemplateParmDecl *TempTempParm
5120     = cast<TemplateTemplateParmDecl>(Param);
5121   if (!hasReachableDefaultArgument(TempTempParm))
5122     return TemplateArgumentLoc();
5123 
5124   HasDefaultArg = true;
5125   NestedNameSpecifierLoc QualifierLoc;
5126   TemplateName TName = SubstDefaultTemplateArgument(
5127       *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
5128       CanonicalConverted, QualifierLoc);
5129   if (TName.isNull())
5130     return TemplateArgumentLoc();
5131 
5132   return TemplateArgumentLoc(
5133       Context, TemplateArgument(TName),
5134       TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
5135       TempTempParm->getDefaultArgument().getTemplateNameLoc());
5136 }
5137 
5138 /// Convert a template-argument that we parsed as a type into a template, if
5139 /// possible. C++ permits injected-class-names to perform dual service as
5140 /// template template arguments and as template type arguments.
5141 static TemplateArgumentLoc
5142 convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5143   // Extract and step over any surrounding nested-name-specifier.
5144   NestedNameSpecifierLoc QualLoc;
5145   if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5146     if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
5147       return TemplateArgumentLoc();
5148 
5149     QualLoc = ETLoc.getQualifierLoc();
5150     TLoc = ETLoc.getNamedTypeLoc();
5151   }
5152   // If this type was written as an injected-class-name, it can be used as a
5153   // template template argument.
5154   if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5155     return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5156                                QualLoc, InjLoc.getNameLoc());
5157 
5158   // If this type was written as an injected-class-name, it may have been
5159   // converted to a RecordType during instantiation. If the RecordType is
5160   // *not* wrapped in a TemplateSpecializationType and denotes a class
5161   // template specialization, it must have come from an injected-class-name.
5162   if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5163     if (auto *CTSD =
5164             dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5165       return TemplateArgumentLoc(Context,
5166                                  TemplateName(CTSD->getSpecializedTemplate()),
5167                                  QualLoc, RecLoc.getNameLoc());
5168 
5169   return TemplateArgumentLoc();
5170 }
5171 
5172 bool Sema::CheckTemplateArgument(
5173     NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
5174     SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5175     unsigned ArgumentPackIndex,
5176     SmallVectorImpl<TemplateArgument> &SugaredConverted,
5177     SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5178     CheckTemplateArgumentKind CTAK) {
5179   // Check template type parameters.
5180   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5181     return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
5182                                      CanonicalConverted);
5183 
5184   // Check non-type template parameters.
5185   if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5186     // Do substitution on the type of the non-type template parameter
5187     // with the template arguments we've seen thus far.  But if the
5188     // template has a dependent context then we cannot substitute yet.
5189     QualType NTTPType = NTTP->getType();
5190     if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5191       NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5192 
5193     if (NTTPType->isInstantiationDependentType() &&
5194         !isa<TemplateTemplateParmDecl>(Template) &&
5195         !Template->getDeclContext()->isDependentContext()) {
5196       // Do substitution on the type of the non-type template parameter.
5197       InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5198                                  SugaredConverted,
5199                                  SourceRange(TemplateLoc, RAngleLoc));
5200       if (Inst.isInvalid())
5201         return true;
5202 
5203       MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
5204                                            /*Final=*/true);
5205       // If the parameter is a pack expansion, expand this slice of the pack.
5206       if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5207         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
5208                                                            ArgumentPackIndex);
5209         NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5210                              NTTP->getDeclName());
5211       } else {
5212         NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5213                              NTTP->getDeclName());
5214       }
5215 
5216       // If that worked, check the non-type template parameter type
5217       // for validity.
5218       if (!NTTPType.isNull())
5219         NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5220                                                      NTTP->getLocation());
5221       if (NTTPType.isNull())
5222         return true;
5223     }
5224 
5225     switch (Arg.getArgument().getKind()) {
5226     case TemplateArgument::Null:
5227       llvm_unreachable("Should never see a NULL template argument here");
5228 
5229     case TemplateArgument::Expression: {
5230       Expr *E = Arg.getArgument().getAsExpr();
5231       TemplateArgument SugaredResult, CanonicalResult;
5232       unsigned CurSFINAEErrors = NumSFINAEErrors;
5233       ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
5234                                              CanonicalResult, CTAK);
5235       if (Res.isInvalid())
5236         return true;
5237       // If the current template argument causes an error, give up now.
5238       if (CurSFINAEErrors < NumSFINAEErrors)
5239         return true;
5240 
5241       // If the resulting expression is new, then use it in place of the
5242       // old expression in the template argument.
5243       if (Res.get() != E) {
5244         TemplateArgument TA(Res.get());
5245         Arg = TemplateArgumentLoc(TA, Res.get());
5246       }
5247 
5248       SugaredConverted.push_back(SugaredResult);
5249       CanonicalConverted.push_back(CanonicalResult);
5250       break;
5251     }
5252 
5253     case TemplateArgument::Declaration:
5254     case TemplateArgument::Integral:
5255     case TemplateArgument::StructuralValue:
5256     case TemplateArgument::NullPtr:
5257       // We've already checked this template argument, so just copy
5258       // it to the list of converted arguments.
5259       SugaredConverted.push_back(Arg.getArgument());
5260       CanonicalConverted.push_back(
5261           Context.getCanonicalTemplateArgument(Arg.getArgument()));
5262       break;
5263 
5264     case TemplateArgument::Template:
5265     case TemplateArgument::TemplateExpansion:
5266       // We were given a template template argument. It may not be ill-formed;
5267       // see below.
5268       if (DependentTemplateName *DTN
5269             = Arg.getArgument().getAsTemplateOrTemplatePattern()
5270                                               .getAsDependentTemplateName()) {
5271         // We have a template argument such as \c T::template X, which we
5272         // parsed as a template template argument. However, since we now
5273         // know that we need a non-type template argument, convert this
5274         // template name into an expression.
5275 
5276         DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5277                                      Arg.getTemplateNameLoc());
5278 
5279         CXXScopeSpec SS;
5280         SS.Adopt(Arg.getTemplateQualifierLoc());
5281         // FIXME: the template-template arg was a DependentTemplateName,
5282         // so it was provided with a template keyword. However, its source
5283         // location is not stored in the template argument structure.
5284         SourceLocation TemplateKWLoc;
5285         ExprResult E = DependentScopeDeclRefExpr::Create(
5286             Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5287             nullptr);
5288 
5289         // If we parsed the template argument as a pack expansion, create a
5290         // pack expansion expression.
5291         if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
5292           E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5293           if (E.isInvalid())
5294             return true;
5295         }
5296 
5297         TemplateArgument SugaredResult, CanonicalResult;
5298         E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
5299                                   CanonicalResult, CTAK_Specified);
5300         if (E.isInvalid())
5301           return true;
5302 
5303         SugaredConverted.push_back(SugaredResult);
5304         CanonicalConverted.push_back(CanonicalResult);
5305         break;
5306       }
5307 
5308       // We have a template argument that actually does refer to a class
5309       // template, alias template, or template template parameter, and
5310       // therefore cannot be a non-type template argument.
5311       Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5312         << Arg.getSourceRange();
5313       NoteTemplateParameterLocation(*Param);
5314 
5315       return true;
5316 
5317     case TemplateArgument::Type: {
5318       // We have a non-type template parameter but the template
5319       // argument is a type.
5320 
5321       // C++ [temp.arg]p2:
5322       //   In a template-argument, an ambiguity between a type-id and
5323       //   an expression is resolved to a type-id, regardless of the
5324       //   form of the corresponding template-parameter.
5325       //
5326       // We warn specifically about this case, since it can be rather
5327       // confusing for users.
5328       QualType T = Arg.getArgument().getAsType();
5329       SourceRange SR = Arg.getSourceRange();
5330       if (T->isFunctionType())
5331         Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5332       else
5333         Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5334       NoteTemplateParameterLocation(*Param);
5335       return true;
5336     }
5337 
5338     case TemplateArgument::Pack:
5339       llvm_unreachable("Caller must expand template argument packs");
5340     }
5341 
5342     return false;
5343   }
5344 
5345 
5346   // Check template template parameters.
5347   TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5348 
5349   TemplateParameterList *Params = TempParm->getTemplateParameters();
5350   if (TempParm->isExpandedParameterPack())
5351     Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5352 
5353   // Substitute into the template parameter list of the template
5354   // template parameter, since previously-supplied template arguments
5355   // may appear within the template template parameter.
5356   //
5357   // FIXME: Skip this if the parameters aren't instantiation-dependent.
5358   {
5359     // Set up a template instantiation context.
5360     LocalInstantiationScope Scope(*this);
5361     InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5362                                SugaredConverted,
5363                                SourceRange(TemplateLoc, RAngleLoc));
5364     if (Inst.isInvalid())
5365       return true;
5366 
5367     Params =
5368         SubstTemplateParams(Params, CurContext,
5369                             MultiLevelTemplateArgumentList(
5370                                 Template, SugaredConverted, /*Final=*/true),
5371                             /*EvaluateConstraints=*/false);
5372     if (!Params)
5373       return true;
5374   }
5375 
5376   // C++1z [temp.local]p1: (DR1004)
5377   //   When [the injected-class-name] is used [...] as a template-argument for
5378   //   a template template-parameter [...] it refers to the class template
5379   //   itself.
5380   if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5381     TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5382         Context, Arg.getTypeSourceInfo()->getTypeLoc());
5383     if (!ConvertedArg.getArgument().isNull())
5384       Arg = ConvertedArg;
5385   }
5386 
5387   switch (Arg.getArgument().getKind()) {
5388   case TemplateArgument::Null:
5389     llvm_unreachable("Should never see a NULL template argument here");
5390 
5391   case TemplateArgument::Template:
5392   case TemplateArgument::TemplateExpansion:
5393     if (CheckTemplateTemplateArgument(TempParm, Params, Arg,
5394                                       /*IsDeduced=*/CTAK != CTAK_Specified))
5395       return true;
5396 
5397     SugaredConverted.push_back(Arg.getArgument());
5398     CanonicalConverted.push_back(
5399         Context.getCanonicalTemplateArgument(Arg.getArgument()));
5400     break;
5401 
5402   case TemplateArgument::Expression:
5403   case TemplateArgument::Type:
5404     // We have a template template parameter but the template
5405     // argument does not refer to a template.
5406     Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5407       << getLangOpts().CPlusPlus11;
5408     return true;
5409 
5410   case TemplateArgument::Declaration:
5411   case TemplateArgument::Integral:
5412   case TemplateArgument::StructuralValue:
5413   case TemplateArgument::NullPtr:
5414     llvm_unreachable("non-type argument with template template parameter");
5415 
5416   case TemplateArgument::Pack:
5417     llvm_unreachable("Caller must expand template argument packs");
5418   }
5419 
5420   return false;
5421 }
5422 
5423 /// Diagnose a missing template argument.
5424 template<typename TemplateParmDecl>
5425 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5426                                     TemplateDecl *TD,
5427                                     const TemplateParmDecl *D,
5428                                     TemplateArgumentListInfo &Args) {
5429   // Dig out the most recent declaration of the template parameter; there may be
5430   // declarations of the template that are more recent than TD.
5431   D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5432                                  ->getTemplateParameters()
5433                                  ->getParam(D->getIndex()));
5434 
5435   // If there's a default argument that's not reachable, diagnose that we're
5436   // missing a module import.
5437   llvm::SmallVector<Module*, 8> Modules;
5438   if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5439     S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5440                             D->getDefaultArgumentLoc(), Modules,
5441                             Sema::MissingImportKind::DefaultArgument,
5442                             /*Recover*/true);
5443     return true;
5444   }
5445 
5446   // FIXME: If there's a more recent default argument that *is* visible,
5447   // diagnose that it was declared too late.
5448 
5449   TemplateParameterList *Params = TD->getTemplateParameters();
5450 
5451   S.Diag(Loc, diag::err_template_arg_list_different_arity)
5452     << /*not enough args*/0
5453     << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5454     << TD;
5455   S.NoteTemplateLocation(*TD, Params->getSourceRange());
5456   return true;
5457 }
5458 
5459 /// Check that the given template argument list is well-formed
5460 /// for specializing the given template.
5461 bool Sema::CheckTemplateArgumentList(
5462     TemplateDecl *Template, SourceLocation TemplateLoc,
5463     TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5464     bool PartialTemplateArgs,
5465     SmallVectorImpl<TemplateArgument> &SugaredConverted,
5466     SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5467     bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied,
5468     bool PartialOrderingTTP) {
5469 
5470   if (ConstraintsNotSatisfied)
5471     *ConstraintsNotSatisfied = false;
5472 
5473   // Make a copy of the template arguments for processing.  Only make the
5474   // changes at the end when successful in matching the arguments to the
5475   // template.
5476   TemplateArgumentListInfo NewArgs = TemplateArgs;
5477 
5478   TemplateParameterList *Params = GetTemplateParameterList(Template);
5479 
5480   SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5481 
5482   // C++ [temp.arg]p1:
5483   //   [...] The type and form of each template-argument specified in
5484   //   a template-id shall match the type and form specified for the
5485   //   corresponding parameter declared by the template in its
5486   //   template-parameter-list.
5487   bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5488   SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5489   SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5490   unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5491   LocalInstantiationScope InstScope(*this, true);
5492   for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5493                                        ParamEnd = Params->end(),
5494                                        Param = ParamBegin;
5495        Param != ParamEnd;
5496        /* increment in loop */) {
5497     if (size_t ParamIdx = Param - ParamBegin;
5498         DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5499       // All written arguments should have been consumed by this point.
5500       assert(ArgIdx == NumArgs && "bad default argument deduction");
5501       // FIXME: Don't ignore parameter packs.
5502       if (ParamIdx == DefaultArgs.StartPos && !(*Param)->isParameterPack()) {
5503         assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5504         // Default arguments from a DeducedTemplateName are already converted.
5505         for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5506           SugaredConverted.push_back(DefArg);
5507           CanonicalConverted.push_back(
5508               Context.getCanonicalTemplateArgument(DefArg));
5509           ++Param;
5510         }
5511         continue;
5512       }
5513     }
5514 
5515     // If we have an expanded parameter pack, make sure we don't have too
5516     // many arguments.
5517     if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5518       if (*Expansions == SugaredArgumentPack.size()) {
5519         // We're done with this parameter pack. Pack up its arguments and add
5520         // them to the list.
5521         SugaredConverted.push_back(
5522             TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5523         SugaredArgumentPack.clear();
5524 
5525         CanonicalConverted.push_back(
5526             TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5527         CanonicalArgumentPack.clear();
5528 
5529         // This argument is assigned to the next parameter.
5530         ++Param;
5531         continue;
5532       } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5533         // Not enough arguments for this parameter pack.
5534         Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5535           << /*not enough args*/0
5536           << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5537           << Template;
5538         NoteTemplateLocation(*Template, Params->getSourceRange());
5539         return true;
5540       }
5541     }
5542 
5543     if (ArgIdx < NumArgs) {
5544       // Check the template argument we were given.
5545       if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
5546                                 RAngleLoc, SugaredArgumentPack.size(),
5547                                 SugaredConverted, CanonicalConverted,
5548                                 CTAK_Specified))
5549         return true;
5550 
5551       CanonicalConverted.back().setIsDefaulted(
5552           clang::isSubstitutedDefaultArgument(
5553               Context, NewArgs[ArgIdx].getArgument(), *Param,
5554               CanonicalConverted, Params->getDepth()));
5555 
5556       bool PackExpansionIntoNonPack =
5557           NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5558           (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5559       // CWG1430: Don't diagnose this pack expansion when partial
5560       // ordering template template parameters. Some uses of the template could
5561       // be valid, and invalid uses will be diagnosed later during
5562       // instantiation.
5563       if (PackExpansionIntoNonPack && !PartialOrderingTTP &&
5564           (isa<TypeAliasTemplateDecl>(Template) ||
5565            isa<ConceptDecl>(Template))) {
5566         // CWG1430: we have a pack expansion as an argument to an
5567         // alias template, and it's not part of a parameter pack. This
5568         // can't be canonicalized, so reject it now.
5569         // As for concepts - we cannot normalize constraints where this
5570         // situation exists.
5571         Diag(NewArgs[ArgIdx].getLocation(),
5572              diag::err_template_expansion_into_fixed_list)
5573           << (isa<ConceptDecl>(Template) ? 1 : 0)
5574           << NewArgs[ArgIdx].getSourceRange();
5575         NoteTemplateParameterLocation(**Param);
5576         return true;
5577       }
5578 
5579       // We're now done with this argument.
5580       ++ArgIdx;
5581 
5582       if ((*Param)->isTemplateParameterPack()) {
5583         // The template parameter was a template parameter pack, so take the
5584         // deduced argument and place it on the argument pack. Note that we
5585         // stay on the same template parameter so that we can deduce more
5586         // arguments.
5587         SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
5588         CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
5589       } else {
5590         // Move to the next template parameter.
5591         ++Param;
5592       }
5593 
5594       // If we just saw a pack expansion into a non-pack, then directly convert
5595       // the remaining arguments, because we don't know what parameters they'll
5596       // match up with.
5597       if (PackExpansionIntoNonPack) {
5598         if (!SugaredArgumentPack.empty()) {
5599           // If we were part way through filling in an expanded parameter pack,
5600           // fall back to just producing individual arguments.
5601           SugaredConverted.insert(SugaredConverted.end(),
5602                                   SugaredArgumentPack.begin(),
5603                                   SugaredArgumentPack.end());
5604           SugaredArgumentPack.clear();
5605 
5606           CanonicalConverted.insert(CanonicalConverted.end(),
5607                                     CanonicalArgumentPack.begin(),
5608                                     CanonicalArgumentPack.end());
5609           CanonicalArgumentPack.clear();
5610         }
5611 
5612         while (ArgIdx < NumArgs) {
5613           const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5614           SugaredConverted.push_back(Arg);
5615           CanonicalConverted.push_back(
5616               Context.getCanonicalTemplateArgument(Arg));
5617           ++ArgIdx;
5618         }
5619 
5620         return false;
5621       }
5622 
5623       continue;
5624     }
5625 
5626     // If we're checking a partial template argument list, we're done.
5627     if (PartialTemplateArgs) {
5628       if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
5629         SugaredConverted.push_back(
5630             TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5631         CanonicalConverted.push_back(
5632             TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5633       }
5634       return false;
5635     }
5636 
5637     // If we have a template parameter pack with no more corresponding
5638     // arguments, just break out now and we'll fill in the argument pack below.
5639     if ((*Param)->isTemplateParameterPack()) {
5640       assert(!getExpandedPackSize(*Param) &&
5641              "Should have dealt with this already");
5642 
5643       // A non-expanded parameter pack before the end of the parameter list
5644       // only occurs for an ill-formed template parameter list, unless we've
5645       // got a partial argument list for a function template, so just bail out.
5646       if (Param + 1 != ParamEnd) {
5647         assert(
5648             (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
5649             "Concept templates must have parameter packs at the end.");
5650         return true;
5651       }
5652 
5653       SugaredConverted.push_back(
5654           TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5655       SugaredArgumentPack.clear();
5656 
5657       CanonicalConverted.push_back(
5658           TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5659       CanonicalArgumentPack.clear();
5660 
5661       ++Param;
5662       continue;
5663     }
5664 
5665     // Check whether we have a default argument.
5666     bool HasDefaultArg;
5667 
5668     // Retrieve the default template argument from the template
5669     // parameter. For each kind of template parameter, we substitute the
5670     // template arguments provided thus far and any "outer" template arguments
5671     // (when the template parameter was part of a nested template) into
5672     // the default argument.
5673     TemplateArgumentLoc Arg = SubstDefaultTemplateArgumentIfAvailable(
5674         Template, TemplateLoc, RAngleLoc, *Param, SugaredConverted,
5675         CanonicalConverted, HasDefaultArg);
5676 
5677     if (Arg.getArgument().isNull()) {
5678       if (!HasDefaultArg) {
5679         if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
5680           return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5681                                          NewArgs);
5682         if (NonTypeTemplateParmDecl *NTTP =
5683                 dyn_cast<NonTypeTemplateParmDecl>(*Param))
5684           return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5685                                          NewArgs);
5686         return diagnoseMissingArgument(*this, TemplateLoc, Template,
5687                                        cast<TemplateTemplateParmDecl>(*Param),
5688                                        NewArgs);
5689       }
5690       return true;
5691     }
5692 
5693     // Introduce an instantiation record that describes where we are using
5694     // the default template argument. We're not actually instantiating a
5695     // template here, we just create this object to put a note into the
5696     // context stack.
5697     InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
5698                                SugaredConverted,
5699                                SourceRange(TemplateLoc, RAngleLoc));
5700     if (Inst.isInvalid())
5701       return true;
5702 
5703     // Check the default template argument.
5704     if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
5705                               SugaredConverted, CanonicalConverted,
5706                               CTAK_Specified))
5707       return true;
5708 
5709     SugaredConverted.back().setIsDefaulted(true);
5710     CanonicalConverted.back().setIsDefaulted(true);
5711 
5712     // Core issue 150 (assumed resolution): if this is a template template
5713     // parameter, keep track of the default template arguments from the
5714     // template definition.
5715     if (isTemplateTemplateParameter)
5716       NewArgs.addArgument(Arg);
5717 
5718     // Move to the next template parameter and argument.
5719     ++Param;
5720     ++ArgIdx;
5721   }
5722 
5723   // If we're performing a partial argument substitution, allow any trailing
5724   // pack expansions; they might be empty. This can happen even if
5725   // PartialTemplateArgs is false (the list of arguments is complete but
5726   // still dependent).
5727   if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5728       CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5729     while (ArgIdx < NumArgs &&
5730            NewArgs[ArgIdx].getArgument().isPackExpansion()) {
5731       const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
5732       SugaredConverted.push_back(Arg);
5733       CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
5734     }
5735   }
5736 
5737   // If we have any leftover arguments, then there were too many arguments.
5738   // Complain and fail.
5739   if (ArgIdx < NumArgs) {
5740     Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5741         << /*too many args*/1
5742         << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5743         << Template
5744         << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5745     NoteTemplateLocation(*Template, Params->getSourceRange());
5746     return true;
5747   }
5748 
5749   // No problems found with the new argument list, propagate changes back
5750   // to caller.
5751   if (UpdateArgsWithConversions)
5752     TemplateArgs = std::move(NewArgs);
5753 
5754   if (!PartialTemplateArgs) {
5755     // Setup the context/ThisScope for the case where we are needing to
5756     // re-instantiate constraints outside of normal instantiation.
5757     DeclContext *NewContext = Template->getDeclContext();
5758 
5759     // If this template is in a template, make sure we extract the templated
5760     // decl.
5761     if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
5762       NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
5763     auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
5764 
5765     Qualifiers ThisQuals;
5766     if (const auto *Method =
5767             dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
5768       ThisQuals = Method->getMethodQualifiers();
5769 
5770     ContextRAII Context(*this, NewContext);
5771     CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
5772 
5773     MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
5774         Template, NewContext, /*Final=*/false, CanonicalConverted,
5775         /*RelativeToPrimary=*/true, /*ForConceptInstantiation=*/true);
5776     if (EnsureTemplateArgumentListConstraints(
5777             Template, MLTAL,
5778             SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
5779       if (ConstraintsNotSatisfied)
5780         *ConstraintsNotSatisfied = true;
5781       return true;
5782     }
5783   }
5784 
5785   return false;
5786 }
5787 
5788 namespace {
5789   class UnnamedLocalNoLinkageFinder
5790     : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5791   {
5792     Sema &S;
5793     SourceRange SR;
5794 
5795     typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
5796 
5797   public:
5798     UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5799 
5800     bool Visit(QualType T) {
5801       return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5802     }
5803 
5804 #define TYPE(Class, Parent) \
5805     bool Visit##Class##Type(const Class##Type *);
5806 #define ABSTRACT_TYPE(Class, Parent) \
5807     bool Visit##Class##Type(const Class##Type *) { return false; }
5808 #define NON_CANONICAL_TYPE(Class, Parent) \
5809     bool Visit##Class##Type(const Class##Type *) { return false; }
5810 #include "clang/AST/TypeNodes.inc"
5811 
5812     bool VisitTagDecl(const TagDecl *Tag);
5813     bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5814   };
5815 } // end anonymous namespace
5816 
5817 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5818   return false;
5819 }
5820 
5821 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5822   return Visit(T->getElementType());
5823 }
5824 
5825 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5826   return Visit(T->getPointeeType());
5827 }
5828 
5829 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5830                                                     const BlockPointerType* T) {
5831   return Visit(T->getPointeeType());
5832 }
5833 
5834 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5835                                                 const LValueReferenceType* T) {
5836   return Visit(T->getPointeeType());
5837 }
5838 
5839 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5840                                                 const RValueReferenceType* T) {
5841   return Visit(T->getPointeeType());
5842 }
5843 
5844 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5845                                                   const MemberPointerType* T) {
5846   return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5847 }
5848 
5849 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5850                                                   const ConstantArrayType* T) {
5851   return Visit(T->getElementType());
5852 }
5853 
5854 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5855                                                  const IncompleteArrayType* T) {
5856   return Visit(T->getElementType());
5857 }
5858 
5859 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5860                                                    const VariableArrayType* T) {
5861   return Visit(T->getElementType());
5862 }
5863 
5864 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5865                                             const DependentSizedArrayType* T) {
5866   return Visit(T->getElementType());
5867 }
5868 
5869 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5870                                          const DependentSizedExtVectorType* T) {
5871   return Visit(T->getElementType());
5872 }
5873 
5874 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
5875     const DependentSizedMatrixType *T) {
5876   return Visit(T->getElementType());
5877 }
5878 
5879 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5880     const DependentAddressSpaceType *T) {
5881   return Visit(T->getPointeeType());
5882 }
5883 
5884 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5885   return Visit(T->getElementType());
5886 }
5887 
5888 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5889     const DependentVectorType *T) {
5890   return Visit(T->getElementType());
5891 }
5892 
5893 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5894   return Visit(T->getElementType());
5895 }
5896 
5897 bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
5898     const ConstantMatrixType *T) {
5899   return Visit(T->getElementType());
5900 }
5901 
5902 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5903                                                   const FunctionProtoType* T) {
5904   for (const auto &A : T->param_types()) {
5905     if (Visit(A))
5906       return true;
5907   }
5908 
5909   return Visit(T->getReturnType());
5910 }
5911 
5912 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5913                                                const FunctionNoProtoType* T) {
5914   return Visit(T->getReturnType());
5915 }
5916 
5917 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5918                                                   const UnresolvedUsingType*) {
5919   return false;
5920 }
5921 
5922 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5923   return false;
5924 }
5925 
5926 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5927   return Visit(T->getUnmodifiedType());
5928 }
5929 
5930 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5931   return false;
5932 }
5933 
5934 bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
5935     const PackIndexingType *) {
5936   return false;
5937 }
5938 
5939 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5940                                                     const UnaryTransformType*) {
5941   return false;
5942 }
5943 
5944 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5945   return Visit(T->getDeducedType());
5946 }
5947 
5948 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5949     const DeducedTemplateSpecializationType *T) {
5950   return Visit(T->getDeducedType());
5951 }
5952 
5953 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5954   return VisitTagDecl(T->getDecl());
5955 }
5956 
5957 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5958   return VisitTagDecl(T->getDecl());
5959 }
5960 
5961 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5962                                                  const TemplateTypeParmType*) {
5963   return false;
5964 }
5965 
5966 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5967                                         const SubstTemplateTypeParmPackType *) {
5968   return false;
5969 }
5970 
5971 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5972                                             const TemplateSpecializationType*) {
5973   return false;
5974 }
5975 
5976 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5977                                               const InjectedClassNameType* T) {
5978   return VisitTagDecl(T->getDecl());
5979 }
5980 
5981 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5982                                                    const DependentNameType* T) {
5983   return VisitNestedNameSpecifier(T->getQualifier());
5984 }
5985 
5986 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5987                                  const DependentTemplateSpecializationType* T) {
5988   if (auto *Q = T->getQualifier())
5989     return VisitNestedNameSpecifier(Q);
5990   return false;
5991 }
5992 
5993 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5994                                                    const PackExpansionType* T) {
5995   return Visit(T->getPattern());
5996 }
5997 
5998 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5999   return false;
6000 }
6001 
6002 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6003                                                    const ObjCInterfaceType *) {
6004   return false;
6005 }
6006 
6007 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6008                                                 const ObjCObjectPointerType *) {
6009   return false;
6010 }
6011 
6012 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6013   return Visit(T->getValueType());
6014 }
6015 
6016 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6017   return false;
6018 }
6019 
6020 bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6021   return false;
6022 }
6023 
6024 bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6025     const ArrayParameterType *T) {
6026   return VisitConstantArrayType(T);
6027 }
6028 
6029 bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6030     const DependentBitIntType *T) {
6031   return false;
6032 }
6033 
6034 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6035   if (Tag->getDeclContext()->isFunctionOrMethod()) {
6036     S.Diag(SR.getBegin(),
6037            S.getLangOpts().CPlusPlus11 ?
6038              diag::warn_cxx98_compat_template_arg_local_type :
6039              diag::ext_template_arg_local_type)
6040       << S.Context.getTypeDeclType(Tag) << SR;
6041     return true;
6042   }
6043 
6044   if (!Tag->hasNameForLinkage()) {
6045     S.Diag(SR.getBegin(),
6046            S.getLangOpts().CPlusPlus11 ?
6047              diag::warn_cxx98_compat_template_arg_unnamed_type :
6048              diag::ext_template_arg_unnamed_type) << SR;
6049     S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6050     return true;
6051   }
6052 
6053   return false;
6054 }
6055 
6056 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6057                                                     NestedNameSpecifier *NNS) {
6058   assert(NNS);
6059   if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
6060     return true;
6061 
6062   switch (NNS->getKind()) {
6063   case NestedNameSpecifier::Identifier:
6064   case NestedNameSpecifier::Namespace:
6065   case NestedNameSpecifier::NamespaceAlias:
6066   case NestedNameSpecifier::Global:
6067   case NestedNameSpecifier::Super:
6068     return false;
6069 
6070   case NestedNameSpecifier::TypeSpec:
6071   case NestedNameSpecifier::TypeSpecWithTemplate:
6072     return Visit(QualType(NNS->getAsType(), 0));
6073   }
6074   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6075 }
6076 
6077 bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6078   assert(ArgInfo && "invalid TypeSourceInfo");
6079   QualType Arg = ArgInfo->getType();
6080   SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6081   QualType CanonArg = Context.getCanonicalType(Arg);
6082 
6083   if (CanonArg->isVariablyModifiedType()) {
6084     return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6085   } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6086     return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6087   }
6088 
6089   // C++03 [temp.arg.type]p2:
6090   //   A local type, a type with no linkage, an unnamed type or a type
6091   //   compounded from any of these types shall not be used as a
6092   //   template-argument for a template type-parameter.
6093   //
6094   // C++11 allows these, and even in C++03 we allow them as an extension with
6095   // a warning.
6096   if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6097     UnnamedLocalNoLinkageFinder Finder(*this, SR);
6098     (void)Finder.Visit(CanonArg);
6099   }
6100 
6101   return false;
6102 }
6103 
6104 enum NullPointerValueKind {
6105   NPV_NotNullPointer,
6106   NPV_NullPointer,
6107   NPV_Error
6108 };
6109 
6110 /// Determine whether the given template argument is a null pointer
6111 /// value of the appropriate type.
6112 static NullPointerValueKind
6113 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
6114                                    QualType ParamType, Expr *Arg,
6115                                    Decl *Entity = nullptr) {
6116   if (Arg->isValueDependent() || Arg->isTypeDependent())
6117     return NPV_NotNullPointer;
6118 
6119   // dllimport'd entities aren't constant but are available inside of template
6120   // arguments.
6121   if (Entity && Entity->hasAttr<DLLImportAttr>())
6122     return NPV_NotNullPointer;
6123 
6124   if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6125     llvm_unreachable(
6126         "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6127 
6128   if (!S.getLangOpts().CPlusPlus11)
6129     return NPV_NotNullPointer;
6130 
6131   // Determine whether we have a constant expression.
6132   ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
6133   if (ArgRV.isInvalid())
6134     return NPV_Error;
6135   Arg = ArgRV.get();
6136 
6137   Expr::EvalResult EvalResult;
6138   SmallVector<PartialDiagnosticAt, 8> Notes;
6139   EvalResult.Diag = &Notes;
6140   if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6141       EvalResult.HasSideEffects) {
6142     SourceLocation DiagLoc = Arg->getExprLoc();
6143 
6144     // If our only note is the usual "invalid subexpression" note, just point
6145     // the caret at its location rather than producing an essentially
6146     // redundant note.
6147     if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6148         diag::note_invalid_subexpr_in_const_expr) {
6149       DiagLoc = Notes[0].first;
6150       Notes.clear();
6151     }
6152 
6153     S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6154       << Arg->getType() << Arg->getSourceRange();
6155     for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6156       S.Diag(Notes[I].first, Notes[I].second);
6157 
6158     S.NoteTemplateParameterLocation(*Param);
6159     return NPV_Error;
6160   }
6161 
6162   // C++11 [temp.arg.nontype]p1:
6163   //   - an address constant expression of type std::nullptr_t
6164   if (Arg->getType()->isNullPtrType())
6165     return NPV_NullPointer;
6166 
6167   //   - a constant expression that evaluates to a null pointer value (4.10); or
6168   //   - a constant expression that evaluates to a null member pointer value
6169   //     (4.11); or
6170   if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6171       (EvalResult.Val.isMemberPointer() &&
6172        !EvalResult.Val.getMemberPointerDecl())) {
6173     // If our expression has an appropriate type, we've succeeded.
6174     bool ObjCLifetimeConversion;
6175     if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6176         S.IsQualificationConversion(Arg->getType(), ParamType, false,
6177                                      ObjCLifetimeConversion))
6178       return NPV_NullPointer;
6179 
6180     // The types didn't match, but we know we got a null pointer; complain,
6181     // then recover as if the types were correct.
6182     S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6183       << Arg->getType() << ParamType << Arg->getSourceRange();
6184     S.NoteTemplateParameterLocation(*Param);
6185     return NPV_NullPointer;
6186   }
6187 
6188   if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6189     // We found a pointer that isn't null, but doesn't refer to an object.
6190     // We could just return NPV_NotNullPointer, but we can print a better
6191     // message with the information we have here.
6192     S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6193       << EvalResult.Val.getAsString(S.Context, ParamType);
6194     S.NoteTemplateParameterLocation(*Param);
6195     return NPV_Error;
6196   }
6197 
6198   // If we don't have a null pointer value, but we do have a NULL pointer
6199   // constant, suggest a cast to the appropriate type.
6200   if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
6201     std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6202     S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6203         << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6204         << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
6205                                       ")");
6206     S.NoteTemplateParameterLocation(*Param);
6207     return NPV_NullPointer;
6208   }
6209 
6210   // FIXME: If we ever want to support general, address-constant expressions
6211   // as non-type template arguments, we should return the ExprResult here to
6212   // be interpreted by the caller.
6213   return NPV_NotNullPointer;
6214 }
6215 
6216 /// Checks whether the given template argument is compatible with its
6217 /// template parameter.
6218 static bool CheckTemplateArgumentIsCompatibleWithParameter(
6219     Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6220     Expr *Arg, QualType ArgType) {
6221   bool ObjCLifetimeConversion;
6222   if (ParamType->isPointerType() &&
6223       !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6224       S.IsQualificationConversion(ArgType, ParamType, false,
6225                                   ObjCLifetimeConversion)) {
6226     // For pointer-to-object types, qualification conversions are
6227     // permitted.
6228   } else {
6229     if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6230       if (!ParamRef->getPointeeType()->isFunctionType()) {
6231         // C++ [temp.arg.nontype]p5b3:
6232         //   For a non-type template-parameter of type reference to
6233         //   object, no conversions apply. The type referred to by the
6234         //   reference may be more cv-qualified than the (otherwise
6235         //   identical) type of the template- argument. The
6236         //   template-parameter is bound directly to the
6237         //   template-argument, which shall be an lvalue.
6238 
6239         // FIXME: Other qualifiers?
6240         unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6241         unsigned ArgQuals = ArgType.getCVRQualifiers();
6242 
6243         if ((ParamQuals | ArgQuals) != ParamQuals) {
6244           S.Diag(Arg->getBeginLoc(),
6245                  diag::err_template_arg_ref_bind_ignores_quals)
6246               << ParamType << Arg->getType() << Arg->getSourceRange();
6247           S.NoteTemplateParameterLocation(*Param);
6248           return true;
6249         }
6250       }
6251     }
6252 
6253     // At this point, the template argument refers to an object or
6254     // function with external linkage. We now need to check whether the
6255     // argument and parameter types are compatible.
6256     if (!S.Context.hasSameUnqualifiedType(ArgType,
6257                                           ParamType.getNonReferenceType())) {
6258       // We can't perform this conversion or binding.
6259       if (ParamType->isReferenceType())
6260         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6261             << ParamType << ArgIn->getType() << Arg->getSourceRange();
6262       else
6263         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6264             << ArgIn->getType() << ParamType << Arg->getSourceRange();
6265       S.NoteTemplateParameterLocation(*Param);
6266       return true;
6267     }
6268   }
6269 
6270   return false;
6271 }
6272 
6273 /// Checks whether the given template argument is the address
6274 /// of an object or function according to C++ [temp.arg.nontype]p1.
6275 static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6276     Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6277     TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6278   bool Invalid = false;
6279   Expr *Arg = ArgIn;
6280   QualType ArgType = Arg->getType();
6281 
6282   bool AddressTaken = false;
6283   SourceLocation AddrOpLoc;
6284   if (S.getLangOpts().MicrosoftExt) {
6285     // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6286     // dereference and address-of operators.
6287     Arg = Arg->IgnoreParenCasts();
6288 
6289     bool ExtWarnMSTemplateArg = false;
6290     UnaryOperatorKind FirstOpKind;
6291     SourceLocation FirstOpLoc;
6292     while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6293       UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6294       if (UnOpKind == UO_Deref)
6295         ExtWarnMSTemplateArg = true;
6296       if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6297         Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6298         if (!AddrOpLoc.isValid()) {
6299           FirstOpKind = UnOpKind;
6300           FirstOpLoc = UnOp->getOperatorLoc();
6301         }
6302       } else
6303         break;
6304     }
6305     if (FirstOpLoc.isValid()) {
6306       if (ExtWarnMSTemplateArg)
6307         S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6308             << ArgIn->getSourceRange();
6309 
6310       if (FirstOpKind == UO_AddrOf)
6311         AddressTaken = true;
6312       else if (Arg->getType()->isPointerType()) {
6313         // We cannot let pointers get dereferenced here, that is obviously not a
6314         // constant expression.
6315         assert(FirstOpKind == UO_Deref);
6316         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6317             << Arg->getSourceRange();
6318       }
6319     }
6320   } else {
6321     // See through any implicit casts we added to fix the type.
6322     Arg = Arg->IgnoreImpCasts();
6323 
6324     // C++ [temp.arg.nontype]p1:
6325     //
6326     //   A template-argument for a non-type, non-template
6327     //   template-parameter shall be one of: [...]
6328     //
6329     //     -- the address of an object or function with external
6330     //        linkage, including function templates and function
6331     //        template-ids but excluding non-static class members,
6332     //        expressed as & id-expression where the & is optional if
6333     //        the name refers to a function or array, or if the
6334     //        corresponding template-parameter is a reference; or
6335 
6336     // In C++98/03 mode, give an extension warning on any extra parentheses.
6337     // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6338     bool ExtraParens = false;
6339     while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6340       if (!Invalid && !ExtraParens) {
6341         S.Diag(Arg->getBeginLoc(),
6342                S.getLangOpts().CPlusPlus11
6343                    ? diag::warn_cxx98_compat_template_arg_extra_parens
6344                    : diag::ext_template_arg_extra_parens)
6345             << Arg->getSourceRange();
6346         ExtraParens = true;
6347       }
6348 
6349       Arg = Parens->getSubExpr();
6350     }
6351 
6352     while (SubstNonTypeTemplateParmExpr *subst =
6353                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6354       Arg = subst->getReplacement()->IgnoreImpCasts();
6355 
6356     if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6357       if (UnOp->getOpcode() == UO_AddrOf) {
6358         Arg = UnOp->getSubExpr();
6359         AddressTaken = true;
6360         AddrOpLoc = UnOp->getOperatorLoc();
6361       }
6362     }
6363 
6364     while (SubstNonTypeTemplateParmExpr *subst =
6365                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6366       Arg = subst->getReplacement()->IgnoreImpCasts();
6367   }
6368 
6369   ValueDecl *Entity = nullptr;
6370   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6371     Entity = DRE->getDecl();
6372   else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6373     Entity = CUE->getGuidDecl();
6374 
6375   // If our parameter has pointer type, check for a null template value.
6376   if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6377     switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6378                                                Entity)) {
6379     case NPV_NullPointer:
6380       S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6381       SugaredConverted = TemplateArgument(ParamType,
6382                                           /*isNullPtr=*/true);
6383       CanonicalConverted =
6384           TemplateArgument(S.Context.getCanonicalType(ParamType),
6385                            /*isNullPtr=*/true);
6386       return false;
6387 
6388     case NPV_Error:
6389       return true;
6390 
6391     case NPV_NotNullPointer:
6392       break;
6393     }
6394   }
6395 
6396   // Stop checking the precise nature of the argument if it is value dependent,
6397   // it should be checked when instantiated.
6398   if (Arg->isValueDependent()) {
6399     SugaredConverted = TemplateArgument(ArgIn);
6400     CanonicalConverted =
6401         S.Context.getCanonicalTemplateArgument(SugaredConverted);
6402     return false;
6403   }
6404 
6405   if (!Entity) {
6406     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6407         << Arg->getSourceRange();
6408     S.NoteTemplateParameterLocation(*Param);
6409     return true;
6410   }
6411 
6412   // Cannot refer to non-static data members
6413   if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6414     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6415         << Entity << Arg->getSourceRange();
6416     S.NoteTemplateParameterLocation(*Param);
6417     return true;
6418   }
6419 
6420   // Cannot refer to non-static member functions
6421   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6422     if (!Method->isStatic()) {
6423       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6424           << Method << Arg->getSourceRange();
6425       S.NoteTemplateParameterLocation(*Param);
6426       return true;
6427     }
6428   }
6429 
6430   FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6431   VarDecl *Var = dyn_cast<VarDecl>(Entity);
6432   MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6433 
6434   // A non-type template argument must refer to an object or function.
6435   if (!Func && !Var && !Guid) {
6436     // We found something, but we don't know specifically what it is.
6437     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6438         << Arg->getSourceRange();
6439     S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6440     return true;
6441   }
6442 
6443   // Address / reference template args must have external linkage in C++98.
6444   if (Entity->getFormalLinkage() == Linkage::Internal) {
6445     S.Diag(Arg->getBeginLoc(),
6446            S.getLangOpts().CPlusPlus11
6447                ? diag::warn_cxx98_compat_template_arg_object_internal
6448                : diag::ext_template_arg_object_internal)
6449         << !Func << Entity << Arg->getSourceRange();
6450     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6451       << !Func;
6452   } else if (!Entity->hasLinkage()) {
6453     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6454         << !Func << Entity << Arg->getSourceRange();
6455     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6456       << !Func;
6457     return true;
6458   }
6459 
6460   if (Var) {
6461     // A value of reference type is not an object.
6462     if (Var->getType()->isReferenceType()) {
6463       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6464           << Var->getType() << Arg->getSourceRange();
6465       S.NoteTemplateParameterLocation(*Param);
6466       return true;
6467     }
6468 
6469     // A template argument must have static storage duration.
6470     if (Var->getTLSKind()) {
6471       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6472           << Arg->getSourceRange();
6473       S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6474       return true;
6475     }
6476   }
6477 
6478   if (AddressTaken && ParamType->isReferenceType()) {
6479     // If we originally had an address-of operator, but the
6480     // parameter has reference type, complain and (if things look
6481     // like they will work) drop the address-of operator.
6482     if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6483                                           ParamType.getNonReferenceType())) {
6484       S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6485         << ParamType;
6486       S.NoteTemplateParameterLocation(*Param);
6487       return true;
6488     }
6489 
6490     S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6491       << ParamType
6492       << FixItHint::CreateRemoval(AddrOpLoc);
6493     S.NoteTemplateParameterLocation(*Param);
6494 
6495     ArgType = Entity->getType();
6496   }
6497 
6498   // If the template parameter has pointer type, either we must have taken the
6499   // address or the argument must decay to a pointer.
6500   if (!AddressTaken && ParamType->isPointerType()) {
6501     if (Func) {
6502       // Function-to-pointer decay.
6503       ArgType = S.Context.getPointerType(Func->getType());
6504     } else if (Entity->getType()->isArrayType()) {
6505       // Array-to-pointer decay.
6506       ArgType = S.Context.getArrayDecayedType(Entity->getType());
6507     } else {
6508       // If the template parameter has pointer type but the address of
6509       // this object was not taken, complain and (possibly) recover by
6510       // taking the address of the entity.
6511       ArgType = S.Context.getPointerType(Entity->getType());
6512       if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6513         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6514           << ParamType;
6515         S.NoteTemplateParameterLocation(*Param);
6516         return true;
6517       }
6518 
6519       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6520         << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6521 
6522       S.NoteTemplateParameterLocation(*Param);
6523     }
6524   }
6525 
6526   if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6527                                                      Arg, ArgType))
6528     return true;
6529 
6530   // Create the template argument.
6531   SugaredConverted = TemplateArgument(Entity, ParamType);
6532   CanonicalConverted =
6533       TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
6534                        S.Context.getCanonicalType(ParamType));
6535   S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6536   return false;
6537 }
6538 
6539 /// Checks whether the given template argument is a pointer to
6540 /// member constant according to C++ [temp.arg.nontype]p1.
6541 static bool
6542 CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param,
6543                                      QualType ParamType, Expr *&ResultArg,
6544                                      TemplateArgument &SugaredConverted,
6545                                      TemplateArgument &CanonicalConverted) {
6546   bool Invalid = false;
6547 
6548   Expr *Arg = ResultArg;
6549   bool ObjCLifetimeConversion;
6550 
6551   // C++ [temp.arg.nontype]p1:
6552   //
6553   //   A template-argument for a non-type, non-template
6554   //   template-parameter shall be one of: [...]
6555   //
6556   //     -- a pointer to member expressed as described in 5.3.1.
6557   DeclRefExpr *DRE = nullptr;
6558 
6559   // In C++98/03 mode, give an extension warning on any extra parentheses.
6560   // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6561   bool ExtraParens = false;
6562   while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6563     if (!Invalid && !ExtraParens) {
6564       S.Diag(Arg->getBeginLoc(),
6565              S.getLangOpts().CPlusPlus11
6566                  ? diag::warn_cxx98_compat_template_arg_extra_parens
6567                  : diag::ext_template_arg_extra_parens)
6568           << Arg->getSourceRange();
6569       ExtraParens = true;
6570     }
6571 
6572     Arg = Parens->getSubExpr();
6573   }
6574 
6575   while (SubstNonTypeTemplateParmExpr *subst =
6576            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6577     Arg = subst->getReplacement()->IgnoreImpCasts();
6578 
6579   // A pointer-to-member constant written &Class::member.
6580   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6581     if (UnOp->getOpcode() == UO_AddrOf) {
6582       DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6583       if (DRE && !DRE->getQualifier())
6584         DRE = nullptr;
6585     }
6586   }
6587   // A constant of pointer-to-member type.
6588   else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6589     ValueDecl *VD = DRE->getDecl();
6590     if (VD->getType()->isMemberPointerType()) {
6591       if (isa<NonTypeTemplateParmDecl>(VD)) {
6592         if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6593           SugaredConverted = TemplateArgument(Arg);
6594           CanonicalConverted =
6595               S.Context.getCanonicalTemplateArgument(SugaredConverted);
6596         } else {
6597           SugaredConverted = TemplateArgument(VD, ParamType);
6598           CanonicalConverted =
6599               TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
6600                                S.Context.getCanonicalType(ParamType));
6601         }
6602         return Invalid;
6603       }
6604     }
6605 
6606     DRE = nullptr;
6607   }
6608 
6609   ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6610 
6611   // Check for a null pointer value.
6612   switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6613                                              Entity)) {
6614   case NPV_Error:
6615     return true;
6616   case NPV_NullPointer:
6617     S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6618     SugaredConverted = TemplateArgument(ParamType,
6619                                         /*isNullPtr*/ true);
6620     CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6621                                           /*isNullPtr*/ true);
6622     return false;
6623   case NPV_NotNullPointer:
6624     break;
6625   }
6626 
6627   if (S.IsQualificationConversion(ResultArg->getType(),
6628                                   ParamType.getNonReferenceType(), false,
6629                                   ObjCLifetimeConversion)) {
6630     ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6631                                     ResultArg->getValueKind())
6632                     .get();
6633   } else if (!S.Context.hasSameUnqualifiedType(
6634                  ResultArg->getType(), ParamType.getNonReferenceType())) {
6635     // We can't perform this conversion.
6636     S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6637         << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6638     S.NoteTemplateParameterLocation(*Param);
6639     return true;
6640   }
6641 
6642   if (!DRE)
6643     return S.Diag(Arg->getBeginLoc(),
6644                   diag::err_template_arg_not_pointer_to_member_form)
6645            << Arg->getSourceRange();
6646 
6647   if (isa<FieldDecl>(DRE->getDecl()) ||
6648       isa<IndirectFieldDecl>(DRE->getDecl()) ||
6649       isa<CXXMethodDecl>(DRE->getDecl())) {
6650     assert((isa<FieldDecl>(DRE->getDecl()) ||
6651             isa<IndirectFieldDecl>(DRE->getDecl()) ||
6652             cast<CXXMethodDecl>(DRE->getDecl())
6653                 ->isImplicitObjectMemberFunction()) &&
6654            "Only non-static member pointers can make it here");
6655 
6656     // Okay: this is the address of a non-static member, and therefore
6657     // a member pointer constant.
6658     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6659       SugaredConverted = TemplateArgument(Arg);
6660       CanonicalConverted =
6661           S.Context.getCanonicalTemplateArgument(SugaredConverted);
6662     } else {
6663       ValueDecl *D = DRE->getDecl();
6664       SugaredConverted = TemplateArgument(D, ParamType);
6665       CanonicalConverted =
6666           TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
6667                            S.Context.getCanonicalType(ParamType));
6668     }
6669     return Invalid;
6670   }
6671 
6672   // We found something else, but we don't know specifically what it is.
6673   S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6674       << Arg->getSourceRange();
6675   S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6676   return true;
6677 }
6678 
6679 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6680                                        QualType ParamType, Expr *Arg,
6681                                        TemplateArgument &SugaredConverted,
6682                                        TemplateArgument &CanonicalConverted,
6683                                        CheckTemplateArgumentKind CTAK) {
6684   SourceLocation StartLoc = Arg->getBeginLoc();
6685 
6686   // If the parameter type somehow involves auto, deduce the type now.
6687   DeducedType *DeducedT = ParamType->getContainedDeducedType();
6688   if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
6689     // During template argument deduction, we allow 'decltype(auto)' to
6690     // match an arbitrary dependent argument.
6691     // FIXME: The language rules don't say what happens in this case.
6692     // FIXME: We get an opaque dependent type out of decltype(auto) if the
6693     // expression is merely instantiation-dependent; is this enough?
6694     if (Arg->isTypeDependent()) {
6695       auto *AT = dyn_cast<AutoType>(DeducedT);
6696       if (AT && AT->isDecltypeAuto()) {
6697         SugaredConverted = TemplateArgument(Arg);
6698         CanonicalConverted = TemplateArgument(
6699             Context.getCanonicalTemplateArgument(SugaredConverted));
6700         return Arg;
6701       }
6702     }
6703 
6704     // When checking a deduced template argument, deduce from its type even if
6705     // the type is dependent, in order to check the types of non-type template
6706     // arguments line up properly in partial ordering.
6707     Expr *DeductionArg = Arg;
6708     if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6709       DeductionArg = PE->getPattern();
6710     TypeSourceInfo *TSI =
6711         Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
6712     if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
6713       InitializedEntity Entity =
6714           InitializedEntity::InitializeTemplateParameter(ParamType, Param);
6715       InitializationKind Kind = InitializationKind::CreateForInit(
6716           DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
6717       Expr *Inits[1] = {DeductionArg};
6718       ParamType =
6719           DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
6720       if (ParamType.isNull())
6721         return ExprError();
6722     } else {
6723       TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
6724                                  Param->getDepth() + 1);
6725       ParamType = QualType();
6726       TemplateDeductionResult Result =
6727           DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
6728                          /*DependentDeduction=*/true,
6729                          // We do not check constraints right now because the
6730                          // immediately-declared constraint of the auto type is
6731                          // also an associated constraint, and will be checked
6732                          // along with the other associated constraints after
6733                          // checking the template argument list.
6734                          /*IgnoreConstraints=*/true);
6735       if (Result == TemplateDeductionResult::AlreadyDiagnosed) {
6736         if (ParamType.isNull())
6737           return ExprError();
6738       } else if (Result != TemplateDeductionResult::Success) {
6739         Diag(Arg->getExprLoc(),
6740              diag::err_non_type_template_parm_type_deduction_failure)
6741             << Param->getDeclName() << Param->getType() << Arg->getType()
6742             << Arg->getSourceRange();
6743         NoteTemplateParameterLocation(*Param);
6744         return ExprError();
6745       }
6746     }
6747     // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6748     // an error. The error message normally references the parameter
6749     // declaration, but here we'll pass the argument location because that's
6750     // where the parameter type is deduced.
6751     ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6752     if (ParamType.isNull()) {
6753       NoteTemplateParameterLocation(*Param);
6754       return ExprError();
6755     }
6756   }
6757 
6758   // We should have already dropped all cv-qualifiers by now.
6759   assert(!ParamType.hasQualifiers() &&
6760          "non-type template parameter type cannot be qualified");
6761 
6762   // FIXME: When Param is a reference, should we check that Arg is an lvalue?
6763   if (CTAK == CTAK_Deduced &&
6764       (ParamType->isReferenceType()
6765            ? !Context.hasSameType(ParamType.getNonReferenceType(),
6766                                   Arg->getType())
6767            : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
6768     // FIXME: If either type is dependent, we skip the check. This isn't
6769     // correct, since during deduction we're supposed to have replaced each
6770     // template parameter with some unique (non-dependent) placeholder.
6771     // FIXME: If the argument type contains 'auto', we carry on and fail the
6772     // type check in order to force specific types to be more specialized than
6773     // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6774     // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
6775     if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6776         !Arg->getType()->getContainedDeducedType()) {
6777       SugaredConverted = TemplateArgument(Arg);
6778       CanonicalConverted = TemplateArgument(
6779           Context.getCanonicalTemplateArgument(SugaredConverted));
6780       return Arg;
6781     }
6782     // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6783     // we should actually be checking the type of the template argument in P,
6784     // not the type of the template argument deduced from A, against the
6785     // template parameter type.
6786     Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6787       << Arg->getType()
6788       << ParamType.getUnqualifiedType();
6789     NoteTemplateParameterLocation(*Param);
6790     return ExprError();
6791   }
6792 
6793   // If either the parameter has a dependent type or the argument is
6794   // type-dependent, there's nothing we can check now.
6795   if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6796     // Force the argument to the type of the parameter to maintain invariants.
6797     auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6798     if (PE)
6799       Arg = PE->getPattern();
6800     ExprResult E = ImpCastExprToType(
6801         Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6802         ParamType->isLValueReferenceType()   ? VK_LValue
6803         : ParamType->isRValueReferenceType() ? VK_XValue
6804                                              : VK_PRValue);
6805     if (E.isInvalid())
6806       return ExprError();
6807     if (PE) {
6808       // Recreate a pack expansion if we unwrapped one.
6809       E = new (Context)
6810           PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6811                             PE->getNumExpansions());
6812     }
6813     SugaredConverted = TemplateArgument(E.get());
6814     CanonicalConverted = TemplateArgument(
6815         Context.getCanonicalTemplateArgument(SugaredConverted));
6816     return E;
6817   }
6818 
6819   QualType CanonParamType = Context.getCanonicalType(ParamType);
6820   // Avoid making a copy when initializing a template parameter of class type
6821   // from a template parameter object of the same type. This is going beyond
6822   // the standard, but is required for soundness: in
6823   //   template<A a> struct X { X *p; X<a> *q; };
6824   // ... we need p and q to have the same type.
6825   //
6826   // Similarly, don't inject a call to a copy constructor when initializing
6827   // from a template parameter of the same type.
6828   Expr *InnerArg = Arg->IgnoreParenImpCasts();
6829   if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
6830       Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
6831     NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
6832     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
6833 
6834       SugaredConverted = TemplateArgument(TPO, ParamType);
6835       CanonicalConverted =
6836           TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
6837       return Arg;
6838     }
6839     if (isa<NonTypeTemplateParmDecl>(ND)) {
6840       SugaredConverted = TemplateArgument(Arg);
6841       CanonicalConverted =
6842           Context.getCanonicalTemplateArgument(SugaredConverted);
6843       return Arg;
6844     }
6845   }
6846 
6847   // The initialization of the parameter from the argument is
6848   // a constant-evaluated context.
6849   EnterExpressionEvaluationContext ConstantEvaluated(
6850       *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6851 
6852   bool IsConvertedConstantExpression = true;
6853   if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) {
6854     InitializationKind Kind = InitializationKind::CreateForInit(
6855         Arg->getBeginLoc(), /*DirectInit=*/false, Arg);
6856     Expr *Inits[1] = {Arg};
6857     InitializedEntity Entity =
6858         InitializedEntity::InitializeTemplateParameter(ParamType, Param);
6859     InitializationSequence InitSeq(*this, Entity, Kind, Inits);
6860     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
6861     if (Result.isInvalid() || !Result.get())
6862       return ExprError();
6863     Result = ActOnConstantExpression(Result.get());
6864     if (Result.isInvalid() || !Result.get())
6865       return ExprError();
6866     Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
6867                               /*DiscardedValue=*/false,
6868                               /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
6869               .get();
6870     IsConvertedConstantExpression = false;
6871   }
6872 
6873   if (getLangOpts().CPlusPlus17) {
6874     // C++17 [temp.arg.nontype]p1:
6875     //   A template-argument for a non-type template parameter shall be
6876     //   a converted constant expression of the type of the template-parameter.
6877     APValue Value;
6878     ExprResult ArgResult;
6879     if (IsConvertedConstantExpression) {
6880       ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
6881                                                    CCEK_TemplateArg, Param);
6882       if (ArgResult.isInvalid())
6883         return ExprError();
6884     } else {
6885       ArgResult = Arg;
6886     }
6887 
6888     // For a value-dependent argument, CheckConvertedConstantExpression is
6889     // permitted (and expected) to be unable to determine a value.
6890     if (ArgResult.get()->isValueDependent()) {
6891       SugaredConverted = TemplateArgument(ArgResult.get());
6892       CanonicalConverted =
6893           Context.getCanonicalTemplateArgument(SugaredConverted);
6894       return ArgResult;
6895     }
6896 
6897     APValue PreNarrowingValue;
6898     ArgResult = EvaluateConvertedConstantExpression(
6899         ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/
6900         false, PreNarrowingValue);
6901     if (ArgResult.isInvalid())
6902       return ExprError();
6903 
6904     if (Value.isLValue()) {
6905       APValue::LValueBase Base = Value.getLValueBase();
6906       auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6907       //   For a non-type template-parameter of pointer or reference type,
6908       //   the value of the constant expression shall not refer to
6909       assert(ParamType->isPointerOrReferenceType() ||
6910              ParamType->isNullPtrType());
6911       // -- a temporary object
6912       // -- a string literal
6913       // -- the result of a typeid expression, or
6914       // -- a predefined __func__ variable
6915       if (Base &&
6916           (!VD ||
6917            isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
6918         Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6919             << Arg->getSourceRange();
6920         return ExprError();
6921       }
6922 
6923       if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
6924           VD->getType()->isArrayType() &&
6925           Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
6926           !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6927         SugaredConverted = TemplateArgument(VD, ParamType);
6928         CanonicalConverted = TemplateArgument(
6929             cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType);
6930         return ArgResult.get();
6931       }
6932 
6933       // -- a subobject [until C++20]
6934       if (!getLangOpts().CPlusPlus20) {
6935         if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6936             Value.isLValueOnePastTheEnd()) {
6937           Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6938               << Value.getAsString(Context, ParamType);
6939           return ExprError();
6940         }
6941         assert((VD || !ParamType->isReferenceType()) &&
6942                "null reference should not be a constant expression");
6943         assert((!VD || !ParamType->isNullPtrType()) &&
6944                "non-null value of type nullptr_t?");
6945       }
6946     }
6947 
6948     if (Value.isAddrLabelDiff())
6949       return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6950 
6951     SugaredConverted = TemplateArgument(Context, ParamType, Value);
6952     CanonicalConverted = TemplateArgument(Context, CanonParamType, Value);
6953     return ArgResult.get();
6954   }
6955 
6956   // C++ [temp.arg.nontype]p5:
6957   //   The following conversions are performed on each expression used
6958   //   as a non-type template-argument. If a non-type
6959   //   template-argument cannot be converted to the type of the
6960   //   corresponding template-parameter then the program is
6961   //   ill-formed.
6962   if (ParamType->isIntegralOrEnumerationType()) {
6963     // C++11:
6964     //   -- for a non-type template-parameter of integral or
6965     //      enumeration type, conversions permitted in a converted
6966     //      constant expression are applied.
6967     //
6968     // C++98:
6969     //   -- for a non-type template-parameter of integral or
6970     //      enumeration type, integral promotions (4.5) and integral
6971     //      conversions (4.7) are applied.
6972 
6973     if (getLangOpts().CPlusPlus11) {
6974       // C++ [temp.arg.nontype]p1:
6975       //   A template-argument for a non-type, non-template template-parameter
6976       //   shall be one of:
6977       //
6978       //     -- for a non-type template-parameter of integral or enumeration
6979       //        type, a converted constant expression of the type of the
6980       //        template-parameter; or
6981       llvm::APSInt Value;
6982       ExprResult ArgResult =
6983         CheckConvertedConstantExpression(Arg, ParamType, Value,
6984                                          CCEK_TemplateArg);
6985       if (ArgResult.isInvalid())
6986         return ExprError();
6987 
6988       // We can't check arbitrary value-dependent arguments.
6989       if (ArgResult.get()->isValueDependent()) {
6990         SugaredConverted = TemplateArgument(ArgResult.get());
6991         CanonicalConverted =
6992             Context.getCanonicalTemplateArgument(SugaredConverted);
6993         return ArgResult;
6994       }
6995 
6996       // Widen the argument value to sizeof(parameter type). This is almost
6997       // always a no-op, except when the parameter type is bool. In
6998       // that case, this may extend the argument from 1 bit to 8 bits.
6999       QualType IntegerType = ParamType;
7000       if (const EnumType *Enum = IntegerType->getAs<EnumType>())
7001         IntegerType = Enum->getDecl()->getIntegerType();
7002       Value = Value.extOrTrunc(IntegerType->isBitIntType()
7003                                    ? Context.getIntWidth(IntegerType)
7004                                    : Context.getTypeSize(IntegerType));
7005 
7006       SugaredConverted = TemplateArgument(Context, Value, ParamType);
7007       CanonicalConverted =
7008           TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7009       return ArgResult;
7010     }
7011 
7012     ExprResult ArgResult = DefaultLvalueConversion(Arg);
7013     if (ArgResult.isInvalid())
7014       return ExprError();
7015     Arg = ArgResult.get();
7016 
7017     QualType ArgType = Arg->getType();
7018 
7019     // C++ [temp.arg.nontype]p1:
7020     //   A template-argument for a non-type, non-template
7021     //   template-parameter shall be one of:
7022     //
7023     //     -- an integral constant-expression of integral or enumeration
7024     //        type; or
7025     //     -- the name of a non-type template-parameter; or
7026     llvm::APSInt Value;
7027     if (!ArgType->isIntegralOrEnumerationType()) {
7028       Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7029           << ArgType << Arg->getSourceRange();
7030       NoteTemplateParameterLocation(*Param);
7031       return ExprError();
7032     } else if (!Arg->isValueDependent()) {
7033       class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7034         QualType T;
7035 
7036       public:
7037         TmplArgICEDiagnoser(QualType T) : T(T) { }
7038 
7039         SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7040                                              SourceLocation Loc) override {
7041           return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7042         }
7043       } Diagnoser(ArgType);
7044 
7045       Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7046       if (!Arg)
7047         return ExprError();
7048     }
7049 
7050     // From here on out, all we care about is the unqualified form
7051     // of the argument type.
7052     ArgType = ArgType.getUnqualifiedType();
7053 
7054     // Try to convert the argument to the parameter's type.
7055     if (Context.hasSameType(ParamType, ArgType)) {
7056       // Okay: no conversion necessary
7057     } else if (ParamType->isBooleanType()) {
7058       // This is an integral-to-boolean conversion.
7059       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7060     } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7061                !ParamType->isEnumeralType()) {
7062       // This is an integral promotion or conversion.
7063       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7064     } else {
7065       // We can't perform this conversion.
7066       Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7067           << Arg->getType() << ParamType << Arg->getSourceRange();
7068       NoteTemplateParameterLocation(*Param);
7069       return ExprError();
7070     }
7071 
7072     // Add the value of this argument to the list of converted
7073     // arguments. We use the bitwidth and signedness of the template
7074     // parameter.
7075     if (Arg->isValueDependent()) {
7076       // The argument is value-dependent. Create a new
7077       // TemplateArgument with the converted expression.
7078       SugaredConverted = TemplateArgument(Arg);
7079       CanonicalConverted =
7080           Context.getCanonicalTemplateArgument(SugaredConverted);
7081       return Arg;
7082     }
7083 
7084     QualType IntegerType = ParamType;
7085     if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
7086       IntegerType = Enum->getDecl()->getIntegerType();
7087     }
7088 
7089     if (ParamType->isBooleanType()) {
7090       // Value must be zero or one.
7091       Value = Value != 0;
7092       unsigned AllowedBits = Context.getTypeSize(IntegerType);
7093       if (Value.getBitWidth() != AllowedBits)
7094         Value = Value.extOrTrunc(AllowedBits);
7095       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7096     } else {
7097       llvm::APSInt OldValue = Value;
7098 
7099       // Coerce the template argument's value to the value it will have
7100       // based on the template parameter's type.
7101       unsigned AllowedBits = IntegerType->isBitIntType()
7102                                  ? Context.getIntWidth(IntegerType)
7103                                  : Context.getTypeSize(IntegerType);
7104       if (Value.getBitWidth() != AllowedBits)
7105         Value = Value.extOrTrunc(AllowedBits);
7106       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7107 
7108       // Complain if an unsigned parameter received a negative value.
7109       if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7110           (OldValue.isSigned() && OldValue.isNegative())) {
7111         Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7112             << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7113             << Arg->getSourceRange();
7114         NoteTemplateParameterLocation(*Param);
7115       }
7116 
7117       // Complain if we overflowed the template parameter's type.
7118       unsigned RequiredBits;
7119       if (IntegerType->isUnsignedIntegerOrEnumerationType())
7120         RequiredBits = OldValue.getActiveBits();
7121       else if (OldValue.isUnsigned())
7122         RequiredBits = OldValue.getActiveBits() + 1;
7123       else
7124         RequiredBits = OldValue.getSignificantBits();
7125       if (RequiredBits > AllowedBits) {
7126         Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7127             << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7128             << Arg->getSourceRange();
7129         NoteTemplateParameterLocation(*Param);
7130       }
7131     }
7132 
7133     QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7134     SugaredConverted = TemplateArgument(Context, Value, T);
7135     CanonicalConverted =
7136         TemplateArgument(Context, Value, Context.getCanonicalType(T));
7137     return Arg;
7138   }
7139 
7140   QualType ArgType = Arg->getType();
7141   DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7142 
7143   // Handle pointer-to-function, reference-to-function, and
7144   // pointer-to-member-function all in (roughly) the same way.
7145   if (// -- For a non-type template-parameter of type pointer to
7146       //    function, only the function-to-pointer conversion (4.3) is
7147       //    applied. If the template-argument represents a set of
7148       //    overloaded functions (or a pointer to such), the matching
7149       //    function is selected from the set (13.4).
7150       (ParamType->isPointerType() &&
7151        ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7152       // -- For a non-type template-parameter of type reference to
7153       //    function, no conversions apply. If the template-argument
7154       //    represents a set of overloaded functions, the matching
7155       //    function is selected from the set (13.4).
7156       (ParamType->isReferenceType() &&
7157        ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7158       // -- For a non-type template-parameter of type pointer to
7159       //    member function, no conversions apply. If the
7160       //    template-argument represents a set of overloaded member
7161       //    functions, the matching member function is selected from
7162       //    the set (13.4).
7163       (ParamType->isMemberPointerType() &&
7164        ParamType->castAs<MemberPointerType>()->getPointeeType()
7165          ->isFunctionType())) {
7166 
7167     if (Arg->getType() == Context.OverloadTy) {
7168       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7169                                                                 true,
7170                                                                 FoundResult)) {
7171         if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7172           return ExprError();
7173 
7174         ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7175         if (Res.isInvalid())
7176           return ExprError();
7177         Arg = Res.get();
7178         ArgType = Arg->getType();
7179       } else
7180         return ExprError();
7181     }
7182 
7183     if (!ParamType->isMemberPointerType()) {
7184       if (CheckTemplateArgumentAddressOfObjectOrFunction(
7185               *this, Param, ParamType, Arg, SugaredConverted,
7186               CanonicalConverted))
7187         return ExprError();
7188       return Arg;
7189     }
7190 
7191     if (CheckTemplateArgumentPointerToMember(
7192             *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7193       return ExprError();
7194     return Arg;
7195   }
7196 
7197   if (ParamType->isPointerType()) {
7198     //   -- for a non-type template-parameter of type pointer to
7199     //      object, qualification conversions (4.4) and the
7200     //      array-to-pointer conversion (4.2) are applied.
7201     // C++0x also allows a value of std::nullptr_t.
7202     assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7203            "Only object pointers allowed here");
7204 
7205     if (CheckTemplateArgumentAddressOfObjectOrFunction(
7206             *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7207       return ExprError();
7208     return Arg;
7209   }
7210 
7211   if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7212     //   -- For a non-type template-parameter of type reference to
7213     //      object, no conversions apply. The type referred to by the
7214     //      reference may be more cv-qualified than the (otherwise
7215     //      identical) type of the template-argument. The
7216     //      template-parameter is bound directly to the
7217     //      template-argument, which must be an lvalue.
7218     assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7219            "Only object references allowed here");
7220 
7221     if (Arg->getType() == Context.OverloadTy) {
7222       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
7223                                                  ParamRefType->getPointeeType(),
7224                                                                 true,
7225                                                                 FoundResult)) {
7226         if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7227           return ExprError();
7228         ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7229         if (Res.isInvalid())
7230           return ExprError();
7231         Arg = Res.get();
7232         ArgType = Arg->getType();
7233       } else
7234         return ExprError();
7235     }
7236 
7237     if (CheckTemplateArgumentAddressOfObjectOrFunction(
7238             *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7239       return ExprError();
7240     return Arg;
7241   }
7242 
7243   // Deal with parameters of type std::nullptr_t.
7244   if (ParamType->isNullPtrType()) {
7245     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7246       SugaredConverted = TemplateArgument(Arg);
7247       CanonicalConverted =
7248           Context.getCanonicalTemplateArgument(SugaredConverted);
7249       return Arg;
7250     }
7251 
7252     switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7253     case NPV_NotNullPointer:
7254       Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7255         << Arg->getType() << ParamType;
7256       NoteTemplateParameterLocation(*Param);
7257       return ExprError();
7258 
7259     case NPV_Error:
7260       return ExprError();
7261 
7262     case NPV_NullPointer:
7263       Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7264       SugaredConverted = TemplateArgument(ParamType,
7265                                           /*isNullPtr=*/true);
7266       CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7267                                             /*isNullPtr=*/true);
7268       return Arg;
7269     }
7270   }
7271 
7272   //     -- For a non-type template-parameter of type pointer to data
7273   //        member, qualification conversions (4.4) are applied.
7274   assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7275 
7276   if (CheckTemplateArgumentPointerToMember(
7277           *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7278     return ExprError();
7279   return Arg;
7280 }
7281 
7282 static void DiagnoseTemplateParameterListArityMismatch(
7283     Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7284     Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7285 
7286 bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7287                                          TemplateParameterList *Params,
7288                                          TemplateArgumentLoc &Arg,
7289                                          bool IsDeduced) {
7290   TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7291   auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7292   if (!Template) {
7293     // Any dependent template name is fine.
7294     assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7295     return false;
7296   }
7297 
7298   if (Template->isInvalidDecl())
7299     return true;
7300 
7301   // C++0x [temp.arg.template]p1:
7302   //   A template-argument for a template template-parameter shall be
7303   //   the name of a class template or an alias template, expressed as an
7304   //   id-expression. When the template-argument names a class template, only
7305   //   primary class templates are considered when matching the
7306   //   template template argument with the corresponding parameter;
7307   //   partial specializations are not considered even if their
7308   //   parameter lists match that of the template template parameter.
7309   //
7310   // Note that we also allow template template parameters here, which
7311   // will happen when we are dealing with, e.g., class template
7312   // partial specializations.
7313   if (!isa<ClassTemplateDecl>(Template) &&
7314       !isa<TemplateTemplateParmDecl>(Template) &&
7315       !isa<TypeAliasTemplateDecl>(Template) &&
7316       !isa<BuiltinTemplateDecl>(Template)) {
7317     assert(isa<FunctionTemplateDecl>(Template) &&
7318            "Only function templates are possible here");
7319     Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7320     Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7321       << Template;
7322   }
7323 
7324   // C++1z [temp.arg.template]p3: (DR 150)
7325   //   A template-argument matches a template template-parameter P when P
7326   //   is at least as specialized as the template-argument A.
7327   if (getLangOpts().RelaxedTemplateTemplateArgs) {
7328     // Quick check for the common case:
7329     //   If P contains a parameter pack, then A [...] matches P if each of A's
7330     //   template parameters matches the corresponding template parameter in
7331     //   the template-parameter-list of P.
7332     if (TemplateParameterListsAreEqual(
7333             Template->getTemplateParameters(), Params, false,
7334             TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) &&
7335         // If the argument has no associated constraints, then the parameter is
7336         // definitely at least as specialized as the argument.
7337         // Otherwise - we need a more thorough check.
7338         !Template->hasAssociatedConstraints())
7339       return false;
7340 
7341     if (isTemplateTemplateParameterAtLeastAsSpecializedAs(
7342             Params, Template, DefaultArgs, Arg.getLocation(), IsDeduced)) {
7343       // P2113
7344       // C++20[temp.func.order]p2
7345       //   [...] If both deductions succeed, the partial ordering selects the
7346       // more constrained template (if one exists) as determined below.
7347       SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7348       Params->getAssociatedConstraints(ParamsAC);
7349       // C++2a[temp.arg.template]p3
7350       //   [...] In this comparison, if P is unconstrained, the constraints on A
7351       //   are not considered.
7352       if (ParamsAC.empty())
7353         return false;
7354 
7355       Template->getAssociatedConstraints(TemplateAC);
7356 
7357       bool IsParamAtLeastAsConstrained;
7358       if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7359                                  IsParamAtLeastAsConstrained))
7360         return true;
7361       if (!IsParamAtLeastAsConstrained) {
7362         Diag(Arg.getLocation(),
7363              diag::err_template_template_parameter_not_at_least_as_constrained)
7364             << Template << Param << Arg.getSourceRange();
7365         Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7366         Diag(Template->getLocation(), diag::note_entity_declared_at)
7367             << Template;
7368         MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7369                                                       TemplateAC);
7370         return true;
7371       }
7372       return false;
7373     }
7374     // FIXME: Produce better diagnostics for deduction failures.
7375   }
7376 
7377   return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
7378                                          Params,
7379                                          true,
7380                                          TPL_TemplateTemplateArgumentMatch,
7381                                          Arg.getLocation());
7382 }
7383 
7384 static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7385                                                 unsigned HereDiagID,
7386                                                 unsigned ExternalDiagID) {
7387   if (Decl.getLocation().isValid())
7388     return S.Diag(Decl.getLocation(), HereDiagID);
7389 
7390   SmallString<128> Str;
7391   llvm::raw_svector_ostream Out(Str);
7392   PrintingPolicy PP = S.getPrintingPolicy();
7393   PP.TerseOutput = 1;
7394   Decl.print(Out, PP);
7395   return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7396 }
7397 
7398 void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7399                                 std::optional<SourceRange> ParamRange) {
7400   SemaDiagnosticBuilder DB =
7401       noteLocation(*this, Decl, diag::note_template_decl_here,
7402                    diag::note_template_decl_external);
7403   if (ParamRange && ParamRange->isValid()) {
7404     assert(Decl.getLocation().isValid() &&
7405            "Parameter range has location when Decl does not");
7406     DB << *ParamRange;
7407   }
7408 }
7409 
7410 void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7411   noteLocation(*this, Decl, diag::note_template_param_here,
7412                diag::note_template_param_external);
7413 }
7414 
7415 ExprResult Sema::BuildExpressionFromDeclTemplateArgument(
7416     const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7417     NamedDecl *TemplateParam) {
7418   // C++ [temp.param]p8:
7419   //
7420   //   A non-type template-parameter of type "array of T" or
7421   //   "function returning T" is adjusted to be of type "pointer to
7422   //   T" or "pointer to function returning T", respectively.
7423   if (ParamType->isArrayType())
7424     ParamType = Context.getArrayDecayedType(ParamType);
7425   else if (ParamType->isFunctionType())
7426     ParamType = Context.getPointerType(ParamType);
7427 
7428   // For a NULL non-type template argument, return nullptr casted to the
7429   // parameter's type.
7430   if (Arg.getKind() == TemplateArgument::NullPtr) {
7431     return ImpCastExprToType(
7432              new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7433                              ParamType,
7434                              ParamType->getAs<MemberPointerType>()
7435                                ? CK_NullToMemberPointer
7436                                : CK_NullToPointer);
7437   }
7438   assert(Arg.getKind() == TemplateArgument::Declaration &&
7439          "Only declaration template arguments permitted here");
7440 
7441   ValueDecl *VD = Arg.getAsDecl();
7442 
7443   CXXScopeSpec SS;
7444   if (ParamType->isMemberPointerType()) {
7445     // If this is a pointer to member, we need to use a qualified name to
7446     // form a suitable pointer-to-member constant.
7447     assert(VD->getDeclContext()->isRecord() &&
7448            (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7449             isa<IndirectFieldDecl>(VD)));
7450     QualType ClassType
7451       = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
7452     NestedNameSpecifier *Qualifier
7453       = NestedNameSpecifier::Create(Context, nullptr, false,
7454                                     ClassType.getTypePtr());
7455     SS.MakeTrivial(Context, Qualifier, Loc);
7456   }
7457 
7458   ExprResult RefExpr = BuildDeclarationNameExpr(
7459       SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7460   if (RefExpr.isInvalid())
7461     return ExprError();
7462 
7463   // For a pointer, the argument declaration is the pointee. Take its address.
7464   QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7465   if (ParamType->isPointerType() && !ElemT.isNull() &&
7466       Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7467     // Decay an array argument if we want a pointer to its first element.
7468     RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7469     if (RefExpr.isInvalid())
7470       return ExprError();
7471   } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7472     // For any other pointer, take the address (or form a pointer-to-member).
7473     RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7474     if (RefExpr.isInvalid())
7475       return ExprError();
7476   } else if (ParamType->isRecordType()) {
7477     assert(isa<TemplateParamObjectDecl>(VD) &&
7478            "arg for class template param not a template parameter object");
7479     // No conversions apply in this case.
7480     return RefExpr;
7481   } else {
7482     assert(ParamType->isReferenceType() &&
7483            "unexpected type for decl template argument");
7484     if (NonTypeTemplateParmDecl *NTTP =
7485             dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7486       QualType TemplateParamType = NTTP->getType();
7487       const AutoType *AT = TemplateParamType->getAs<AutoType>();
7488       if (AT && AT->isDecltypeAuto()) {
7489         RefExpr = new (getASTContext()) SubstNonTypeTemplateParmExpr(
7490             ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7491             RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7492             /*PackIndex=*/std::nullopt,
7493             /*RefParam=*/true);
7494       }
7495     }
7496   }
7497 
7498   // At this point we should have the right value category.
7499   assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7500          "value kind mismatch for non-type template argument");
7501 
7502   // The type of the template parameter can differ from the type of the
7503   // argument in various ways; convert it now if necessary.
7504   QualType DestExprType = ParamType.getNonLValueExprType(Context);
7505   if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7506     CastKind CK;
7507     QualType Ignored;
7508     if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7509         IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7510       CK = CK_NoOp;
7511     } else if (ParamType->isVoidPointerType() &&
7512                RefExpr.get()->getType()->isPointerType()) {
7513       CK = CK_BitCast;
7514     } else {
7515       // FIXME: Pointers to members can need conversion derived-to-base or
7516       // base-to-derived conversions. We currently don't retain enough
7517       // information to convert properly (we need to track a cast path or
7518       // subobject number in the template argument).
7519       llvm_unreachable(
7520           "unexpected conversion required for non-type template argument");
7521     }
7522     RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7523                                 RefExpr.get()->getValueKind());
7524   }
7525 
7526   return RefExpr;
7527 }
7528 
7529 /// Construct a new expression that refers to the given
7530 /// integral template argument with the given source-location
7531 /// information.
7532 ///
7533 /// This routine takes care of the mapping from an integral template
7534 /// argument (which may have any integral type) to the appropriate
7535 /// literal value.
7536 static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
7537     Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
7538   assert(OrigT->isIntegralOrEnumerationType());
7539 
7540   // If this is an enum type that we're instantiating, we need to use an integer
7541   // type the same size as the enumerator.  We don't want to build an
7542   // IntegerLiteral with enum type.  The integer type of an enum type can be of
7543   // any integral type with C++11 enum classes, make sure we create the right
7544   // type of literal for it.
7545   QualType T = OrigT;
7546   if (const EnumType *ET = OrigT->getAs<EnumType>())
7547     T = ET->getDecl()->getIntegerType();
7548 
7549   Expr *E;
7550   if (T->isAnyCharacterType()) {
7551     CharacterLiteralKind Kind;
7552     if (T->isWideCharType())
7553       Kind = CharacterLiteralKind::Wide;
7554     else if (T->isChar8Type() && S.getLangOpts().Char8)
7555       Kind = CharacterLiteralKind::UTF8;
7556     else if (T->isChar16Type())
7557       Kind = CharacterLiteralKind::UTF16;
7558     else if (T->isChar32Type())
7559       Kind = CharacterLiteralKind::UTF32;
7560     else
7561       Kind = CharacterLiteralKind::Ascii;
7562 
7563     E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
7564   } else if (T->isBooleanType()) {
7565     E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
7566   } else {
7567     E = IntegerLiteral::Create(S.Context, Int, T, Loc);
7568   }
7569 
7570   if (OrigT->isEnumeralType()) {
7571     // FIXME: This is a hack. We need a better way to handle substituted
7572     // non-type template parameters.
7573     E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
7574                                nullptr, S.CurFPFeatureOverrides(),
7575                                S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
7576                                Loc, Loc);
7577   }
7578 
7579   return E;
7580 }
7581 
7582 static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
7583     Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
7584   auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
7585     auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
7586     ILE->setType(T);
7587     return ILE;
7588   };
7589 
7590   switch (Val.getKind()) {
7591   case APValue::AddrLabelDiff:
7592     // This cannot occur in a template argument at all.
7593   case APValue::Array:
7594   case APValue::Struct:
7595   case APValue::Union:
7596     // These can only occur within a template parameter object, which is
7597     // represented as a TemplateArgument::Declaration.
7598     llvm_unreachable("unexpected template argument value");
7599 
7600   case APValue::Int:
7601     return BuildExpressionFromIntegralTemplateArgumentValue(S, T, Val.getInt(),
7602                                                             Loc);
7603 
7604   case APValue::Float:
7605     return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
7606                                    T, Loc);
7607 
7608   case APValue::FixedPoint:
7609     return FixedPointLiteral::CreateFromRawInt(
7610         S.Context, Val.getFixedPoint().getValue(), T, Loc,
7611         Val.getFixedPoint().getScale());
7612 
7613   case APValue::ComplexInt: {
7614     QualType ElemT = T->castAs<ComplexType>()->getElementType();
7615     return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
7616                              S, ElemT, Val.getComplexIntReal(), Loc),
7617                          BuildExpressionFromIntegralTemplateArgumentValue(
7618                              S, ElemT, Val.getComplexIntImag(), Loc)});
7619   }
7620 
7621   case APValue::ComplexFloat: {
7622     QualType ElemT = T->castAs<ComplexType>()->getElementType();
7623     return MakeInitList(
7624         {FloatingLiteral::Create(S.Context, Val.getComplexFloatReal(), true,
7625                                  ElemT, Loc),
7626          FloatingLiteral::Create(S.Context, Val.getComplexFloatImag(), true,
7627                                  ElemT, Loc)});
7628   }
7629 
7630   case APValue::Vector: {
7631     QualType ElemT = T->castAs<VectorType>()->getElementType();
7632     llvm::SmallVector<Expr *, 8> Elts;
7633     for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
7634       Elts.push_back(BuildExpressionFromNonTypeTemplateArgumentValue(
7635           S, ElemT, Val.getVectorElt(I), Loc));
7636     return MakeInitList(Elts);
7637   }
7638 
7639   case APValue::None:
7640   case APValue::Indeterminate:
7641     llvm_unreachable("Unexpected APValue kind.");
7642   case APValue::LValue:
7643   case APValue::MemberPointer:
7644     // There isn't necessarily a valid equivalent source-level syntax for
7645     // these; in particular, a naive lowering might violate access control.
7646     // So for now we lower to a ConstantExpr holding the value, wrapped around
7647     // an OpaqueValueExpr.
7648     // FIXME: We should have a better representation for this.
7649     ExprValueKind VK = VK_PRValue;
7650     if (T->isReferenceType()) {
7651       T = T->getPointeeType();
7652       VK = VK_LValue;
7653     }
7654     auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
7655     return ConstantExpr::Create(S.Context, OVE, Val);
7656   }
7657   llvm_unreachable("Unhandled APValue::ValueKind enum");
7658 }
7659 
7660 ExprResult
7661 Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
7662                                                  SourceLocation Loc) {
7663   switch (Arg.getKind()) {
7664   case TemplateArgument::Null:
7665   case TemplateArgument::Type:
7666   case TemplateArgument::Template:
7667   case TemplateArgument::TemplateExpansion:
7668   case TemplateArgument::Pack:
7669     llvm_unreachable("not a non-type template argument");
7670 
7671   case TemplateArgument::Expression:
7672     return Arg.getAsExpr();
7673 
7674   case TemplateArgument::NullPtr:
7675   case TemplateArgument::Declaration:
7676     return BuildExpressionFromDeclTemplateArgument(
7677         Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
7678 
7679   case TemplateArgument::Integral:
7680     return BuildExpressionFromIntegralTemplateArgumentValue(
7681         *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
7682 
7683   case TemplateArgument::StructuralValue:
7684     return BuildExpressionFromNonTypeTemplateArgumentValue(
7685         *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
7686   }
7687   llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
7688 }
7689 
7690 /// Match two template parameters within template parameter lists.
7691 static bool MatchTemplateParameterKind(
7692     Sema &S, NamedDecl *New,
7693     const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
7694     const NamedDecl *OldInstFrom, bool Complain,
7695     Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
7696   // Check the actual kind (type, non-type, template).
7697   if (Old->getKind() != New->getKind()) {
7698     if (Complain) {
7699       unsigned NextDiag = diag::err_template_param_different_kind;
7700       if (TemplateArgLoc.isValid()) {
7701         S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7702         NextDiag = diag::note_template_param_different_kind;
7703       }
7704       S.Diag(New->getLocation(), NextDiag)
7705         << (Kind != Sema::TPL_TemplateMatch);
7706       S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7707         << (Kind != Sema::TPL_TemplateMatch);
7708     }
7709 
7710     return false;
7711   }
7712 
7713   // Check that both are parameter packs or neither are parameter packs.
7714   // However, if we are matching a template template argument to a
7715   // template template parameter, the template template parameter can have
7716   // a parameter pack where the template template argument does not.
7717   if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7718       !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
7719         Old->isTemplateParameterPack())) {
7720     if (Complain) {
7721       unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7722       if (TemplateArgLoc.isValid()) {
7723         S.Diag(TemplateArgLoc,
7724              diag::err_template_arg_template_params_mismatch);
7725         NextDiag = diag::note_template_parameter_pack_non_pack;
7726       }
7727 
7728       unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7729                       : isa<NonTypeTemplateParmDecl>(New)? 1
7730                       : 2;
7731       S.Diag(New->getLocation(), NextDiag)
7732         << ParamKind << New->isParameterPack();
7733       S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7734         << ParamKind << Old->isParameterPack();
7735     }
7736 
7737     return false;
7738   }
7739 
7740   // For non-type template parameters, check the type of the parameter.
7741   if (NonTypeTemplateParmDecl *OldNTTP
7742                                     = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7743     NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7744 
7745     // If we are matching a template template argument to a template
7746     // template parameter and one of the non-type template parameter types
7747     // is dependent, then we must wait until template instantiation time
7748     // to actually compare the arguments.
7749     if (Kind != Sema::TPL_TemplateTemplateArgumentMatch ||
7750         (!OldNTTP->getType()->isDependentType() &&
7751          !NewNTTP->getType()->isDependentType())) {
7752       // C++20 [temp.over.link]p6:
7753       //   Two [non-type] template-parameters are equivalent [if] they have
7754       //   equivalent types ignoring the use of type-constraints for
7755       //   placeholder types
7756       QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
7757       QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
7758       if (!S.Context.hasSameType(OldType, NewType)) {
7759         if (Complain) {
7760           unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7761           if (TemplateArgLoc.isValid()) {
7762             S.Diag(TemplateArgLoc,
7763                    diag::err_template_arg_template_params_mismatch);
7764             NextDiag = diag::note_template_nontype_parm_different_type;
7765           }
7766           S.Diag(NewNTTP->getLocation(), NextDiag)
7767             << NewNTTP->getType()
7768             << (Kind != Sema::TPL_TemplateMatch);
7769           S.Diag(OldNTTP->getLocation(),
7770                  diag::note_template_nontype_parm_prev_declaration)
7771             << OldNTTP->getType();
7772         }
7773 
7774         return false;
7775       }
7776     }
7777   }
7778   // For template template parameters, check the template parameter types.
7779   // The template parameter lists of template template
7780   // parameters must agree.
7781   else if (TemplateTemplateParmDecl *OldTTP =
7782                dyn_cast<TemplateTemplateParmDecl>(Old)) {
7783     TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7784     if (!S.TemplateParameterListsAreEqual(
7785             NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
7786             OldTTP->getTemplateParameters(), Complain,
7787             (Kind == Sema::TPL_TemplateMatch
7788                  ? Sema::TPL_TemplateTemplateParmMatch
7789                  : Kind),
7790             TemplateArgLoc))
7791       return false;
7792   }
7793 
7794   if (Kind != Sema::TPL_TemplateParamsEquivalent &&
7795       Kind != Sema::TPL_TemplateTemplateArgumentMatch &&
7796       !isa<TemplateTemplateParmDecl>(Old)) {
7797     const Expr *NewC = nullptr, *OldC = nullptr;
7798 
7799     if (isa<TemplateTypeParmDecl>(New)) {
7800       if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
7801         NewC = TC->getImmediatelyDeclaredConstraint();
7802       if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
7803         OldC = TC->getImmediatelyDeclaredConstraint();
7804     } else if (isa<NonTypeTemplateParmDecl>(New)) {
7805       if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
7806                               ->getPlaceholderTypeConstraint())
7807         NewC = E;
7808       if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
7809                               ->getPlaceholderTypeConstraint())
7810         OldC = E;
7811     } else
7812       llvm_unreachable("unexpected template parameter type");
7813 
7814     auto Diagnose = [&] {
7815       S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
7816            diag::err_template_different_type_constraint);
7817       S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
7818            diag::note_template_prev_declaration) << /*declaration*/0;
7819     };
7820 
7821     if (!NewC != !OldC) {
7822       if (Complain)
7823         Diagnose();
7824       return false;
7825     }
7826 
7827     if (NewC) {
7828       if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
7829                                            NewC)) {
7830         if (Complain)
7831           Diagnose();
7832         return false;
7833       }
7834     }
7835   }
7836 
7837   return true;
7838 }
7839 
7840 /// Diagnose a known arity mismatch when comparing template argument
7841 /// lists.
7842 static
7843 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
7844                                                 TemplateParameterList *New,
7845                                                 TemplateParameterList *Old,
7846                                       Sema::TemplateParameterListEqualKind Kind,
7847                                                 SourceLocation TemplateArgLoc) {
7848   unsigned NextDiag = diag::err_template_param_list_different_arity;
7849   if (TemplateArgLoc.isValid()) {
7850     S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7851     NextDiag = diag::note_template_param_list_different_arity;
7852   }
7853   S.Diag(New->getTemplateLoc(), NextDiag)
7854     << (New->size() > Old->size())
7855     << (Kind != Sema::TPL_TemplateMatch)
7856     << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7857   S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7858     << (Kind != Sema::TPL_TemplateMatch)
7859     << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7860 }
7861 
7862 bool Sema::TemplateParameterListsAreEqual(
7863     const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
7864     const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
7865     TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
7866   if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7867     if (Complain)
7868       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7869                                                  TemplateArgLoc);
7870 
7871     return false;
7872   }
7873 
7874   // C++0x [temp.arg.template]p3:
7875   //   A template-argument matches a template template-parameter (call it P)
7876   //   when each of the template parameters in the template-parameter-list of
7877   //   the template-argument's corresponding class template or alias template
7878   //   (call it A) matches the corresponding template parameter in the
7879   //   template-parameter-list of P. [...]
7880   TemplateParameterList::iterator NewParm = New->begin();
7881   TemplateParameterList::iterator NewParmEnd = New->end();
7882   for (TemplateParameterList::iterator OldParm = Old->begin(),
7883                                     OldParmEnd = Old->end();
7884        OldParm != OldParmEnd; ++OldParm) {
7885     if (Kind != TPL_TemplateTemplateArgumentMatch ||
7886         !(*OldParm)->isTemplateParameterPack()) {
7887       if (NewParm == NewParmEnd) {
7888         if (Complain)
7889           DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7890                                                      TemplateArgLoc);
7891 
7892         return false;
7893       }
7894 
7895       if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7896                                       OldInstFrom, Complain, Kind,
7897                                       TemplateArgLoc))
7898         return false;
7899 
7900       ++NewParm;
7901       continue;
7902     }
7903 
7904     // C++0x [temp.arg.template]p3:
7905     //   [...] When P's template- parameter-list contains a template parameter
7906     //   pack (14.5.3), the template parameter pack will match zero or more
7907     //   template parameters or template parameter packs in the
7908     //   template-parameter-list of A with the same type and form as the
7909     //   template parameter pack in P (ignoring whether those template
7910     //   parameters are template parameter packs).
7911     for (; NewParm != NewParmEnd; ++NewParm) {
7912       if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7913                                       OldInstFrom, Complain, Kind,
7914                                       TemplateArgLoc))
7915         return false;
7916     }
7917   }
7918 
7919   // Make sure we exhausted all of the arguments.
7920   if (NewParm != NewParmEnd) {
7921     if (Complain)
7922       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7923                                                  TemplateArgLoc);
7924 
7925     return false;
7926   }
7927 
7928   if (Kind != TPL_TemplateTemplateArgumentMatch &&
7929       Kind != TPL_TemplateParamsEquivalent) {
7930     const Expr *NewRC = New->getRequiresClause();
7931     const Expr *OldRC = Old->getRequiresClause();
7932 
7933     auto Diagnose = [&] {
7934       Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
7935            diag::err_template_different_requires_clause);
7936       Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
7937            diag::note_template_prev_declaration) << /*declaration*/0;
7938     };
7939 
7940     if (!NewRC != !OldRC) {
7941       if (Complain)
7942         Diagnose();
7943       return false;
7944     }
7945 
7946     if (NewRC) {
7947       if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
7948                                          NewRC)) {
7949         if (Complain)
7950           Diagnose();
7951         return false;
7952       }
7953     }
7954   }
7955 
7956   return true;
7957 }
7958 
7959 bool
7960 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
7961   if (!S)
7962     return false;
7963 
7964   // Find the nearest enclosing declaration scope.
7965   S = S->getDeclParent();
7966 
7967   // C++ [temp.pre]p6: [P2096]
7968   //   A template, explicit specialization, or partial specialization shall not
7969   //   have C linkage.
7970   DeclContext *Ctx = S->getEntity();
7971   if (Ctx && Ctx->isExternCContext()) {
7972     Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7973         << TemplateParams->getSourceRange();
7974     if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7975       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7976     return true;
7977   }
7978   Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
7979 
7980   // C++ [temp]p2:
7981   //   A template-declaration can appear only as a namespace scope or
7982   //   class scope declaration.
7983   // C++ [temp.expl.spec]p3:
7984   //   An explicit specialization may be declared in any scope in which the
7985   //   corresponding primary template may be defined.
7986   // C++ [temp.class.spec]p6: [P2096]
7987   //   A partial specialization may be declared in any scope in which the
7988   //   corresponding primary template may be defined.
7989   if (Ctx) {
7990     if (Ctx->isFileContext())
7991       return false;
7992     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7993       // C++ [temp.mem]p2:
7994       //   A local class shall not have member templates.
7995       if (RD->isLocalClass())
7996         return Diag(TemplateParams->getTemplateLoc(),
7997                     diag::err_template_inside_local_class)
7998           << TemplateParams->getSourceRange();
7999       else
8000         return false;
8001     }
8002   }
8003 
8004   return Diag(TemplateParams->getTemplateLoc(),
8005               diag::err_template_outside_namespace_or_class_scope)
8006     << TemplateParams->getSourceRange();
8007 }
8008 
8009 /// Determine what kind of template specialization the given declaration
8010 /// is.
8011 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8012   if (!D)
8013     return TSK_Undeclared;
8014 
8015   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8016     return Record->getTemplateSpecializationKind();
8017   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8018     return Function->getTemplateSpecializationKind();
8019   if (VarDecl *Var = dyn_cast<VarDecl>(D))
8020     return Var->getTemplateSpecializationKind();
8021 
8022   return TSK_Undeclared;
8023 }
8024 
8025 /// Check whether a specialization is well-formed in the current
8026 /// context.
8027 ///
8028 /// This routine determines whether a template specialization can be declared
8029 /// in the current context (C++ [temp.expl.spec]p2).
8030 ///
8031 /// \param S the semantic analysis object for which this check is being
8032 /// performed.
8033 ///
8034 /// \param Specialized the entity being specialized or instantiated, which
8035 /// may be a kind of template (class template, function template, etc.) or
8036 /// a member of a class template (member function, static data member,
8037 /// member class).
8038 ///
8039 /// \param PrevDecl the previous declaration of this entity, if any.
8040 ///
8041 /// \param Loc the location of the explicit specialization or instantiation of
8042 /// this entity.
8043 ///
8044 /// \param IsPartialSpecialization whether this is a partial specialization of
8045 /// a class template.
8046 ///
8047 /// \returns true if there was an error that we cannot recover from, false
8048 /// otherwise.
8049 static bool CheckTemplateSpecializationScope(Sema &S,
8050                                              NamedDecl *Specialized,
8051                                              NamedDecl *PrevDecl,
8052                                              SourceLocation Loc,
8053                                              bool IsPartialSpecialization) {
8054   // Keep these "kind" numbers in sync with the %select statements in the
8055   // various diagnostics emitted by this routine.
8056   int EntityKind = 0;
8057   if (isa<ClassTemplateDecl>(Specialized))
8058     EntityKind = IsPartialSpecialization? 1 : 0;
8059   else if (isa<VarTemplateDecl>(Specialized))
8060     EntityKind = IsPartialSpecialization ? 3 : 2;
8061   else if (isa<FunctionTemplateDecl>(Specialized))
8062     EntityKind = 4;
8063   else if (isa<CXXMethodDecl>(Specialized))
8064     EntityKind = 5;
8065   else if (isa<VarDecl>(Specialized))
8066     EntityKind = 6;
8067   else if (isa<RecordDecl>(Specialized))
8068     EntityKind = 7;
8069   else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8070     EntityKind = 8;
8071   else {
8072     S.Diag(Loc, diag::err_template_spec_unknown_kind)
8073       << S.getLangOpts().CPlusPlus11;
8074     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8075     return true;
8076   }
8077 
8078   // C++ [temp.expl.spec]p2:
8079   //   An explicit specialization may be declared in any scope in which
8080   //   the corresponding primary template may be defined.
8081   if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8082     S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8083       << Specialized;
8084     return true;
8085   }
8086 
8087   // C++ [temp.class.spec]p6:
8088   //   A class template partial specialization may be declared in any
8089   //   scope in which the primary template may be defined.
8090   DeclContext *SpecializedContext =
8091       Specialized->getDeclContext()->getRedeclContext();
8092   DeclContext *DC = S.CurContext->getRedeclContext();
8093 
8094   // Make sure that this redeclaration (or definition) occurs in the same
8095   // scope or an enclosing namespace.
8096   if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8097                             : DC->Equals(SpecializedContext))) {
8098     if (isa<TranslationUnitDecl>(SpecializedContext))
8099       S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8100         << EntityKind << Specialized;
8101     else {
8102       auto *ND = cast<NamedDecl>(SpecializedContext);
8103       int Diag = diag::err_template_spec_redecl_out_of_scope;
8104       if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8105         Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8106       S.Diag(Loc, Diag) << EntityKind << Specialized
8107                         << ND << isa<CXXRecordDecl>(ND);
8108     }
8109 
8110     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8111 
8112     // Don't allow specializing in the wrong class during error recovery.
8113     // Otherwise, things can go horribly wrong.
8114     if (DC->isRecord())
8115       return true;
8116   }
8117 
8118   return false;
8119 }
8120 
8121 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8122   if (!E->isTypeDependent())
8123     return SourceLocation();
8124   DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8125   Checker.TraverseStmt(E);
8126   if (Checker.MatchLoc.isInvalid())
8127     return E->getSourceRange();
8128   return Checker.MatchLoc;
8129 }
8130 
8131 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8132   if (!TL.getType()->isDependentType())
8133     return SourceLocation();
8134   DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8135   Checker.TraverseTypeLoc(TL);
8136   if (Checker.MatchLoc.isInvalid())
8137     return TL.getSourceRange();
8138   return Checker.MatchLoc;
8139 }
8140 
8141 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8142 /// that checks non-type template partial specialization arguments.
8143 static bool CheckNonTypeTemplatePartialSpecializationArgs(
8144     Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8145     const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8146   for (unsigned I = 0; I != NumArgs; ++I) {
8147     if (Args[I].getKind() == TemplateArgument::Pack) {
8148       if (CheckNonTypeTemplatePartialSpecializationArgs(
8149               S, TemplateNameLoc, Param, Args[I].pack_begin(),
8150               Args[I].pack_size(), IsDefaultArgument))
8151         return true;
8152 
8153       continue;
8154     }
8155 
8156     if (Args[I].getKind() != TemplateArgument::Expression)
8157       continue;
8158 
8159     Expr *ArgExpr = Args[I].getAsExpr();
8160 
8161     // We can have a pack expansion of any of the bullets below.
8162     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8163       ArgExpr = Expansion->getPattern();
8164 
8165     // Strip off any implicit casts we added as part of type checking.
8166     while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8167       ArgExpr = ICE->getSubExpr();
8168 
8169     // C++ [temp.class.spec]p8:
8170     //   A non-type argument is non-specialized if it is the name of a
8171     //   non-type parameter. All other non-type arguments are
8172     //   specialized.
8173     //
8174     // Below, we check the two conditions that only apply to
8175     // specialized non-type arguments, so skip any non-specialized
8176     // arguments.
8177     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8178       if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8179         continue;
8180 
8181     // C++ [temp.class.spec]p9:
8182     //   Within the argument list of a class template partial
8183     //   specialization, the following restrictions apply:
8184     //     -- A partially specialized non-type argument expression
8185     //        shall not involve a template parameter of the partial
8186     //        specialization except when the argument expression is a
8187     //        simple identifier.
8188     //     -- The type of a template parameter corresponding to a
8189     //        specialized non-type argument shall not be dependent on a
8190     //        parameter of the specialization.
8191     // DR1315 removes the first bullet, leaving an incoherent set of rules.
8192     // We implement a compromise between the original rules and DR1315:
8193     //     --  A specialized non-type template argument shall not be
8194     //         type-dependent and the corresponding template parameter
8195     //         shall have a non-dependent type.
8196     SourceRange ParamUseRange =
8197         findTemplateParameterInType(Param->getDepth(), ArgExpr);
8198     if (ParamUseRange.isValid()) {
8199       if (IsDefaultArgument) {
8200         S.Diag(TemplateNameLoc,
8201                diag::err_dependent_non_type_arg_in_partial_spec);
8202         S.Diag(ParamUseRange.getBegin(),
8203                diag::note_dependent_non_type_default_arg_in_partial_spec)
8204           << ParamUseRange;
8205       } else {
8206         S.Diag(ParamUseRange.getBegin(),
8207                diag::err_dependent_non_type_arg_in_partial_spec)
8208           << ParamUseRange;
8209       }
8210       return true;
8211     }
8212 
8213     ParamUseRange = findTemplateParameter(
8214         Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8215     if (ParamUseRange.isValid()) {
8216       S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8217              diag::err_dependent_typed_non_type_arg_in_partial_spec)
8218           << Param->getType();
8219       S.NoteTemplateParameterLocation(*Param);
8220       return true;
8221     }
8222   }
8223 
8224   return false;
8225 }
8226 
8227 bool Sema::CheckTemplatePartialSpecializationArgs(
8228     SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8229     unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8230   // We have to be conservative when checking a template in a dependent
8231   // context.
8232   if (PrimaryTemplate->getDeclContext()->isDependentContext())
8233     return false;
8234 
8235   TemplateParameterList *TemplateParams =
8236       PrimaryTemplate->getTemplateParameters();
8237   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8238     NonTypeTemplateParmDecl *Param
8239       = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8240     if (!Param)
8241       continue;
8242 
8243     if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8244                                                       Param, &TemplateArgs[I],
8245                                                       1, I >= NumExplicit))
8246       return true;
8247   }
8248 
8249   return false;
8250 }
8251 
8252 DeclResult Sema::ActOnClassTemplateSpecialization(
8253     Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8254     SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8255     TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8256     MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8257   assert(TUK != TagUseKind::Reference && "References are not specializations");
8258 
8259   SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8260   SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8261   SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8262 
8263   // Find the class template we're specializing
8264   TemplateName Name = TemplateId.Template.get();
8265   ClassTemplateDecl *ClassTemplate
8266     = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8267 
8268   if (!ClassTemplate) {
8269     Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8270       << (Name.getAsTemplateDecl() &&
8271           isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8272     return true;
8273   }
8274 
8275   if (S->isTemplateParamScope())
8276     EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8277 
8278   DeclContext *DC = ClassTemplate->getDeclContext();
8279 
8280   bool isMemberSpecialization = false;
8281   bool isPartialSpecialization = false;
8282 
8283   if (SS.isSet()) {
8284     if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8285         diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8286                                      TemplateNameLoc, &TemplateId,
8287                                      /*IsMemberSpecialization=*/false))
8288       return true;
8289   }
8290 
8291   // Check the validity of the template headers that introduce this
8292   // template.
8293   // FIXME: We probably shouldn't complain about these headers for
8294   // friend declarations.
8295   bool Invalid = false;
8296   TemplateParameterList *TemplateParams =
8297       MatchTemplateParametersToScopeSpecifier(
8298           KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8299           TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8300   if (Invalid)
8301     return true;
8302 
8303   // Check that we can declare a template specialization here.
8304   if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8305     return true;
8306 
8307   if (TemplateParams && DC->isDependentContext()) {
8308     ContextRAII SavedContext(*this, DC);
8309     if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8310       return true;
8311   }
8312 
8313   if (TemplateParams && TemplateParams->size() > 0) {
8314     isPartialSpecialization = true;
8315 
8316     if (TUK == TagUseKind::Friend) {
8317       Diag(KWLoc, diag::err_partial_specialization_friend)
8318         << SourceRange(LAngleLoc, RAngleLoc);
8319       return true;
8320     }
8321 
8322     // C++ [temp.class.spec]p10:
8323     //   The template parameter list of a specialization shall not
8324     //   contain default template argument values.
8325     for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8326       Decl *Param = TemplateParams->getParam(I);
8327       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8328         if (TTP->hasDefaultArgument()) {
8329           Diag(TTP->getDefaultArgumentLoc(),
8330                diag::err_default_arg_in_partial_spec);
8331           TTP->removeDefaultArgument();
8332         }
8333       } else if (NonTypeTemplateParmDecl *NTTP
8334                    = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8335         if (NTTP->hasDefaultArgument()) {
8336           Diag(NTTP->getDefaultArgumentLoc(),
8337                diag::err_default_arg_in_partial_spec)
8338               << NTTP->getDefaultArgument().getSourceRange();
8339           NTTP->removeDefaultArgument();
8340         }
8341       } else {
8342         TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8343         if (TTP->hasDefaultArgument()) {
8344           Diag(TTP->getDefaultArgument().getLocation(),
8345                diag::err_default_arg_in_partial_spec)
8346             << TTP->getDefaultArgument().getSourceRange();
8347           TTP->removeDefaultArgument();
8348         }
8349       }
8350     }
8351   } else if (TemplateParams) {
8352     if (TUK == TagUseKind::Friend)
8353       Diag(KWLoc, diag::err_template_spec_friend)
8354         << FixItHint::CreateRemoval(
8355                                 SourceRange(TemplateParams->getTemplateLoc(),
8356                                             TemplateParams->getRAngleLoc()))
8357         << SourceRange(LAngleLoc, RAngleLoc);
8358   } else {
8359     assert(TUK == TagUseKind::Friend &&
8360            "should have a 'template<>' for this decl");
8361   }
8362 
8363   // Check that the specialization uses the same tag kind as the
8364   // original template.
8365   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8366   assert(Kind != TagTypeKind::Enum &&
8367          "Invalid enum tag in class template spec!");
8368   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8369                                     TUK == TagUseKind::Definition, KWLoc,
8370                                     ClassTemplate->getIdentifier())) {
8371     Diag(KWLoc, diag::err_use_with_wrong_tag)
8372       << ClassTemplate
8373       << FixItHint::CreateReplacement(KWLoc,
8374                             ClassTemplate->getTemplatedDecl()->getKindName());
8375     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8376          diag::note_previous_use);
8377     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8378   }
8379 
8380   // Translate the parser's template argument list in our AST format.
8381   TemplateArgumentListInfo TemplateArgs =
8382       makeTemplateArgumentListInfo(*this, TemplateId);
8383 
8384   // Check for unexpanded parameter packs in any of the template arguments.
8385   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8386     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8387                                         isPartialSpecialization
8388                                             ? UPPC_PartialSpecialization
8389                                             : UPPC_ExplicitSpecialization))
8390       return true;
8391 
8392   // Check that the template argument list is well-formed for this
8393   // template.
8394   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
8395   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8396                                 /*DefaultArgs=*/{},
8397                                 /*PartialTemplateArgs=*/false, SugaredConverted,
8398                                 CanonicalConverted,
8399                                 /*UpdateArgsWithConversions=*/true))
8400     return true;
8401 
8402   // Find the class template (partial) specialization declaration that
8403   // corresponds to these arguments.
8404   if (isPartialSpecialization) {
8405     if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
8406                                                TemplateArgs.size(),
8407                                                CanonicalConverted))
8408       return true;
8409 
8410     // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8411     // also do it during instantiation.
8412     if (!Name.isDependent() &&
8413         !TemplateSpecializationType::anyDependentTemplateArguments(
8414             TemplateArgs, CanonicalConverted)) {
8415       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8416         << ClassTemplate->getDeclName();
8417       isPartialSpecialization = false;
8418       Invalid = true;
8419     }
8420   }
8421 
8422   void *InsertPos = nullptr;
8423   ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8424 
8425   if (isPartialSpecialization)
8426     PrevDecl = ClassTemplate->findPartialSpecialization(
8427         CanonicalConverted, TemplateParams, InsertPos);
8428   else
8429     PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
8430 
8431   ClassTemplateSpecializationDecl *Specialization = nullptr;
8432 
8433   // Check whether we can declare a class template specialization in
8434   // the current scope.
8435   if (TUK != TagUseKind::Friend &&
8436       CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
8437                                        TemplateNameLoc,
8438                                        isPartialSpecialization))
8439     return true;
8440 
8441   // The canonical type
8442   QualType CanonType;
8443   if (isPartialSpecialization) {
8444     // Build the canonical type that describes the converted template
8445     // arguments of the class template partial specialization.
8446     TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8447     CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8448                                                       CanonicalConverted);
8449 
8450     if (Context.hasSameType(CanonType,
8451                         ClassTemplate->getInjectedClassNameSpecialization()) &&
8452         (!Context.getLangOpts().CPlusPlus20 ||
8453          !TemplateParams->hasAssociatedConstraints())) {
8454       // C++ [temp.class.spec]p9b3:
8455       //
8456       //   -- The argument list of the specialization shall not be identical
8457       //      to the implicit argument list of the primary template.
8458       //
8459       // This rule has since been removed, because it's redundant given DR1495,
8460       // but we keep it because it produces better diagnostics and recovery.
8461       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8462           << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8463           << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8464       return CheckClassTemplate(
8465           S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
8466           TemplateNameLoc, Attr, TemplateParams, AS_none,
8467           /*ModulePrivateLoc=*/SourceLocation(),
8468           /*FriendLoc*/ SourceLocation(), TemplateParameterLists.drop_back(),
8469           isMemberSpecialization);
8470     }
8471 
8472     // Create a new class template partial specialization declaration node.
8473     ClassTemplatePartialSpecializationDecl *PrevPartial
8474       = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8475     ClassTemplatePartialSpecializationDecl *Partial =
8476         ClassTemplatePartialSpecializationDecl::Create(
8477             Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
8478             ClassTemplate, CanonicalConverted, CanonType, PrevPartial);
8479 
8480     // If we are providing an explicit specialization of a member class
8481     // template specialization, make a note of that.
8482     if (isMemberSpecialization)
8483       Partial->setMemberSpecialization();
8484     Partial->setTemplateArgsAsWritten(TemplateArgs);
8485     SetNestedNameSpecifier(*this, Partial, SS);
8486     if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8487       Partial->setTemplateParameterListsInfo(
8488           Context, TemplateParameterLists.drop_back(1));
8489     }
8490 
8491     if (!PrevPartial)
8492       ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8493     Specialization = Partial;
8494 
8495     CheckTemplatePartialSpecialization(Partial);
8496   } else {
8497     // Create a new class template specialization declaration node for
8498     // this explicit specialization or friend declaration.
8499     Specialization = ClassTemplateSpecializationDecl::Create(
8500         Context, Kind, DC, KWLoc, TemplateNameLoc, ClassTemplate,
8501         CanonicalConverted, PrevDecl);
8502     Specialization->setTemplateArgsAsWritten(TemplateArgs);
8503     SetNestedNameSpecifier(*this, Specialization, SS);
8504     if (TemplateParameterLists.size() > 0) {
8505       Specialization->setTemplateParameterListsInfo(Context,
8506                                                     TemplateParameterLists);
8507     }
8508 
8509     if (!PrevDecl)
8510       ClassTemplate->AddSpecialization(Specialization, InsertPos);
8511 
8512     if (CurContext->isDependentContext()) {
8513       TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8514       CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8515                                                         CanonicalConverted);
8516     } else {
8517       CanonType = Context.getTypeDeclType(Specialization);
8518     }
8519   }
8520 
8521   // C++ [temp.expl.spec]p6:
8522   //   If a template, a member template or the member of a class template is
8523   //   explicitly specialized then that specialization shall be declared
8524   //   before the first use of that specialization that would cause an implicit
8525   //   instantiation to take place, in every translation unit in which such a
8526   //   use occurs; no diagnostic is required.
8527   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8528     bool Okay = false;
8529     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8530       // Is there any previous explicit specialization declaration?
8531       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8532         Okay = true;
8533         break;
8534       }
8535     }
8536 
8537     if (!Okay) {
8538       SourceRange Range(TemplateNameLoc, RAngleLoc);
8539       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8540         << Context.getTypeDeclType(Specialization) << Range;
8541 
8542       Diag(PrevDecl->getPointOfInstantiation(),
8543            diag::note_instantiation_required_here)
8544         << (PrevDecl->getTemplateSpecializationKind()
8545                                                 != TSK_ImplicitInstantiation);
8546       return true;
8547     }
8548   }
8549 
8550   // If this is not a friend, note that this is an explicit specialization.
8551   if (TUK != TagUseKind::Friend)
8552     Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8553 
8554   // Check that this isn't a redefinition of this specialization.
8555   if (TUK == TagUseKind::Definition) {
8556     RecordDecl *Def = Specialization->getDefinition();
8557     NamedDecl *Hidden = nullptr;
8558     if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8559       SkipBody->ShouldSkip = true;
8560       SkipBody->Previous = Def;
8561       makeMergedDefinitionVisible(Hidden);
8562     } else if (Def) {
8563       SourceRange Range(TemplateNameLoc, RAngleLoc);
8564       Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8565       Diag(Def->getLocation(), diag::note_previous_definition);
8566       Specialization->setInvalidDecl();
8567       return true;
8568     }
8569   }
8570 
8571   ProcessDeclAttributeList(S, Specialization, Attr);
8572   ProcessAPINotes(Specialization);
8573 
8574   // Add alignment attributes if necessary; these attributes are checked when
8575   // the ASTContext lays out the structure.
8576   if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8577     AddAlignmentAttributesForRecord(Specialization);
8578     AddMsStructLayoutForRecord(Specialization);
8579   }
8580 
8581   if (ModulePrivateLoc.isValid())
8582     Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8583       << (isPartialSpecialization? 1 : 0)
8584       << FixItHint::CreateRemoval(ModulePrivateLoc);
8585 
8586   // C++ [temp.expl.spec]p9:
8587   //   A template explicit specialization is in the scope of the
8588   //   namespace in which the template was defined.
8589   //
8590   // We actually implement this paragraph where we set the semantic
8591   // context (in the creation of the ClassTemplateSpecializationDecl),
8592   // but we also maintain the lexical context where the actual
8593   // definition occurs.
8594   Specialization->setLexicalDeclContext(CurContext);
8595 
8596   // We may be starting the definition of this specialization.
8597   if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
8598     Specialization->startDefinition();
8599 
8600   if (TUK == TagUseKind::Friend) {
8601     // Build the fully-sugared type for this class template
8602     // specialization as the user wrote in the specialization
8603     // itself. This means that we'll pretty-print the type retrieved
8604     // from the specialization's declaration the way that the user
8605     // actually wrote the specialization, rather than formatting the
8606     // name based on the "canonical" representation used to store the
8607     // template arguments in the specialization.
8608     TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
8609         Name, TemplateNameLoc, TemplateArgs, CanonType);
8610     FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
8611                                             TemplateNameLoc,
8612                                             WrittenTy,
8613                                             /*FIXME:*/KWLoc);
8614     Friend->setAccess(AS_public);
8615     CurContext->addDecl(Friend);
8616   } else {
8617     // Add the specialization into its lexical context, so that it can
8618     // be seen when iterating through the list of declarations in that
8619     // context. However, specializations are not found by name lookup.
8620     CurContext->addDecl(Specialization);
8621   }
8622 
8623   if (SkipBody && SkipBody->ShouldSkip)
8624     return SkipBody->Previous;
8625 
8626   Specialization->setInvalidDecl(Invalid);
8627   inferGslOwnerPointerAttribute(Specialization);
8628   return Specialization;
8629 }
8630 
8631 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
8632                               MultiTemplateParamsArg TemplateParameterLists,
8633                                     Declarator &D) {
8634   Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8635   ActOnDocumentableDecl(NewDecl);
8636   return NewDecl;
8637 }
8638 
8639 ConceptDecl *Sema::ActOnStartConceptDefinition(
8640     Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8641     const IdentifierInfo *Name, SourceLocation NameLoc) {
8642   DeclContext *DC = CurContext;
8643 
8644   if (!DC->getRedeclContext()->isFileContext()) {
8645     Diag(NameLoc,
8646       diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8647     return nullptr;
8648   }
8649 
8650   if (TemplateParameterLists.size() > 1) {
8651     Diag(NameLoc, diag::err_concept_extra_headers);
8652     return nullptr;
8653   }
8654 
8655   TemplateParameterList *Params = TemplateParameterLists.front();
8656 
8657   if (Params->size() == 0) {
8658     Diag(NameLoc, diag::err_concept_no_parameters);
8659     return nullptr;
8660   }
8661 
8662   // Ensure that the parameter pack, if present, is the last parameter in the
8663   // template.
8664   for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
8665                                              ParamEnd = Params->end();
8666        ParamIt != ParamEnd; ++ParamIt) {
8667     Decl const *Param = *ParamIt;
8668     if (Param->isParameterPack()) {
8669       if (++ParamIt == ParamEnd)
8670         break;
8671       Diag(Param->getLocation(),
8672            diag::err_template_param_pack_must_be_last_template_parameter);
8673       return nullptr;
8674     }
8675   }
8676 
8677   ConceptDecl *NewDecl =
8678       ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
8679 
8680   if (NewDecl->hasAssociatedConstraints()) {
8681     // C++2a [temp.concept]p4:
8682     // A concept shall not have associated constraints.
8683     Diag(NameLoc, diag::err_concept_no_associated_constraints);
8684     NewDecl->setInvalidDecl();
8685   }
8686 
8687   DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
8688   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8689                         forRedeclarationInCurContext());
8690   LookupName(Previous, S);
8691   FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8692                        /*AllowInlineNamespace*/ false);
8693 
8694   // We cannot properly handle redeclarations until we parse the constraint
8695   // expression, so only inject the name if we are sure we are not redeclaring a
8696   // symbol
8697   if (Previous.empty())
8698     PushOnScopeChains(NewDecl, S, true);
8699 
8700   return NewDecl;
8701 }
8702 
8703 static bool RemoveLookupResult(LookupResult &R, NamedDecl *C) {
8704   bool Found = false;
8705   LookupResult::Filter F = R.makeFilter();
8706   while (F.hasNext()) {
8707     NamedDecl *D = F.next();
8708     if (D == C) {
8709       F.erase();
8710       Found = true;
8711       break;
8712     }
8713   }
8714   F.done();
8715   return Found;
8716 }
8717 
8718 ConceptDecl *
8719 Sema::ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
8720                                    Expr *ConstraintExpr,
8721                                    const ParsedAttributesView &Attrs) {
8722   assert(!C->hasDefinition() && "Concept already defined");
8723   if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
8724     return nullptr;
8725   C->setDefinition(ConstraintExpr);
8726   ProcessDeclAttributeList(S, C, Attrs);
8727 
8728   // Check for conflicting previous declaration.
8729   DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
8730   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8731                         forRedeclarationInCurContext());
8732   LookupName(Previous, S);
8733   FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8734                        /*AllowInlineNamespace*/ false);
8735   bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
8736   bool AddToScope = true;
8737   CheckConceptRedefinition(C, Previous, AddToScope);
8738 
8739   ActOnDocumentableDecl(C);
8740   if (!WasAlreadyAdded && AddToScope)
8741     PushOnScopeChains(C, S);
8742 
8743   return C;
8744 }
8745 
8746 void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
8747                                     LookupResult &Previous, bool &AddToScope) {
8748   AddToScope = true;
8749 
8750   if (Previous.empty())
8751     return;
8752 
8753   auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
8754   if (!OldConcept) {
8755     auto *Old = Previous.getRepresentativeDecl();
8756     Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
8757         << NewDecl->getDeclName();
8758     notePreviousDefinition(Old, NewDecl->getLocation());
8759     AddToScope = false;
8760     return;
8761   }
8762   // Check if we can merge with a concept declaration.
8763   bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
8764   if (!IsSame) {
8765     Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
8766         << NewDecl->getDeclName();
8767     notePreviousDefinition(OldConcept, NewDecl->getLocation());
8768     AddToScope = false;
8769     return;
8770   }
8771   if (hasReachableDefinition(OldConcept) &&
8772       IsRedefinitionInModule(NewDecl, OldConcept)) {
8773     Diag(NewDecl->getLocation(), diag::err_redefinition)
8774         << NewDecl->getDeclName();
8775     notePreviousDefinition(OldConcept, NewDecl->getLocation());
8776     AddToScope = false;
8777     return;
8778   }
8779   if (!Previous.isSingleResult()) {
8780     // FIXME: we should produce an error in case of ambig and failed lookups.
8781     //        Other decls (e.g. namespaces) also have this shortcoming.
8782     return;
8783   }
8784   // We unwrap canonical decl late to check for module visibility.
8785   Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
8786 }
8787 
8788 bool Sema::CheckConceptUseInDefinition(ConceptDecl *Concept,
8789                                        SourceLocation Loc) {
8790   if (!Concept->isInvalidDecl() && !Concept->hasDefinition()) {
8791     Diag(Loc, diag::err_recursive_concept) << Concept;
8792     Diag(Concept->getLocation(), diag::note_declared_at);
8793     return true;
8794   }
8795   return false;
8796 }
8797 
8798 /// \brief Strips various properties off an implicit instantiation
8799 /// that has just been explicitly specialized.
8800 static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
8801   if (MinGW || (isa<FunctionDecl>(D) &&
8802                 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
8803     D->dropAttrs<DLLImportAttr, DLLExportAttr>();
8804 
8805   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8806     FD->setInlineSpecified(false);
8807 }
8808 
8809 /// Compute the diagnostic location for an explicit instantiation
8810 //  declaration or definition.
8811 static SourceLocation DiagLocForExplicitInstantiation(
8812     NamedDecl* D, SourceLocation PointOfInstantiation) {
8813   // Explicit instantiations following a specialization have no effect and
8814   // hence no PointOfInstantiation. In that case, walk decl backwards
8815   // until a valid name loc is found.
8816   SourceLocation PrevDiagLoc = PointOfInstantiation;
8817   for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8818        Prev = Prev->getPreviousDecl()) {
8819     PrevDiagLoc = Prev->getLocation();
8820   }
8821   assert(PrevDiagLoc.isValid() &&
8822          "Explicit instantiation without point of instantiation?");
8823   return PrevDiagLoc;
8824 }
8825 
8826 bool
8827 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
8828                                              TemplateSpecializationKind NewTSK,
8829                                              NamedDecl *PrevDecl,
8830                                              TemplateSpecializationKind PrevTSK,
8831                                         SourceLocation PrevPointOfInstantiation,
8832                                              bool &HasNoEffect) {
8833   HasNoEffect = false;
8834 
8835   switch (NewTSK) {
8836   case TSK_Undeclared:
8837   case TSK_ImplicitInstantiation:
8838     assert(
8839         (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8840         "previous declaration must be implicit!");
8841     return false;
8842 
8843   case TSK_ExplicitSpecialization:
8844     switch (PrevTSK) {
8845     case TSK_Undeclared:
8846     case TSK_ExplicitSpecialization:
8847       // Okay, we're just specializing something that is either already
8848       // explicitly specialized or has merely been mentioned without any
8849       // instantiation.
8850       return false;
8851 
8852     case TSK_ImplicitInstantiation:
8853       if (PrevPointOfInstantiation.isInvalid()) {
8854         // The declaration itself has not actually been instantiated, so it is
8855         // still okay to specialize it.
8856         StripImplicitInstantiation(
8857             PrevDecl,
8858             Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
8859         return false;
8860       }
8861       // Fall through
8862       [[fallthrough]];
8863 
8864     case TSK_ExplicitInstantiationDeclaration:
8865     case TSK_ExplicitInstantiationDefinition:
8866       assert((PrevTSK == TSK_ImplicitInstantiation ||
8867               PrevPointOfInstantiation.isValid()) &&
8868              "Explicit instantiation without point of instantiation?");
8869 
8870       // C++ [temp.expl.spec]p6:
8871       //   If a template, a member template or the member of a class template
8872       //   is explicitly specialized then that specialization shall be declared
8873       //   before the first use of that specialization that would cause an
8874       //   implicit instantiation to take place, in every translation unit in
8875       //   which such a use occurs; no diagnostic is required.
8876       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8877         // Is there any previous explicit specialization declaration?
8878         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
8879           return false;
8880       }
8881 
8882       Diag(NewLoc, diag::err_specialization_after_instantiation)
8883         << PrevDecl;
8884       Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
8885         << (PrevTSK != TSK_ImplicitInstantiation);
8886 
8887       return true;
8888     }
8889     llvm_unreachable("The switch over PrevTSK must be exhaustive.");
8890 
8891   case TSK_ExplicitInstantiationDeclaration:
8892     switch (PrevTSK) {
8893     case TSK_ExplicitInstantiationDeclaration:
8894       // This explicit instantiation declaration is redundant (that's okay).
8895       HasNoEffect = true;
8896       return false;
8897 
8898     case TSK_Undeclared:
8899     case TSK_ImplicitInstantiation:
8900       // We're explicitly instantiating something that may have already been
8901       // implicitly instantiated; that's fine.
8902       return false;
8903 
8904     case TSK_ExplicitSpecialization:
8905       // C++0x [temp.explicit]p4:
8906       //   For a given set of template parameters, if an explicit instantiation
8907       //   of a template appears after a declaration of an explicit
8908       //   specialization for that template, the explicit instantiation has no
8909       //   effect.
8910       HasNoEffect = true;
8911       return false;
8912 
8913     case TSK_ExplicitInstantiationDefinition:
8914       // C++0x [temp.explicit]p10:
8915       //   If an entity is the subject of both an explicit instantiation
8916       //   declaration and an explicit instantiation definition in the same
8917       //   translation unit, the definition shall follow the declaration.
8918       Diag(NewLoc,
8919            diag::err_explicit_instantiation_declaration_after_definition);
8920 
8921       // Explicit instantiations following a specialization have no effect and
8922       // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8923       // until a valid name loc is found.
8924       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8925            diag::note_explicit_instantiation_definition_here);
8926       HasNoEffect = true;
8927       return false;
8928     }
8929     llvm_unreachable("Unexpected TemplateSpecializationKind!");
8930 
8931   case TSK_ExplicitInstantiationDefinition:
8932     switch (PrevTSK) {
8933     case TSK_Undeclared:
8934     case TSK_ImplicitInstantiation:
8935       // We're explicitly instantiating something that may have already been
8936       // implicitly instantiated; that's fine.
8937       return false;
8938 
8939     case TSK_ExplicitSpecialization:
8940       // C++ DR 259, C++0x [temp.explicit]p4:
8941       //   For a given set of template parameters, if an explicit
8942       //   instantiation of a template appears after a declaration of
8943       //   an explicit specialization for that template, the explicit
8944       //   instantiation has no effect.
8945       Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
8946         << PrevDecl;
8947       Diag(PrevDecl->getLocation(),
8948            diag::note_previous_template_specialization);
8949       HasNoEffect = true;
8950       return false;
8951 
8952     case TSK_ExplicitInstantiationDeclaration:
8953       // We're explicitly instantiating a definition for something for which we
8954       // were previously asked to suppress instantiations. That's fine.
8955 
8956       // C++0x [temp.explicit]p4:
8957       //   For a given set of template parameters, if an explicit instantiation
8958       //   of a template appears after a declaration of an explicit
8959       //   specialization for that template, the explicit instantiation has no
8960       //   effect.
8961       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8962         // Is there any previous explicit specialization declaration?
8963         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8964           HasNoEffect = true;
8965           break;
8966         }
8967       }
8968 
8969       return false;
8970 
8971     case TSK_ExplicitInstantiationDefinition:
8972       // C++0x [temp.spec]p5:
8973       //   For a given template and a given set of template-arguments,
8974       //     - an explicit instantiation definition shall appear at most once
8975       //       in a program,
8976 
8977       // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8978       Diag(NewLoc, (getLangOpts().MSVCCompat)
8979                        ? diag::ext_explicit_instantiation_duplicate
8980                        : diag::err_explicit_instantiation_duplicate)
8981           << PrevDecl;
8982       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8983            diag::note_previous_explicit_instantiation);
8984       HasNoEffect = true;
8985       return false;
8986     }
8987   }
8988 
8989   llvm_unreachable("Missing specialization/instantiation case?");
8990 }
8991 
8992 bool Sema::CheckDependentFunctionTemplateSpecialization(
8993     FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
8994     LookupResult &Previous) {
8995   // Remove anything from Previous that isn't a function template in
8996   // the correct context.
8997   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8998   LookupResult::Filter F = Previous.makeFilter();
8999   enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9000   SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9001   while (F.hasNext()) {
9002     NamedDecl *D = F.next()->getUnderlyingDecl();
9003     if (!isa<FunctionTemplateDecl>(D)) {
9004       F.erase();
9005       DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9006       continue;
9007     }
9008 
9009     if (!FDLookupContext->InEnclosingNamespaceSetOf(
9010             D->getDeclContext()->getRedeclContext())) {
9011       F.erase();
9012       DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9013       continue;
9014     }
9015   }
9016   F.done();
9017 
9018   bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9019   if (Previous.empty()) {
9020     Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9021         << IsFriend;
9022     for (auto &P : DiscardedCandidates)
9023       Diag(P.second->getLocation(),
9024            diag::note_dependent_function_template_spec_discard_reason)
9025           << P.first << IsFriend;
9026     return true;
9027   }
9028 
9029   FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
9030                                          ExplicitTemplateArgs);
9031   return false;
9032 }
9033 
9034 bool Sema::CheckFunctionTemplateSpecialization(
9035     FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9036     LookupResult &Previous, bool QualifiedFriend) {
9037   // The set of function template specializations that could match this
9038   // explicit function template specialization.
9039   UnresolvedSet<8> Candidates;
9040   TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9041                                             /*ForTakingAddress=*/false);
9042 
9043   llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9044       ConvertedTemplateArgs;
9045 
9046   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9047   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9048          I != E; ++I) {
9049     NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9050     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9051       // Only consider templates found within the same semantic lookup scope as
9052       // FD.
9053       if (!FDLookupContext->InEnclosingNamespaceSetOf(
9054                                 Ovl->getDeclContext()->getRedeclContext()))
9055         continue;
9056 
9057       QualType FT = FD->getType();
9058       // C++11 [dcl.constexpr]p8:
9059       //   A constexpr specifier for a non-static member function that is not
9060       //   a constructor declares that member function to be const.
9061       //
9062       // When matching a constexpr member function template specialization
9063       // against the primary template, we don't yet know whether the
9064       // specialization has an implicit 'const' (because we don't know whether
9065       // it will be a static member function until we know which template it
9066       // specializes). This rule was removed in C++14.
9067       if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9068           !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9069           !isa<CXXConstructorDecl, CXXDestructorDecl>(NewMD)) {
9070         auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9071         if (OldMD && OldMD->isConst()) {
9072           const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9073           FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9074           EPI.TypeQuals.addConst();
9075           FT = Context.getFunctionType(FPT->getReturnType(),
9076                                        FPT->getParamTypes(), EPI);
9077         }
9078       }
9079 
9080       TemplateArgumentListInfo Args;
9081       if (ExplicitTemplateArgs)
9082         Args = *ExplicitTemplateArgs;
9083 
9084       // C++ [temp.expl.spec]p11:
9085       //   A trailing template-argument can be left unspecified in the
9086       //   template-id naming an explicit function template specialization
9087       //   provided it can be deduced from the function argument type.
9088       // Perform template argument deduction to determine whether we may be
9089       // specializing this template.
9090       // FIXME: It is somewhat wasteful to build
9091       TemplateDeductionInfo Info(FailedCandidates.getLocation());
9092       FunctionDecl *Specialization = nullptr;
9093       if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9094               cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9095               ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9096           TDK != TemplateDeductionResult::Success) {
9097         // Template argument deduction failed; record why it failed, so
9098         // that we can provide nifty diagnostics.
9099         FailedCandidates.addCandidate().set(
9100             I.getPair(), FunTmpl->getTemplatedDecl(),
9101             MakeDeductionFailureInfo(Context, TDK, Info));
9102         (void)TDK;
9103         continue;
9104       }
9105 
9106       // Target attributes are part of the cuda function signature, so
9107       // the deduced template's cuda target must match that of the
9108       // specialization.  Given that C++ template deduction does not
9109       // take target attributes into account, we reject candidates
9110       // here that have a different target.
9111       if (LangOpts.CUDA &&
9112           CUDA().IdentifyTarget(Specialization,
9113                                 /* IgnoreImplicitHDAttr = */ true) !=
9114               CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9115         FailedCandidates.addCandidate().set(
9116             I.getPair(), FunTmpl->getTemplatedDecl(),
9117             MakeDeductionFailureInfo(
9118                 Context, TemplateDeductionResult::CUDATargetMismatch, Info));
9119         continue;
9120       }
9121 
9122       // Record this candidate.
9123       if (ExplicitTemplateArgs)
9124         ConvertedTemplateArgs[Specialization] = std::move(Args);
9125       Candidates.addDecl(Specialization, I.getAccess());
9126     }
9127   }
9128 
9129   // For a qualified friend declaration (with no explicit marker to indicate
9130   // that a template specialization was intended), note all (template and
9131   // non-template) candidates.
9132   if (QualifiedFriend && Candidates.empty()) {
9133     Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9134         << FD->getDeclName() << FDLookupContext;
9135     // FIXME: We should form a single candidate list and diagnose all
9136     // candidates at once, to get proper sorting and limiting.
9137     for (auto *OldND : Previous) {
9138       if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9139         NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9140     }
9141     FailedCandidates.NoteCandidates(*this, FD->getLocation());
9142     return true;
9143   }
9144 
9145   // Find the most specialized function template.
9146   UnresolvedSetIterator Result = getMostSpecialized(
9147       Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9148       PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9149       PDiag(diag::err_function_template_spec_ambiguous)
9150           << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9151       PDiag(diag::note_function_template_spec_matched));
9152 
9153   if (Result == Candidates.end())
9154     return true;
9155 
9156   // Ignore access information;  it doesn't figure into redeclaration checking.
9157   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
9158 
9159   // C++23 [except.spec]p13:
9160   //   An exception specification is considered to be needed when:
9161   //   - [...]
9162   //   - the exception specification is compared to that of another declaration
9163   //     (e.g., an explicit specialization or an overriding virtual function);
9164   //   - [...]
9165   //
9166   //  The exception specification of a defaulted function is evaluated as
9167   //  described above only when needed; similarly, the noexcept-specifier of a
9168   //  specialization of a function template or member function of a class
9169   //  template is instantiated only when needed.
9170   //
9171   // The standard doesn't specify what the "comparison with another declaration"
9172   // entails, nor the exact circumstances in which it occurs. Moreover, it does
9173   // not state which properties of an explicit specialization must match the
9174   // primary template.
9175   //
9176   // We assume that an explicit specialization must correspond with (per
9177   // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9178   // the declaration produced by substitution into the function template.
9179   //
9180   // Since the determination whether two function declarations correspond does
9181   // not consider exception specification, we only need to instantiate it once
9182   // we determine the primary template when comparing types per
9183   // [basic.link]p11.1.
9184   auto *SpecializationFPT =
9185       Specialization->getType()->castAs<FunctionProtoType>();
9186   // If the function has a dependent exception specification, resolve it after
9187   // we have selected the primary template so we can check whether it matches.
9188   if (getLangOpts().CPlusPlus17 &&
9189       isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9190       !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9191     return true;
9192 
9193   FunctionTemplateSpecializationInfo *SpecInfo
9194     = Specialization->getTemplateSpecializationInfo();
9195   assert(SpecInfo && "Function template specialization info missing?");
9196 
9197   // Note: do not overwrite location info if previous template
9198   // specialization kind was explicit.
9199   TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9200   if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9201     Specialization->setLocation(FD->getLocation());
9202     Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9203     // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9204     // function can differ from the template declaration with respect to
9205     // the constexpr specifier.
9206     // FIXME: We need an update record for this AST mutation.
9207     // FIXME: What if there are multiple such prior declarations (for instance,
9208     // from different modules)?
9209     Specialization->setConstexprKind(FD->getConstexprKind());
9210   }
9211 
9212   // FIXME: Check if the prior specialization has a point of instantiation.
9213   // If so, we have run afoul of .
9214 
9215   // If this is a friend declaration, then we're not really declaring
9216   // an explicit specialization.
9217   bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9218 
9219   // Check the scope of this explicit specialization.
9220   if (!isFriend &&
9221       CheckTemplateSpecializationScope(*this,
9222                                        Specialization->getPrimaryTemplate(),
9223                                        Specialization, FD->getLocation(),
9224                                        false))
9225     return true;
9226 
9227   // C++ [temp.expl.spec]p6:
9228   //   If a template, a member template or the member of a class template is
9229   //   explicitly specialized then that specialization shall be declared
9230   //   before the first use of that specialization that would cause an implicit
9231   //   instantiation to take place, in every translation unit in which such a
9232   //   use occurs; no diagnostic is required.
9233   bool HasNoEffect = false;
9234   if (!isFriend &&
9235       CheckSpecializationInstantiationRedecl(FD->getLocation(),
9236                                              TSK_ExplicitSpecialization,
9237                                              Specialization,
9238                                    SpecInfo->getTemplateSpecializationKind(),
9239                                          SpecInfo->getPointOfInstantiation(),
9240                                              HasNoEffect))
9241     return true;
9242 
9243   // Mark the prior declaration as an explicit specialization, so that later
9244   // clients know that this is an explicit specialization.
9245   if (!isFriend) {
9246     // Since explicit specializations do not inherit '=delete' from their
9247     // primary function template - check if the 'specialization' that was
9248     // implicitly generated (during template argument deduction for partial
9249     // ordering) from the most specialized of all the function templates that
9250     // 'FD' could have been specializing, has a 'deleted' definition.  If so,
9251     // first check that it was implicitly generated during template argument
9252     // deduction by making sure it wasn't referenced, and then reset the deleted
9253     // flag to not-deleted, so that we can inherit that information from 'FD'.
9254     if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9255         !Specialization->getCanonicalDecl()->isReferenced()) {
9256       // FIXME: This assert will not hold in the presence of modules.
9257       assert(
9258           Specialization->getCanonicalDecl() == Specialization &&
9259           "This must be the only existing declaration of this specialization");
9260       // FIXME: We need an update record for this AST mutation.
9261       Specialization->setDeletedAsWritten(false);
9262     }
9263     // FIXME: We need an update record for this AST mutation.
9264     SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9265     MarkUnusedFileScopedDecl(Specialization);
9266   }
9267 
9268   // Turn the given function declaration into a function template
9269   // specialization, with the template arguments from the previous
9270   // specialization.
9271   // Take copies of (semantic and syntactic) template argument lists.
9272   TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
9273       Context, Specialization->getTemplateSpecializationArgs()->asArray());
9274   FD->setFunctionTemplateSpecialization(
9275       Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9276       SpecInfo->getTemplateSpecializationKind(),
9277       ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9278 
9279   // A function template specialization inherits the target attributes
9280   // of its template.  (We require the attributes explicitly in the
9281   // code to match, but a template may have implicit attributes by
9282   // virtue e.g. of being constexpr, and it passes these implicit
9283   // attributes on to its specializations.)
9284   if (LangOpts.CUDA)
9285     CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9286 
9287   // The "previous declaration" for this function template specialization is
9288   // the prior function template specialization.
9289   Previous.clear();
9290   Previous.addDecl(Specialization);
9291   return false;
9292 }
9293 
9294 bool
9295 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9296   assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9297          "Only for non-template members");
9298 
9299   // Try to find the member we are instantiating.
9300   NamedDecl *FoundInstantiation = nullptr;
9301   NamedDecl *Instantiation = nullptr;
9302   NamedDecl *InstantiatedFrom = nullptr;
9303   MemberSpecializationInfo *MSInfo = nullptr;
9304 
9305   if (Previous.empty()) {
9306     // Nowhere to look anyway.
9307   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9308     UnresolvedSet<8> Candidates;
9309     for (NamedDecl *Candidate : Previous) {
9310       auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9311       // Ignore any candidates that aren't member functions.
9312       if (!Method)
9313         continue;
9314 
9315       QualType Adjusted = Function->getType();
9316       if (!hasExplicitCallingConv(Adjusted))
9317         Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9318       // Ignore any candidates with the wrong type.
9319       // This doesn't handle deduced return types, but both function
9320       // declarations should be undeduced at this point.
9321       // FIXME: The exception specification should probably be ignored when
9322       // comparing the types.
9323       if (!Context.hasSameType(Adjusted, Method->getType()))
9324         continue;
9325 
9326       // Ignore any candidates with unsatisfied constraints.
9327       if (ConstraintSatisfaction Satisfaction;
9328           Method->getTrailingRequiresClause() &&
9329           (CheckFunctionConstraints(Method, Satisfaction,
9330                                     /*UsageLoc=*/Member->getLocation(),
9331                                     /*ForOverloadResolution=*/true) ||
9332            !Satisfaction.IsSatisfied))
9333         continue;
9334 
9335       Candidates.addDecl(Candidate);
9336     }
9337 
9338     // If we have no viable candidates left after filtering, we are done.
9339     if (Candidates.empty())
9340       return false;
9341 
9342     // Find the function that is more constrained than every other function it
9343     // has been compared to.
9344     UnresolvedSetIterator Best = Candidates.begin();
9345     CXXMethodDecl *BestMethod = nullptr;
9346     for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9347          I != E; ++I) {
9348       auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9349       if (I == Best ||
9350           getMoreConstrainedFunction(Method, BestMethod) == Method) {
9351         Best = I;
9352         BestMethod = Method;
9353       }
9354     }
9355 
9356     FoundInstantiation = *Best;
9357     Instantiation = BestMethod;
9358     InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9359     MSInfo = BestMethod->getMemberSpecializationInfo();
9360 
9361     // Make sure the best candidate is more constrained than all of the others.
9362     bool Ambiguous = false;
9363     for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9364          I != E; ++I) {
9365       auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9366       if (I != Best &&
9367           getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9368         Ambiguous = true;
9369         break;
9370       }
9371     }
9372 
9373     if (Ambiguous) {
9374       Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9375           << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9376       for (NamedDecl *Candidate : Candidates) {
9377         Candidate = Candidate->getUnderlyingDecl();
9378         Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9379             << Candidate;
9380       }
9381       return true;
9382     }
9383   } else if (isa<VarDecl>(Member)) {
9384     VarDecl *PrevVar;
9385     if (Previous.isSingleResult() &&
9386         (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9387       if (PrevVar->isStaticDataMember()) {
9388         FoundInstantiation = Previous.getRepresentativeDecl();
9389         Instantiation = PrevVar;
9390         InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9391         MSInfo = PrevVar->getMemberSpecializationInfo();
9392       }
9393   } else if (isa<RecordDecl>(Member)) {
9394     CXXRecordDecl *PrevRecord;
9395     if (Previous.isSingleResult() &&
9396         (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9397       FoundInstantiation = Previous.getRepresentativeDecl();
9398       Instantiation = PrevRecord;
9399       InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9400       MSInfo = PrevRecord->getMemberSpecializationInfo();
9401     }
9402   } else if (isa<EnumDecl>(Member)) {
9403     EnumDecl *PrevEnum;
9404     if (Previous.isSingleResult() &&
9405         (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9406       FoundInstantiation = Previous.getRepresentativeDecl();
9407       Instantiation = PrevEnum;
9408       InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9409       MSInfo = PrevEnum->getMemberSpecializationInfo();
9410     }
9411   }
9412 
9413   if (!Instantiation) {
9414     // There is no previous declaration that matches. Since member
9415     // specializations are always out-of-line, the caller will complain about
9416     // this mismatch later.
9417     return false;
9418   }
9419 
9420   // A member specialization in a friend declaration isn't really declaring
9421   // an explicit specialization, just identifying a specific (possibly implicit)
9422   // specialization. Don't change the template specialization kind.
9423   //
9424   // FIXME: Is this really valid? Other compilers reject.
9425   if (Member->getFriendObjectKind() != Decl::FOK_None) {
9426     // Preserve instantiation information.
9427     if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9428       cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9429                                       cast<CXXMethodDecl>(InstantiatedFrom),
9430         cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
9431     } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9432       cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9433                                       cast<CXXRecordDecl>(InstantiatedFrom),
9434         cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
9435     }
9436 
9437     Previous.clear();
9438     Previous.addDecl(FoundInstantiation);
9439     return false;
9440   }
9441 
9442   // Make sure that this is a specialization of a member.
9443   if (!InstantiatedFrom) {
9444     Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9445       << Member;
9446     Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9447     return true;
9448   }
9449 
9450   // C++ [temp.expl.spec]p6:
9451   //   If a template, a member template or the member of a class template is
9452   //   explicitly specialized then that specialization shall be declared
9453   //   before the first use of that specialization that would cause an implicit
9454   //   instantiation to take place, in every translation unit in which such a
9455   //   use occurs; no diagnostic is required.
9456   assert(MSInfo && "Member specialization info missing?");
9457 
9458   bool HasNoEffect = false;
9459   if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
9460                                              TSK_ExplicitSpecialization,
9461                                              Instantiation,
9462                                      MSInfo->getTemplateSpecializationKind(),
9463                                            MSInfo->getPointOfInstantiation(),
9464                                              HasNoEffect))
9465     return true;
9466 
9467   // Check the scope of this explicit specialization.
9468   if (CheckTemplateSpecializationScope(*this,
9469                                        InstantiatedFrom,
9470                                        Instantiation, Member->getLocation(),
9471                                        false))
9472     return true;
9473 
9474   // Note that this member specialization is an "instantiation of" the
9475   // corresponding member of the original template.
9476   if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9477     FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9478     if (InstantiationFunction->getTemplateSpecializationKind() ==
9479           TSK_ImplicitInstantiation) {
9480       // Explicit specializations of member functions of class templates do not
9481       // inherit '=delete' from the member function they are specializing.
9482       if (InstantiationFunction->isDeleted()) {
9483         // FIXME: This assert will not hold in the presence of modules.
9484         assert(InstantiationFunction->getCanonicalDecl() ==
9485                InstantiationFunction);
9486         // FIXME: We need an update record for this AST mutation.
9487         InstantiationFunction->setDeletedAsWritten(false);
9488       }
9489     }
9490 
9491     MemberFunction->setInstantiationOfMemberFunction(
9492         cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9493   } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9494     MemberVar->setInstantiationOfStaticDataMember(
9495         cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9496   } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9497     MemberClass->setInstantiationOfMemberClass(
9498         cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9499   } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9500     MemberEnum->setInstantiationOfMemberEnum(
9501         cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9502   } else {
9503     llvm_unreachable("unknown member specialization kind");
9504   }
9505 
9506   // Save the caller the trouble of having to figure out which declaration
9507   // this specialization matches.
9508   Previous.clear();
9509   Previous.addDecl(FoundInstantiation);
9510   return false;
9511 }
9512 
9513 /// Complete the explicit specialization of a member of a class template by
9514 /// updating the instantiated member to be marked as an explicit specialization.
9515 ///
9516 /// \param OrigD The member declaration instantiated from the template.
9517 /// \param Loc The location of the explicit specialization of the member.
9518 template<typename DeclT>
9519 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9520                                              SourceLocation Loc) {
9521   if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9522     return;
9523 
9524   // FIXME: Inform AST mutation listeners of this AST mutation.
9525   // FIXME: If there are multiple in-class declarations of the member (from
9526   // multiple modules, or a declaration and later definition of a member type),
9527   // should we update all of them?
9528   OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9529   OrigD->setLocation(Loc);
9530 }
9531 
9532 void Sema::CompleteMemberSpecialization(NamedDecl *Member,
9533                                         LookupResult &Previous) {
9534   NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9535   if (Instantiation == Member)
9536     return;
9537 
9538   if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9539     completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9540   else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9541     completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9542   else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9543     completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9544   else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9545     completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9546   else
9547     llvm_unreachable("unknown member specialization kind");
9548 }
9549 
9550 /// Check the scope of an explicit instantiation.
9551 ///
9552 /// \returns true if a serious error occurs, false otherwise.
9553 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
9554                                             SourceLocation InstLoc,
9555                                             bool WasQualifiedName) {
9556   DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
9557   DeclContext *CurContext = S.CurContext->getRedeclContext();
9558 
9559   if (CurContext->isRecord()) {
9560     S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9561       << D;
9562     return true;
9563   }
9564 
9565   // C++11 [temp.explicit]p3:
9566   //   An explicit instantiation shall appear in an enclosing namespace of its
9567   //   template. If the name declared in the explicit instantiation is an
9568   //   unqualified name, the explicit instantiation shall appear in the
9569   //   namespace where its template is declared or, if that namespace is inline
9570   //   (7.3.1), any namespace from its enclosing namespace set.
9571   //
9572   // This is DR275, which we do not retroactively apply to C++98/03.
9573   if (WasQualifiedName) {
9574     if (CurContext->Encloses(OrigContext))
9575       return false;
9576   } else {
9577     if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9578       return false;
9579   }
9580 
9581   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9582     if (WasQualifiedName)
9583       S.Diag(InstLoc,
9584              S.getLangOpts().CPlusPlus11?
9585                diag::err_explicit_instantiation_out_of_scope :
9586                diag::warn_explicit_instantiation_out_of_scope_0x)
9587         << D << NS;
9588     else
9589       S.Diag(InstLoc,
9590              S.getLangOpts().CPlusPlus11?
9591                diag::err_explicit_instantiation_unqualified_wrong_namespace :
9592                diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9593         << D << NS;
9594   } else
9595     S.Diag(InstLoc,
9596            S.getLangOpts().CPlusPlus11?
9597              diag::err_explicit_instantiation_must_be_global :
9598              diag::warn_explicit_instantiation_must_be_global_0x)
9599       << D;
9600   S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9601   return false;
9602 }
9603 
9604 /// Common checks for whether an explicit instantiation of \p D is valid.
9605 static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
9606                                        SourceLocation InstLoc,
9607                                        bool WasQualifiedName,
9608                                        TemplateSpecializationKind TSK) {
9609   // C++ [temp.explicit]p13:
9610   //   An explicit instantiation declaration shall not name a specialization of
9611   //   a template with internal linkage.
9612   if (TSK == TSK_ExplicitInstantiationDeclaration &&
9613       D->getFormalLinkage() == Linkage::Internal) {
9614     S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9615     return true;
9616   }
9617 
9618   // C++11 [temp.explicit]p3: [DR 275]
9619   //   An explicit instantiation shall appear in an enclosing namespace of its
9620   //   template.
9621   if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9622     return true;
9623 
9624   return false;
9625 }
9626 
9627 /// Determine whether the given scope specifier has a template-id in it.
9628 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
9629   if (!SS.isSet())
9630     return false;
9631 
9632   // C++11 [temp.explicit]p3:
9633   //   If the explicit instantiation is for a member function, a member class
9634   //   or a static data member of a class template specialization, the name of
9635   //   the class template specialization in the qualified-id for the member
9636   //   name shall be a simple-template-id.
9637   //
9638   // C++98 has the same restriction, just worded differently.
9639   for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9640        NNS = NNS->getPrefix())
9641     if (const Type *T = NNS->getAsType())
9642       if (isa<TemplateSpecializationType>(T))
9643         return true;
9644 
9645   return false;
9646 }
9647 
9648 /// Make a dllexport or dllimport attr on a class template specialization take
9649 /// effect.
9650 static void dllExportImportClassTemplateSpecialization(
9651     Sema &S, ClassTemplateSpecializationDecl *Def) {
9652   auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
9653   assert(A && "dllExportImportClassTemplateSpecialization called "
9654               "on Def without dllexport or dllimport");
9655 
9656   // We reject explicit instantiations in class scope, so there should
9657   // never be any delayed exported classes to worry about.
9658   assert(S.DelayedDllExportClasses.empty() &&
9659          "delayed exports present at explicit instantiation");
9660   S.checkClassLevelDLLAttribute(Def);
9661 
9662   // Propagate attribute to base class templates.
9663   for (auto &B : Def->bases()) {
9664     if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9665             B.getType()->getAsCXXRecordDecl()))
9666       S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
9667   }
9668 
9669   S.referenceDLLExportedClassMethods();
9670 }
9671 
9672 DeclResult Sema::ActOnExplicitInstantiation(
9673     Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9674     unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9675     TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9676     SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9677     SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9678   // Find the class template we're specializing
9679   TemplateName Name = TemplateD.get();
9680   TemplateDecl *TD = Name.getAsTemplateDecl();
9681   // Check that the specialization uses the same tag kind as the
9682   // original template.
9683   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9684   assert(Kind != TagTypeKind::Enum &&
9685          "Invalid enum tag in class template explicit instantiation!");
9686 
9687   ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
9688 
9689   if (!ClassTemplate) {
9690     NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9691     Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
9692         << TD << NTK << llvm::to_underlying(Kind);
9693     Diag(TD->getLocation(), diag::note_previous_use);
9694     return true;
9695   }
9696 
9697   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9698                                     Kind, /*isDefinition*/false, KWLoc,
9699                                     ClassTemplate->getIdentifier())) {
9700     Diag(KWLoc, diag::err_use_with_wrong_tag)
9701       << ClassTemplate
9702       << FixItHint::CreateReplacement(KWLoc,
9703                             ClassTemplate->getTemplatedDecl()->getKindName());
9704     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9705          diag::note_previous_use);
9706     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9707   }
9708 
9709   // C++0x [temp.explicit]p2:
9710   //   There are two forms of explicit instantiation: an explicit instantiation
9711   //   definition and an explicit instantiation declaration. An explicit
9712   //   instantiation declaration begins with the extern keyword. [...]
9713   TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9714                                        ? TSK_ExplicitInstantiationDefinition
9715                                        : TSK_ExplicitInstantiationDeclaration;
9716 
9717   if (TSK == TSK_ExplicitInstantiationDeclaration &&
9718       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9719     // Check for dllexport class template instantiation declarations,
9720     // except for MinGW mode.
9721     for (const ParsedAttr &AL : Attr) {
9722       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9723         Diag(ExternLoc,
9724              diag::warn_attribute_dllexport_explicit_instantiation_decl);
9725         Diag(AL.getLoc(), diag::note_attribute);
9726         break;
9727       }
9728     }
9729 
9730     if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9731       Diag(ExternLoc,
9732            diag::warn_attribute_dllexport_explicit_instantiation_decl);
9733       Diag(A->getLocation(), diag::note_attribute);
9734     }
9735   }
9736 
9737   // In MSVC mode, dllimported explicit instantiation definitions are treated as
9738   // instantiation declarations for most purposes.
9739   bool DLLImportExplicitInstantiationDef = false;
9740   if (TSK == TSK_ExplicitInstantiationDefinition &&
9741       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9742     // Check for dllimport class template instantiation definitions.
9743     bool DLLImport =
9744         ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9745     for (const ParsedAttr &AL : Attr) {
9746       if (AL.getKind() == ParsedAttr::AT_DLLImport)
9747         DLLImport = true;
9748       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9749         // dllexport trumps dllimport here.
9750         DLLImport = false;
9751         break;
9752       }
9753     }
9754     if (DLLImport) {
9755       TSK = TSK_ExplicitInstantiationDeclaration;
9756       DLLImportExplicitInstantiationDef = true;
9757     }
9758   }
9759 
9760   // Translate the parser's template argument list in our AST format.
9761   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9762   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9763 
9764   // Check that the template argument list is well-formed for this
9765   // template.
9766   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
9767   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
9768                                 /*DefaultArgs=*/{}, false, SugaredConverted,
9769                                 CanonicalConverted,
9770                                 /*UpdateArgsWithConversions=*/true))
9771     return true;
9772 
9773   // Find the class template specialization declaration that
9774   // corresponds to these arguments.
9775   void *InsertPos = nullptr;
9776   ClassTemplateSpecializationDecl *PrevDecl =
9777       ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
9778 
9779   TemplateSpecializationKind PrevDecl_TSK
9780     = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9781 
9782   if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9783       Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9784     // Check for dllexport class template instantiation definitions in MinGW
9785     // mode, if a previous declaration of the instantiation was seen.
9786     for (const ParsedAttr &AL : Attr) {
9787       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9788         Diag(AL.getLoc(),
9789              diag::warn_attribute_dllexport_explicit_instantiation_def);
9790         break;
9791       }
9792     }
9793   }
9794 
9795   if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9796                                  SS.isSet(), TSK))
9797     return true;
9798 
9799   ClassTemplateSpecializationDecl *Specialization = nullptr;
9800 
9801   bool HasNoEffect = false;
9802   if (PrevDecl) {
9803     if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
9804                                                PrevDecl, PrevDecl_TSK,
9805                                             PrevDecl->getPointOfInstantiation(),
9806                                                HasNoEffect))
9807       return PrevDecl;
9808 
9809     // Even though HasNoEffect == true means that this explicit instantiation
9810     // has no effect on semantics, we go on to put its syntax in the AST.
9811 
9812     if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9813         PrevDecl_TSK == TSK_Undeclared) {
9814       // Since the only prior class template specialization with these
9815       // arguments was referenced but not declared, reuse that
9816       // declaration node as our own, updating the source location
9817       // for the template name to reflect our new declaration.
9818       // (Other source locations will be updated later.)
9819       Specialization = PrevDecl;
9820       Specialization->setLocation(TemplateNameLoc);
9821       PrevDecl = nullptr;
9822     }
9823 
9824     if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9825         DLLImportExplicitInstantiationDef) {
9826       // The new specialization might add a dllimport attribute.
9827       HasNoEffect = false;
9828     }
9829   }
9830 
9831   if (!Specialization) {
9832     // Create a new class template specialization declaration node for
9833     // this explicit specialization.
9834     Specialization = ClassTemplateSpecializationDecl::Create(
9835         Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9836         ClassTemplate, CanonicalConverted, PrevDecl);
9837     SetNestedNameSpecifier(*this, Specialization, SS);
9838 
9839     // A MSInheritanceAttr attached to the previous declaration must be
9840     // propagated to the new node prior to instantiation.
9841     if (PrevDecl) {
9842       if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
9843         auto *Clone = A->clone(getASTContext());
9844         Clone->setInherited(true);
9845         Specialization->addAttr(Clone);
9846         Consumer.AssignInheritanceModel(Specialization);
9847       }
9848     }
9849 
9850     if (!HasNoEffect && !PrevDecl) {
9851       // Insert the new specialization.
9852       ClassTemplate->AddSpecialization(Specialization, InsertPos);
9853     }
9854   }
9855 
9856   Specialization->setTemplateArgsAsWritten(TemplateArgs);
9857 
9858   // Set source locations for keywords.
9859   Specialization->setExternKeywordLoc(ExternLoc);
9860   Specialization->setTemplateKeywordLoc(TemplateLoc);
9861   Specialization->setBraceRange(SourceRange());
9862 
9863   bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
9864   ProcessDeclAttributeList(S, Specialization, Attr);
9865   ProcessAPINotes(Specialization);
9866 
9867   // Add the explicit instantiation into its lexical context. However,
9868   // since explicit instantiations are never found by name lookup, we
9869   // just put it into the declaration context directly.
9870   Specialization->setLexicalDeclContext(CurContext);
9871   CurContext->addDecl(Specialization);
9872 
9873   // Syntax is now OK, so return if it has no other effect on semantics.
9874   if (HasNoEffect) {
9875     // Set the template specialization kind.
9876     Specialization->setTemplateSpecializationKind(TSK);
9877     return Specialization;
9878   }
9879 
9880   // C++ [temp.explicit]p3:
9881   //   A definition of a class template or class member template
9882   //   shall be in scope at the point of the explicit instantiation of
9883   //   the class template or class member template.
9884   //
9885   // This check comes when we actually try to perform the
9886   // instantiation.
9887   ClassTemplateSpecializationDecl *Def
9888     = cast_or_null<ClassTemplateSpecializationDecl>(
9889                                               Specialization->getDefinition());
9890   if (!Def)
9891     InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
9892   else if (TSK == TSK_ExplicitInstantiationDefinition) {
9893     MarkVTableUsed(TemplateNameLoc, Specialization, true);
9894     Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9895   }
9896 
9897   // Instantiate the members of this class template specialization.
9898   Def = cast_or_null<ClassTemplateSpecializationDecl>(
9899                                        Specialization->getDefinition());
9900   if (Def) {
9901     TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
9902     // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9903     // TSK_ExplicitInstantiationDefinition
9904     if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
9905         (TSK == TSK_ExplicitInstantiationDefinition ||
9906          DLLImportExplicitInstantiationDef)) {
9907       // FIXME: Need to notify the ASTMutationListener that we did this.
9908       Def->setTemplateSpecializationKind(TSK);
9909 
9910       if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
9911           Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
9912         // An explicit instantiation definition can add a dll attribute to a
9913         // template with a previous instantiation declaration. MinGW doesn't
9914         // allow this.
9915         auto *A = cast<InheritableAttr>(
9916             getDLLAttr(Specialization)->clone(getASTContext()));
9917         A->setInherited(true);
9918         Def->addAttr(A);
9919         dllExportImportClassTemplateSpecialization(*this, Def);
9920       }
9921     }
9922 
9923     // Fix a TSK_ImplicitInstantiation followed by a
9924     // TSK_ExplicitInstantiationDefinition
9925     bool NewlyDLLExported =
9926         !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9927     if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
9928         Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
9929       // An explicit instantiation definition can add a dll attribute to a
9930       // template with a previous implicit instantiation. MinGW doesn't allow
9931       // this. We limit clang to only adding dllexport, to avoid potentially
9932       // strange codegen behavior. For example, if we extend this conditional
9933       // to dllimport, and we have a source file calling a method on an
9934       // implicitly instantiated template class instance and then declaring a
9935       // dllimport explicit instantiation definition for the same template
9936       // class, the codegen for the method call will not respect the dllimport,
9937       // while it will with cl. The Def will already have the DLL attribute,
9938       // since the Def and Specialization will be the same in the case of
9939       // Old_TSK == TSK_ImplicitInstantiation, and we already added the
9940       // attribute to the Specialization; we just need to make it take effect.
9941       assert(Def == Specialization &&
9942              "Def and Specialization should match for implicit instantiation");
9943       dllExportImportClassTemplateSpecialization(*this, Def);
9944     }
9945 
9946     // In MinGW mode, export the template instantiation if the declaration
9947     // was marked dllexport.
9948     if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9949         Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
9950         PrevDecl->hasAttr<DLLExportAttr>()) {
9951       dllExportImportClassTemplateSpecialization(*this, Def);
9952     }
9953 
9954     // Set the template specialization kind. Make sure it is set before
9955     // instantiating the members which will trigger ASTConsumer callbacks.
9956     Specialization->setTemplateSpecializationKind(TSK);
9957     InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
9958   } else {
9959 
9960     // Set the template specialization kind.
9961     Specialization->setTemplateSpecializationKind(TSK);
9962   }
9963 
9964   return Specialization;
9965 }
9966 
9967 DeclResult
9968 Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
9969                                  SourceLocation TemplateLoc, unsigned TagSpec,
9970                                  SourceLocation KWLoc, CXXScopeSpec &SS,
9971                                  IdentifierInfo *Name, SourceLocation NameLoc,
9972                                  const ParsedAttributesView &Attr) {
9973 
9974   bool Owned = false;
9975   bool IsDependent = false;
9976   Decl *TagD =
9977       ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
9978                Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
9979                MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
9980                false, TypeResult(), /*IsTypeSpecifier*/ false,
9981                /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside)
9982           .get();
9983   assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
9984 
9985   if (!TagD)
9986     return true;
9987 
9988   TagDecl *Tag = cast<TagDecl>(TagD);
9989   assert(!Tag->isEnum() && "shouldn't see enumerations here");
9990 
9991   if (Tag->isInvalidDecl())
9992     return true;
9993 
9994   CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
9995   CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
9996   if (!Pattern) {
9997     Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
9998       << Context.getTypeDeclType(Record);
9999     Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10000     return true;
10001   }
10002 
10003   // C++0x [temp.explicit]p2:
10004   //   If the explicit instantiation is for a class or member class, the
10005   //   elaborated-type-specifier in the declaration shall include a
10006   //   simple-template-id.
10007   //
10008   // C++98 has the same restriction, just worded differently.
10009   if (!ScopeSpecifierHasTemplateId(SS))
10010     Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10011       << Record << SS.getRange();
10012 
10013   // C++0x [temp.explicit]p2:
10014   //   There are two forms of explicit instantiation: an explicit instantiation
10015   //   definition and an explicit instantiation declaration. An explicit
10016   //   instantiation declaration begins with the extern keyword. [...]
10017   TemplateSpecializationKind TSK
10018     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10019                            : TSK_ExplicitInstantiationDeclaration;
10020 
10021   CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10022 
10023   // Verify that it is okay to explicitly instantiate here.
10024   CXXRecordDecl *PrevDecl
10025     = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10026   if (!PrevDecl && Record->getDefinition())
10027     PrevDecl = Record;
10028   if (PrevDecl) {
10029     MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10030     bool HasNoEffect = false;
10031     assert(MSInfo && "No member specialization information?");
10032     if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10033                                                PrevDecl,
10034                                         MSInfo->getTemplateSpecializationKind(),
10035                                              MSInfo->getPointOfInstantiation(),
10036                                                HasNoEffect))
10037       return true;
10038     if (HasNoEffect)
10039       return TagD;
10040   }
10041 
10042   CXXRecordDecl *RecordDef
10043     = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10044   if (!RecordDef) {
10045     // C++ [temp.explicit]p3:
10046     //   A definition of a member class of a class template shall be in scope
10047     //   at the point of an explicit instantiation of the member class.
10048     CXXRecordDecl *Def
10049       = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10050     if (!Def) {
10051       Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10052         << 0 << Record->getDeclName() << Record->getDeclContext();
10053       Diag(Pattern->getLocation(), diag::note_forward_declaration)
10054         << Pattern;
10055       return true;
10056     } else {
10057       if (InstantiateClass(NameLoc, Record, Def,
10058                            getTemplateInstantiationArgs(Record),
10059                            TSK))
10060         return true;
10061 
10062       RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10063       if (!RecordDef)
10064         return true;
10065     }
10066   }
10067 
10068   // Instantiate all of the members of the class.
10069   InstantiateClassMembers(NameLoc, RecordDef,
10070                           getTemplateInstantiationArgs(Record), TSK);
10071 
10072   if (TSK == TSK_ExplicitInstantiationDefinition)
10073     MarkVTableUsed(NameLoc, RecordDef, true);
10074 
10075   // FIXME: We don't have any representation for explicit instantiations of
10076   // member classes. Such a representation is not needed for compilation, but it
10077   // should be available for clients that want to see all of the declarations in
10078   // the source code.
10079   return TagD;
10080 }
10081 
10082 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10083                                             SourceLocation ExternLoc,
10084                                             SourceLocation TemplateLoc,
10085                                             Declarator &D) {
10086   // Explicit instantiations always require a name.
10087   // TODO: check if/when DNInfo should replace Name.
10088   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10089   DeclarationName Name = NameInfo.getName();
10090   if (!Name) {
10091     if (!D.isInvalidType())
10092       Diag(D.getDeclSpec().getBeginLoc(),
10093            diag::err_explicit_instantiation_requires_name)
10094           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10095 
10096     return true;
10097   }
10098 
10099   // Get the innermost enclosing declaration scope.
10100   S = S->getDeclParent();
10101 
10102   // Determine the type of the declaration.
10103   TypeSourceInfo *T = GetTypeForDeclarator(D);
10104   QualType R = T->getType();
10105   if (R.isNull())
10106     return true;
10107 
10108   // C++ [dcl.stc]p1:
10109   //   A storage-class-specifier shall not be specified in [...] an explicit
10110   //   instantiation (14.7.2) directive.
10111   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10112     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10113       << Name;
10114     return true;
10115   } else if (D.getDeclSpec().getStorageClassSpec()
10116                                                 != DeclSpec::SCS_unspecified) {
10117     // Complain about then remove the storage class specifier.
10118     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10119       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10120 
10121     D.getMutableDeclSpec().ClearStorageClassSpecs();
10122   }
10123 
10124   // C++0x [temp.explicit]p1:
10125   //   [...] An explicit instantiation of a function template shall not use the
10126   //   inline or constexpr specifiers.
10127   // Presumably, this also applies to member functions of class templates as
10128   // well.
10129   if (D.getDeclSpec().isInlineSpecified())
10130     Diag(D.getDeclSpec().getInlineSpecLoc(),
10131          getLangOpts().CPlusPlus11 ?
10132            diag::err_explicit_instantiation_inline :
10133            diag::warn_explicit_instantiation_inline_0x)
10134       << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10135   if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10136     // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10137     // not already specified.
10138     Diag(D.getDeclSpec().getConstexprSpecLoc(),
10139          diag::err_explicit_instantiation_constexpr);
10140 
10141   // A deduction guide is not on the list of entities that can be explicitly
10142   // instantiated.
10143   if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10144     Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10145         << /*explicit instantiation*/ 0;
10146     return true;
10147   }
10148 
10149   // C++0x [temp.explicit]p2:
10150   //   There are two forms of explicit instantiation: an explicit instantiation
10151   //   definition and an explicit instantiation declaration. An explicit
10152   //   instantiation declaration begins with the extern keyword. [...]
10153   TemplateSpecializationKind TSK
10154     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10155                            : TSK_ExplicitInstantiationDeclaration;
10156 
10157   LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10158   LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
10159                    /*ObjectType=*/QualType());
10160 
10161   if (!R->isFunctionType()) {
10162     // C++ [temp.explicit]p1:
10163     //   A [...] static data member of a class template can be explicitly
10164     //   instantiated from the member definition associated with its class
10165     //   template.
10166     // C++1y [temp.explicit]p1:
10167     //   A [...] variable [...] template specialization can be explicitly
10168     //   instantiated from its template.
10169     if (Previous.isAmbiguous())
10170       return true;
10171 
10172     VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10173     VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10174 
10175     if (!PrevTemplate) {
10176       if (!Prev || !Prev->isStaticDataMember()) {
10177         // We expect to see a static data member here.
10178         Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10179             << Name;
10180         for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10181              P != PEnd; ++P)
10182           Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10183         return true;
10184       }
10185 
10186       if (!Prev->getInstantiatedFromStaticDataMember()) {
10187         // FIXME: Check for explicit specialization?
10188         Diag(D.getIdentifierLoc(),
10189              diag::err_explicit_instantiation_data_member_not_instantiated)
10190             << Prev;
10191         Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10192         // FIXME: Can we provide a note showing where this was declared?
10193         return true;
10194       }
10195     } else {
10196       // Explicitly instantiate a variable template.
10197 
10198       // C++1y [dcl.spec.auto]p6:
10199       //   ... A program that uses auto or decltype(auto) in a context not
10200       //   explicitly allowed in this section is ill-formed.
10201       //
10202       // This includes auto-typed variable template instantiations.
10203       if (R->isUndeducedType()) {
10204         Diag(T->getTypeLoc().getBeginLoc(),
10205              diag::err_auto_not_allowed_var_inst);
10206         return true;
10207       }
10208 
10209       if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10210         // C++1y [temp.explicit]p3:
10211         //   If the explicit instantiation is for a variable, the unqualified-id
10212         //   in the declaration shall be a template-id.
10213         Diag(D.getIdentifierLoc(),
10214              diag::err_explicit_instantiation_without_template_id)
10215           << PrevTemplate;
10216         Diag(PrevTemplate->getLocation(),
10217              diag::note_explicit_instantiation_here);
10218         return true;
10219       }
10220 
10221       // Translate the parser's template argument list into our AST format.
10222       TemplateArgumentListInfo TemplateArgs =
10223           makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10224 
10225       DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
10226                                           D.getIdentifierLoc(), TemplateArgs);
10227       if (Res.isInvalid())
10228         return true;
10229 
10230       if (!Res.isUsable()) {
10231         // We somehow specified dependent template arguments in an explicit
10232         // instantiation. This should probably only happen during error
10233         // recovery.
10234         Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10235         return true;
10236       }
10237 
10238       // Ignore access control bits, we don't need them for redeclaration
10239       // checking.
10240       Prev = cast<VarDecl>(Res.get());
10241     }
10242 
10243     // C++0x [temp.explicit]p2:
10244     //   If the explicit instantiation is for a member function, a member class
10245     //   or a static data member of a class template specialization, the name of
10246     //   the class template specialization in the qualified-id for the member
10247     //   name shall be a simple-template-id.
10248     //
10249     // C++98 has the same restriction, just worded differently.
10250     //
10251     // This does not apply to variable template specializations, where the
10252     // template-id is in the unqualified-id instead.
10253     if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10254       Diag(D.getIdentifierLoc(),
10255            diag::ext_explicit_instantiation_without_qualified_id)
10256         << Prev << D.getCXXScopeSpec().getRange();
10257 
10258     CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10259 
10260     // Verify that it is okay to explicitly instantiate here.
10261     TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10262     SourceLocation POI = Prev->getPointOfInstantiation();
10263     bool HasNoEffect = false;
10264     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
10265                                                PrevTSK, POI, HasNoEffect))
10266       return true;
10267 
10268     if (!HasNoEffect) {
10269       // Instantiate static data member or variable template.
10270       Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10271       if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10272         VTSD->setExternKeywordLoc(ExternLoc);
10273         VTSD->setTemplateKeywordLoc(TemplateLoc);
10274       }
10275 
10276       // Merge attributes.
10277       ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10278       if (PrevTemplate)
10279         ProcessAPINotes(Prev);
10280 
10281       if (TSK == TSK_ExplicitInstantiationDefinition)
10282         InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
10283     }
10284 
10285     // Check the new variable specialization against the parsed input.
10286     if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10287       Diag(T->getTypeLoc().getBeginLoc(),
10288            diag::err_invalid_var_template_spec_type)
10289           << 0 << PrevTemplate << R << Prev->getType();
10290       Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10291           << 2 << PrevTemplate->getDeclName();
10292       return true;
10293     }
10294 
10295     // FIXME: Create an ExplicitInstantiation node?
10296     return (Decl*) nullptr;
10297   }
10298 
10299   // If the declarator is a template-id, translate the parser's template
10300   // argument list into our AST format.
10301   bool HasExplicitTemplateArgs = false;
10302   TemplateArgumentListInfo TemplateArgs;
10303   if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10304     TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10305     HasExplicitTemplateArgs = true;
10306   }
10307 
10308   // C++ [temp.explicit]p1:
10309   //   A [...] function [...] can be explicitly instantiated from its template.
10310   //   A member function [...] of a class template can be explicitly
10311   //  instantiated from the member definition associated with its class
10312   //  template.
10313   UnresolvedSet<8> TemplateMatches;
10314   OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10315                                           OverloadCandidateSet::CSK_Normal);
10316   TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10317   for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10318        P != PEnd; ++P) {
10319     NamedDecl *Prev = *P;
10320     if (!HasExplicitTemplateArgs) {
10321       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10322         QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10323                                                 /*AdjustExceptionSpec*/true);
10324         if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10325           if (Method->getPrimaryTemplate()) {
10326             TemplateMatches.addDecl(Method, P.getAccess());
10327           } else {
10328             OverloadCandidate &C = NonTemplateMatches.addCandidate();
10329             C.FoundDecl = P.getPair();
10330             C.Function = Method;
10331             C.Viable = true;
10332             ConstraintSatisfaction S;
10333             if (Method->getTrailingRequiresClause() &&
10334                 (CheckFunctionConstraints(Method, S, D.getIdentifierLoc(),
10335                                           /*ForOverloadResolution=*/true) ||
10336                  !S.IsSatisfied)) {
10337               C.Viable = false;
10338               C.FailureKind = ovl_fail_constraints_not_satisfied;
10339             }
10340           }
10341         }
10342       }
10343     }
10344 
10345     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10346     if (!FunTmpl)
10347       continue;
10348 
10349     TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10350     FunctionDecl *Specialization = nullptr;
10351     if (TemplateDeductionResult TDK = DeduceTemplateArguments(
10352             FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10353             Specialization, Info);
10354         TDK != TemplateDeductionResult::Success) {
10355       // Keep track of almost-matches.
10356       FailedTemplateCandidates.addCandidate().set(
10357           P.getPair(), FunTmpl->getTemplatedDecl(),
10358           MakeDeductionFailureInfo(Context, TDK, Info));
10359       (void)TDK;
10360       continue;
10361     }
10362 
10363     // Target attributes are part of the cuda function signature, so
10364     // the cuda target of the instantiated function must match that of its
10365     // template.  Given that C++ template deduction does not take
10366     // target attributes into account, we reject candidates here that
10367     // have a different target.
10368     if (LangOpts.CUDA &&
10369         CUDA().IdentifyTarget(Specialization,
10370                               /* IgnoreImplicitHDAttr = */ true) !=
10371             CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10372       FailedTemplateCandidates.addCandidate().set(
10373           P.getPair(), FunTmpl->getTemplatedDecl(),
10374           MakeDeductionFailureInfo(
10375               Context, TemplateDeductionResult::CUDATargetMismatch, Info));
10376       continue;
10377     }
10378 
10379     TemplateMatches.addDecl(Specialization, P.getAccess());
10380   }
10381 
10382   FunctionDecl *Specialization = nullptr;
10383   if (!NonTemplateMatches.empty()) {
10384     unsigned Msg = 0;
10385     OverloadCandidateDisplayKind DisplayKind;
10386     OverloadCandidateSet::iterator Best;
10387     switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
10388                                                   Best)) {
10389     case OR_Success:
10390     case OR_Deleted:
10391       Specialization = cast<FunctionDecl>(Best->Function);
10392       break;
10393     case OR_Ambiguous:
10394       Msg = diag::err_explicit_instantiation_ambiguous;
10395       DisplayKind = OCD_AmbiguousCandidates;
10396       break;
10397     case OR_No_Viable_Function:
10398       Msg = diag::err_explicit_instantiation_no_candidate;
10399       DisplayKind = OCD_AllCandidates;
10400       break;
10401     }
10402     if (Msg) {
10403       PartialDiagnostic Diag = PDiag(Msg) << Name;
10404       NonTemplateMatches.NoteCandidates(
10405           PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
10406           {});
10407       return true;
10408     }
10409   }
10410 
10411   if (!Specialization) {
10412     // Find the most specialized function template specialization.
10413     UnresolvedSetIterator Result = getMostSpecialized(
10414         TemplateMatches.begin(), TemplateMatches.end(),
10415         FailedTemplateCandidates, D.getIdentifierLoc(),
10416         PDiag(diag::err_explicit_instantiation_not_known) << Name,
10417         PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10418         PDiag(diag::note_explicit_instantiation_candidate));
10419 
10420     if (Result == TemplateMatches.end())
10421       return true;
10422 
10423     // Ignore access control bits, we don't need them for redeclaration checking.
10424     Specialization = cast<FunctionDecl>(*Result);
10425   }
10426 
10427   // C++11 [except.spec]p4
10428   // In an explicit instantiation an exception-specification may be specified,
10429   // but is not required.
10430   // If an exception-specification is specified in an explicit instantiation
10431   // directive, it shall be compatible with the exception-specifications of
10432   // other declarations of that function.
10433   if (auto *FPT = R->getAs<FunctionProtoType>())
10434     if (FPT->hasExceptionSpec()) {
10435       unsigned DiagID =
10436           diag::err_mismatched_exception_spec_explicit_instantiation;
10437       if (getLangOpts().MicrosoftExt)
10438         DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10439       bool Result = CheckEquivalentExceptionSpec(
10440           PDiag(DiagID) << Specialization->getType(),
10441           PDiag(diag::note_explicit_instantiation_here),
10442           Specialization->getType()->getAs<FunctionProtoType>(),
10443           Specialization->getLocation(), FPT, D.getBeginLoc());
10444       // In Microsoft mode, mismatching exception specifications just cause a
10445       // warning.
10446       if (!getLangOpts().MicrosoftExt && Result)
10447         return true;
10448     }
10449 
10450   if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10451     Diag(D.getIdentifierLoc(),
10452          diag::err_explicit_instantiation_member_function_not_instantiated)
10453       << Specialization
10454       << (Specialization->getTemplateSpecializationKind() ==
10455           TSK_ExplicitSpecialization);
10456     Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10457     return true;
10458   }
10459 
10460   FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10461   if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10462     PrevDecl = Specialization;
10463 
10464   if (PrevDecl) {
10465     bool HasNoEffect = false;
10466     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10467                                                PrevDecl,
10468                                      PrevDecl->getTemplateSpecializationKind(),
10469                                           PrevDecl->getPointOfInstantiation(),
10470                                                HasNoEffect))
10471       return true;
10472 
10473     // FIXME: We may still want to build some representation of this
10474     // explicit specialization.
10475     if (HasNoEffect)
10476       return (Decl*) nullptr;
10477   }
10478 
10479   // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10480   // functions
10481   //     valarray<size_t>::valarray(size_t) and
10482   //     valarray<size_t>::~valarray()
10483   // that it declared to have internal linkage with the internal_linkage
10484   // attribute. Ignore the explicit instantiation declaration in this case.
10485   if (Specialization->hasAttr<InternalLinkageAttr>() &&
10486       TSK == TSK_ExplicitInstantiationDeclaration) {
10487     if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10488       if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10489           RD->isInStdNamespace())
10490         return (Decl*) nullptr;
10491   }
10492 
10493   ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10494   ProcessAPINotes(Specialization);
10495 
10496   // In MSVC mode, dllimported explicit instantiation definitions are treated as
10497   // instantiation declarations.
10498   if (TSK == TSK_ExplicitInstantiationDefinition &&
10499       Specialization->hasAttr<DLLImportAttr>() &&
10500       Context.getTargetInfo().getCXXABI().isMicrosoft())
10501     TSK = TSK_ExplicitInstantiationDeclaration;
10502 
10503   Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10504 
10505   if (Specialization->isDefined()) {
10506     // Let the ASTConsumer know that this function has been explicitly
10507     // instantiated now, and its linkage might have changed.
10508     Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
10509   } else if (TSK == TSK_ExplicitInstantiationDefinition)
10510     InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10511 
10512   // C++0x [temp.explicit]p2:
10513   //   If the explicit instantiation is for a member function, a member class
10514   //   or a static data member of a class template specialization, the name of
10515   //   the class template specialization in the qualified-id for the member
10516   //   name shall be a simple-template-id.
10517   //
10518   // C++98 has the same restriction, just worded differently.
10519   FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10520   if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10521       D.getCXXScopeSpec().isSet() &&
10522       !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10523     Diag(D.getIdentifierLoc(),
10524          diag::ext_explicit_instantiation_without_qualified_id)
10525     << Specialization << D.getCXXScopeSpec().getRange();
10526 
10527   CheckExplicitInstantiation(
10528       *this,
10529       FunTmpl ? (NamedDecl *)FunTmpl
10530               : Specialization->getInstantiatedFromMemberFunction(),
10531       D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10532 
10533   // FIXME: Create some kind of ExplicitInstantiationDecl here.
10534   return (Decl*) nullptr;
10535 }
10536 
10537 TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10538                                    const CXXScopeSpec &SS,
10539                                    const IdentifierInfo *Name,
10540                                    SourceLocation TagLoc,
10541                                    SourceLocation NameLoc) {
10542   // This has to hold, because SS is expected to be defined.
10543   assert(Name && "Expected a name in a dependent tag");
10544 
10545   NestedNameSpecifier *NNS = SS.getScopeRep();
10546   if (!NNS)
10547     return true;
10548 
10549   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10550 
10551   if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
10552     Diag(NameLoc, diag::err_dependent_tag_decl)
10553         << (TUK == TagUseKind::Definition) << llvm::to_underlying(Kind)
10554         << SS.getRange();
10555     return true;
10556   }
10557 
10558   // Create the resulting type.
10559   ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10560   QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
10561 
10562   // Create type-source location information for this type.
10563   TypeLocBuilder TLB;
10564   DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
10565   TL.setElaboratedKeywordLoc(TagLoc);
10566   TL.setQualifierLoc(SS.getWithLocInContext(Context));
10567   TL.setNameLoc(NameLoc);
10568   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
10569 }
10570 
10571 TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10572                                    const CXXScopeSpec &SS,
10573                                    const IdentifierInfo &II,
10574                                    SourceLocation IdLoc,
10575                                    ImplicitTypenameContext IsImplicitTypename) {
10576   if (SS.isInvalid())
10577     return true;
10578 
10579   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10580     Diag(TypenameLoc,
10581          getLangOpts().CPlusPlus11 ?
10582            diag::warn_cxx98_compat_typename_outside_of_template :
10583            diag::ext_typename_outside_of_template)
10584       << FixItHint::CreateRemoval(TypenameLoc);
10585 
10586   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10587   TypeSourceInfo *TSI = nullptr;
10588   QualType T =
10589       CheckTypenameType((TypenameLoc.isValid() ||
10590                          IsImplicitTypename == ImplicitTypenameContext::Yes)
10591                             ? ElaboratedTypeKeyword::Typename
10592                             : ElaboratedTypeKeyword::None,
10593                         TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
10594                         /*DeducedTSTContext=*/true);
10595   if (T.isNull())
10596     return true;
10597   return CreateParsedType(T, TSI);
10598 }
10599 
10600 TypeResult
10601 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10602                         const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
10603                         TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
10604                         SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
10605                         ASTTemplateArgsPtr TemplateArgsIn,
10606                         SourceLocation RAngleLoc) {
10607   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10608     Diag(TypenameLoc,
10609          getLangOpts().CPlusPlus11 ?
10610            diag::warn_cxx98_compat_typename_outside_of_template :
10611            diag::ext_typename_outside_of_template)
10612       << FixItHint::CreateRemoval(TypenameLoc);
10613 
10614   // Strangely, non-type results are not ignored by this lookup, so the
10615   // program is ill-formed if it finds an injected-class-name.
10616   if (TypenameLoc.isValid()) {
10617     auto *LookupRD =
10618         dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10619     if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10620       Diag(TemplateIILoc,
10621            diag::ext_out_of_line_qualified_id_type_names_constructor)
10622         << TemplateII << 0 /*injected-class-name used as template name*/
10623         << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10624     }
10625   }
10626 
10627   // Translate the parser's template argument list in our AST format.
10628   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10629   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10630 
10631   TemplateName Template = TemplateIn.get();
10632   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10633     // Construct a dependent template specialization type.
10634     assert(DTN && "dependent template has non-dependent name?");
10635     assert(DTN->getQualifier() == SS.getScopeRep());
10636 
10637     if (!DTN->isIdentifier()) {
10638       Diag(TemplateIILoc, diag::err_template_id_not_a_type) << Template;
10639       NoteAllFoundTemplates(Template);
10640       return true;
10641     }
10642 
10643     QualType T = Context.getDependentTemplateSpecializationType(
10644         ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
10645         DTN->getIdentifier(), TemplateArgs.arguments());
10646 
10647     // Create source-location information for this type.
10648     TypeLocBuilder Builder;
10649     DependentTemplateSpecializationTypeLoc SpecTL
10650     = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
10651     SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10652     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
10653     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10654     SpecTL.setTemplateNameLoc(TemplateIILoc);
10655     SpecTL.setLAngleLoc(LAngleLoc);
10656     SpecTL.setRAngleLoc(RAngleLoc);
10657     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10658       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10659     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
10660   }
10661 
10662   QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
10663   if (T.isNull())
10664     return true;
10665 
10666   // Provide source-location information for the template specialization type.
10667   TypeLocBuilder Builder;
10668   TemplateSpecializationTypeLoc SpecTL
10669     = Builder.push<TemplateSpecializationTypeLoc>(T);
10670   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10671   SpecTL.setTemplateNameLoc(TemplateIILoc);
10672   SpecTL.setLAngleLoc(LAngleLoc);
10673   SpecTL.setRAngleLoc(RAngleLoc);
10674   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10675     SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10676 
10677   T = Context.getElaboratedType(ElaboratedTypeKeyword::Typename,
10678                                 SS.getScopeRep(), T);
10679   ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10680   TL.setElaboratedKeywordLoc(TypenameLoc);
10681   TL.setQualifierLoc(SS.getWithLocInContext(Context));
10682 
10683   TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10684   return CreateParsedType(T, TSI);
10685 }
10686 
10687 /// Determine whether this failed name lookup should be treated as being
10688 /// disabled by a usage of std::enable_if.
10689 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
10690                        SourceRange &CondRange, Expr *&Cond) {
10691   // We must be looking for a ::type...
10692   if (!II.isStr("type"))
10693     return false;
10694 
10695   // ... within an explicitly-written template specialization...
10696   if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10697     return false;
10698   TypeLoc EnableIfTy = NNS.getTypeLoc();
10699   TemplateSpecializationTypeLoc EnableIfTSTLoc =
10700       EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
10701   if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10702     return false;
10703   const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10704 
10705   // ... which names a complete class template declaration...
10706   const TemplateDecl *EnableIfDecl =
10707     EnableIfTST->getTemplateName().getAsTemplateDecl();
10708   if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10709     return false;
10710 
10711   // ... called "enable_if".
10712   const IdentifierInfo *EnableIfII =
10713     EnableIfDecl->getDeclName().getAsIdentifierInfo();
10714   if (!EnableIfII || !EnableIfII->isStr("enable_if"))
10715     return false;
10716 
10717   // Assume the first template argument is the condition.
10718   CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
10719 
10720   // Dig out the condition.
10721   Cond = nullptr;
10722   if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
10723         != TemplateArgument::Expression)
10724     return true;
10725 
10726   Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
10727 
10728   // Ignore Boolean literals; they add no value.
10729   if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
10730     Cond = nullptr;
10731 
10732   return true;
10733 }
10734 
10735 QualType
10736 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
10737                         SourceLocation KeywordLoc,
10738                         NestedNameSpecifierLoc QualifierLoc,
10739                         const IdentifierInfo &II,
10740                         SourceLocation IILoc,
10741                         TypeSourceInfo **TSI,
10742                         bool DeducedTSTContext) {
10743   QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
10744                                  DeducedTSTContext);
10745   if (T.isNull())
10746     return QualType();
10747 
10748   *TSI = Context.CreateTypeSourceInfo(T);
10749   if (isa<DependentNameType>(T)) {
10750     DependentNameTypeLoc TL =
10751         (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
10752     TL.setElaboratedKeywordLoc(KeywordLoc);
10753     TL.setQualifierLoc(QualifierLoc);
10754     TL.setNameLoc(IILoc);
10755   } else {
10756     ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
10757     TL.setElaboratedKeywordLoc(KeywordLoc);
10758     TL.setQualifierLoc(QualifierLoc);
10759     TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
10760   }
10761   return T;
10762 }
10763 
10764 /// Build the type that describes a C++ typename specifier,
10765 /// e.g., "typename T::type".
10766 QualType
10767 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
10768                         SourceLocation KeywordLoc,
10769                         NestedNameSpecifierLoc QualifierLoc,
10770                         const IdentifierInfo &II,
10771                         SourceLocation IILoc, bool DeducedTSTContext) {
10772   CXXScopeSpec SS;
10773   SS.Adopt(QualifierLoc);
10774 
10775   DeclContext *Ctx = nullptr;
10776   if (QualifierLoc) {
10777     Ctx = computeDeclContext(SS);
10778     if (!Ctx) {
10779       // If the nested-name-specifier is dependent and couldn't be
10780       // resolved to a type, build a typename type.
10781       assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
10782       return Context.getDependentNameType(Keyword,
10783                                           QualifierLoc.getNestedNameSpecifier(),
10784                                           &II);
10785     }
10786 
10787     // If the nested-name-specifier refers to the current instantiation,
10788     // the "typename" keyword itself is superfluous. In C++03, the
10789     // program is actually ill-formed. However, DR 382 (in C++0x CD1)
10790     // allows such extraneous "typename" keywords, and we retroactively
10791     // apply this DR to C++03 code with only a warning. In any case we continue.
10792 
10793     if (RequireCompleteDeclContext(SS, Ctx))
10794       return QualType();
10795   }
10796 
10797   DeclarationName Name(&II);
10798   LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
10799   if (Ctx)
10800     LookupQualifiedName(Result, Ctx, SS);
10801   else
10802     LookupName(Result, CurScope);
10803   unsigned DiagID = 0;
10804   Decl *Referenced = nullptr;
10805   switch (Result.getResultKind()) {
10806   case LookupResult::NotFound: {
10807     // If we're looking up 'type' within a template named 'enable_if', produce
10808     // a more specific diagnostic.
10809     SourceRange CondRange;
10810     Expr *Cond = nullptr;
10811     if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10812       // If we have a condition, narrow it down to the specific failed
10813       // condition.
10814       if (Cond) {
10815         Expr *FailedCond;
10816         std::string FailedDescription;
10817         std::tie(FailedCond, FailedDescription) =
10818           findFailedBooleanCondition(Cond);
10819 
10820         Diag(FailedCond->getExprLoc(),
10821              diag::err_typename_nested_not_found_requirement)
10822           << FailedDescription
10823           << FailedCond->getSourceRange();
10824         return QualType();
10825       }
10826 
10827       Diag(CondRange.getBegin(),
10828            diag::err_typename_nested_not_found_enable_if)
10829           << Ctx << CondRange;
10830       return QualType();
10831     }
10832 
10833     DiagID = Ctx ? diag::err_typename_nested_not_found
10834                  : diag::err_unknown_typename;
10835     break;
10836   }
10837 
10838   case LookupResult::FoundUnresolvedValue: {
10839     // We found a using declaration that is a value. Most likely, the using
10840     // declaration itself is meant to have the 'typename' keyword.
10841     SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10842                           IILoc);
10843     Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10844       << Name << Ctx << FullRange;
10845     if (UnresolvedUsingValueDecl *Using
10846           = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
10847       SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
10848       Diag(Loc, diag::note_using_value_decl_missing_typename)
10849         << FixItHint::CreateInsertion(Loc, "typename ");
10850     }
10851   }
10852   // Fall through to create a dependent typename type, from which we can recover
10853   // better.
10854   [[fallthrough]];
10855 
10856   case LookupResult::NotFoundInCurrentInstantiation:
10857     // Okay, it's a member of an unknown instantiation.
10858     return Context.getDependentNameType(Keyword,
10859                                         QualifierLoc.getNestedNameSpecifier(),
10860                                         &II);
10861 
10862   case LookupResult::Found:
10863     if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
10864       // C++ [class.qual]p2:
10865       //   In a lookup in which function names are not ignored and the
10866       //   nested-name-specifier nominates a class C, if the name specified
10867       //   after the nested-name-specifier, when looked up in C, is the
10868       //   injected-class-name of C [...] then the name is instead considered
10869       //   to name the constructor of class C.
10870       //
10871       // Unlike in an elaborated-type-specifier, function names are not ignored
10872       // in typename-specifier lookup. However, they are ignored in all the
10873       // contexts where we form a typename type with no keyword (that is, in
10874       // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10875       //
10876       // FIXME: That's not strictly true: mem-initializer-id lookup does not
10877       // ignore functions, but that appears to be an oversight.
10878       auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10879       auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10880       if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
10881           FoundRD->isInjectedClassName() &&
10882           declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10883         Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10884             << &II << 1 << 0 /*'typename' keyword used*/;
10885 
10886       // We found a type. Build an ElaboratedType, since the
10887       // typename-specifier was just sugar.
10888       MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
10889       return Context.getElaboratedType(Keyword,
10890                                        QualifierLoc.getNestedNameSpecifier(),
10891                                        Context.getTypeDeclType(Type));
10892     }
10893 
10894     // C++ [dcl.type.simple]p2:
10895     //   A type-specifier of the form
10896     //     typename[opt] nested-name-specifier[opt] template-name
10897     //   is a placeholder for a deduced class type [...].
10898     if (getLangOpts().CPlusPlus17) {
10899       if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10900         if (!DeducedTSTContext) {
10901           QualType T(QualifierLoc
10902                          ? QualifierLoc.getNestedNameSpecifier()->getAsType()
10903                          : nullptr, 0);
10904           if (!T.isNull())
10905             Diag(IILoc, diag::err_dependent_deduced_tst)
10906               << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T;
10907           else
10908             Diag(IILoc, diag::err_deduced_tst)
10909               << (int)getTemplateNameKindForDiagnostics(TemplateName(TD));
10910           NoteTemplateLocation(*TD);
10911           return QualType();
10912         }
10913         return Context.getElaboratedType(
10914             Keyword, QualifierLoc.getNestedNameSpecifier(),
10915             Context.getDeducedTemplateSpecializationType(TemplateName(TD),
10916                                                          QualType(), false));
10917       }
10918     }
10919 
10920     DiagID = Ctx ? diag::err_typename_nested_not_type
10921                  : diag::err_typename_not_type;
10922     Referenced = Result.getFoundDecl();
10923     break;
10924 
10925   case LookupResult::FoundOverloaded:
10926     DiagID = Ctx ? diag::err_typename_nested_not_type
10927                  : diag::err_typename_not_type;
10928     Referenced = *Result.begin();
10929     break;
10930 
10931   case LookupResult::Ambiguous:
10932     return QualType();
10933   }
10934 
10935   // If we get here, it's because name lookup did not find a
10936   // type. Emit an appropriate diagnostic and return an error.
10937   SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10938                         IILoc);
10939   if (Ctx)
10940     Diag(IILoc, DiagID) << FullRange << Name << Ctx;
10941   else
10942     Diag(IILoc, DiagID) << FullRange << Name;
10943   if (Referenced)
10944     Diag(Referenced->getLocation(),
10945          Ctx ? diag::note_typename_member_refers_here
10946              : diag::note_typename_refers_here)
10947       << Name;
10948   return QualType();
10949 }
10950 
10951 namespace {
10952   // See Sema::RebuildTypeInCurrentInstantiation
10953   class CurrentInstantiationRebuilder
10954     : public TreeTransform<CurrentInstantiationRebuilder> {
10955     SourceLocation Loc;
10956     DeclarationName Entity;
10957 
10958   public:
10959     typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
10960 
10961     CurrentInstantiationRebuilder(Sema &SemaRef,
10962                                   SourceLocation Loc,
10963                                   DeclarationName Entity)
10964     : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
10965       Loc(Loc), Entity(Entity) { }
10966 
10967     /// Determine whether the given type \p T has already been
10968     /// transformed.
10969     ///
10970     /// For the purposes of type reconstruction, a type has already been
10971     /// transformed if it is NULL or if it is not dependent.
10972     bool AlreadyTransformed(QualType T) {
10973       return T.isNull() || !T->isInstantiationDependentType();
10974     }
10975 
10976     /// Returns the location of the entity whose type is being
10977     /// rebuilt.
10978     SourceLocation getBaseLocation() { return Loc; }
10979 
10980     /// Returns the name of the entity whose type is being rebuilt.
10981     DeclarationName getBaseEntity() { return Entity; }
10982 
10983     /// Sets the "base" location and entity when that
10984     /// information is known based on another transformation.
10985     void setBase(SourceLocation Loc, DeclarationName Entity) {
10986       this->Loc = Loc;
10987       this->Entity = Entity;
10988     }
10989 
10990     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10991       // Lambdas never need to be transformed.
10992       return E;
10993     }
10994   };
10995 } // end anonymous namespace
10996 
10997 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
10998                                                         SourceLocation Loc,
10999                                                         DeclarationName Name) {
11000   if (!T || !T->getType()->isInstantiationDependentType())
11001     return T;
11002 
11003   CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11004   return Rebuilder.TransformType(T);
11005 }
11006 
11007 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11008   CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11009                                           DeclarationName());
11010   return Rebuilder.TransformExpr(E);
11011 }
11012 
11013 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11014   if (SS.isInvalid())
11015     return true;
11016 
11017   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11018   CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11019                                           DeclarationName());
11020   NestedNameSpecifierLoc Rebuilt
11021     = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11022   if (!Rebuilt)
11023     return true;
11024 
11025   SS.Adopt(Rebuilt);
11026   return false;
11027 }
11028 
11029 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11030                                                TemplateParameterList *Params) {
11031   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11032     Decl *Param = Params->getParam(I);
11033 
11034     // There is nothing to rebuild in a type parameter.
11035     if (isa<TemplateTypeParmDecl>(Param))
11036       continue;
11037 
11038     // Rebuild the template parameter list of a template template parameter.
11039     if (TemplateTemplateParmDecl *TTP
11040         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11041       if (RebuildTemplateParamsInCurrentInstantiation(
11042             TTP->getTemplateParameters()))
11043         return true;
11044 
11045       continue;
11046     }
11047 
11048     // Rebuild the type of a non-type template parameter.
11049     NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
11050     TypeSourceInfo *NewTSI
11051       = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
11052                                           NTTP->getLocation(),
11053                                           NTTP->getDeclName());
11054     if (!NewTSI)
11055       return true;
11056 
11057     if (NewTSI->getType()->isUndeducedType()) {
11058       // C++17 [temp.dep.expr]p3:
11059       //   An id-expression is type-dependent if it contains
11060       //    - an identifier associated by name lookup with a non-type
11061       //      template-parameter declared with a type that contains a
11062       //      placeholder type (7.1.7.4),
11063       NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11064     }
11065 
11066     if (NewTSI != NTTP->getTypeSourceInfo()) {
11067       NTTP->setTypeSourceInfo(NewTSI);
11068       NTTP->setType(NewTSI->getType());
11069     }
11070   }
11071 
11072   return false;
11073 }
11074 
11075 std::string
11076 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11077                                       const TemplateArgumentList &Args) {
11078   return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11079 }
11080 
11081 std::string
11082 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11083                                       const TemplateArgument *Args,
11084                                       unsigned NumArgs) {
11085   SmallString<128> Str;
11086   llvm::raw_svector_ostream Out(Str);
11087 
11088   if (!Params || Params->size() == 0 || NumArgs == 0)
11089     return std::string();
11090 
11091   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11092     if (I >= NumArgs)
11093       break;
11094 
11095     if (I == 0)
11096       Out << "[with ";
11097     else
11098       Out << ", ";
11099 
11100     if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11101       Out << Id->getName();
11102     } else {
11103       Out << '$' << I;
11104     }
11105 
11106     Out << " = ";
11107     Args[I].print(getPrintingPolicy(), Out,
11108                   TemplateParameterList::shouldIncludeTypeForArgument(
11109                       getPrintingPolicy(), Params, I));
11110   }
11111 
11112   Out << ']';
11113   return std::string(Out.str());
11114 }
11115 
11116 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11117                                     CachedTokens &Toks) {
11118   if (!FD)
11119     return;
11120 
11121   auto LPT = std::make_unique<LateParsedTemplate>();
11122 
11123   // Take tokens to avoid allocations
11124   LPT->Toks.swap(Toks);
11125   LPT->D = FnD;
11126   LPT->FPO = getCurFPFeatures();
11127   LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11128 
11129   FD->setLateTemplateParsed(true);
11130 }
11131 
11132 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11133   if (!FD)
11134     return;
11135   FD->setLateTemplateParsed(false);
11136 }
11137 
11138 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11139   DeclContext *DC = CurContext;
11140 
11141   while (DC) {
11142     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11143       const FunctionDecl *FD = RD->isLocalClass();
11144       return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11145     } else if (DC->isTranslationUnit() || DC->isNamespace())
11146       return false;
11147 
11148     DC = DC->getParent();
11149   }
11150   return false;
11151 }
11152 
11153 namespace {
11154 /// Walk the path from which a declaration was instantiated, and check
11155 /// that every explicit specialization along that path is visible. This enforces
11156 /// C++ [temp.expl.spec]/6:
11157 ///
11158 ///   If a template, a member template or a member of a class template is
11159 ///   explicitly specialized then that specialization shall be declared before
11160 ///   the first use of that specialization that would cause an implicit
11161 ///   instantiation to take place, in every translation unit in which such a
11162 ///   use occurs; no diagnostic is required.
11163 ///
11164 /// and also C++ [temp.class.spec]/1:
11165 ///
11166 ///   A partial specialization shall be declared before the first use of a
11167 ///   class template specialization that would make use of the partial
11168 ///   specialization as the result of an implicit or explicit instantiation
11169 ///   in every translation unit in which such a use occurs; no diagnostic is
11170 ///   required.
11171 class ExplicitSpecializationVisibilityChecker {
11172   Sema &S;
11173   SourceLocation Loc;
11174   llvm::SmallVector<Module *, 8> Modules;
11175   Sema::AcceptableKind Kind;
11176 
11177 public:
11178   ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11179                                           Sema::AcceptableKind Kind)
11180       : S(S), Loc(Loc), Kind(Kind) {}
11181 
11182   void check(NamedDecl *ND) {
11183     if (auto *FD = dyn_cast<FunctionDecl>(ND))
11184       return checkImpl(FD);
11185     if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11186       return checkImpl(RD);
11187     if (auto *VD = dyn_cast<VarDecl>(ND))
11188       return checkImpl(VD);
11189     if (auto *ED = dyn_cast<EnumDecl>(ND))
11190       return checkImpl(ED);
11191   }
11192 
11193 private:
11194   void diagnose(NamedDecl *D, bool IsPartialSpec) {
11195     auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11196                               : Sema::MissingImportKind::ExplicitSpecialization;
11197     const bool Recover = true;
11198 
11199     // If we got a custom set of modules (because only a subset of the
11200     // declarations are interesting), use them, otherwise let
11201     // diagnoseMissingImport intelligently pick some.
11202     if (Modules.empty())
11203       S.diagnoseMissingImport(Loc, D, Kind, Recover);
11204     else
11205       S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11206   }
11207 
11208   bool CheckMemberSpecialization(const NamedDecl *D) {
11209     return Kind == Sema::AcceptableKind::Visible
11210                ? S.hasVisibleMemberSpecialization(D)
11211                : S.hasReachableMemberSpecialization(D);
11212   }
11213 
11214   bool CheckExplicitSpecialization(const NamedDecl *D) {
11215     return Kind == Sema::AcceptableKind::Visible
11216                ? S.hasVisibleExplicitSpecialization(D)
11217                : S.hasReachableExplicitSpecialization(D);
11218   }
11219 
11220   bool CheckDeclaration(const NamedDecl *D) {
11221     return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11222                                                  : S.hasReachableDeclaration(D);
11223   }
11224 
11225   // Check a specific declaration. There are three problematic cases:
11226   //
11227   //  1) The declaration is an explicit specialization of a template
11228   //     specialization.
11229   //  2) The declaration is an explicit specialization of a member of an
11230   //     templated class.
11231   //  3) The declaration is an instantiation of a template, and that template
11232   //     is an explicit specialization of a member of a templated class.
11233   //
11234   // We don't need to go any deeper than that, as the instantiation of the
11235   // surrounding class / etc is not triggered by whatever triggered this
11236   // instantiation, and thus should be checked elsewhere.
11237   template<typename SpecDecl>
11238   void checkImpl(SpecDecl *Spec) {
11239     bool IsHiddenExplicitSpecialization = false;
11240     if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
11241       IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11242                                            ? !CheckMemberSpecialization(Spec)
11243                                            : !CheckExplicitSpecialization(Spec);
11244     } else {
11245       checkInstantiated(Spec);
11246     }
11247 
11248     if (IsHiddenExplicitSpecialization)
11249       diagnose(Spec->getMostRecentDecl(), false);
11250   }
11251 
11252   void checkInstantiated(FunctionDecl *FD) {
11253     if (auto *TD = FD->getPrimaryTemplate())
11254       checkTemplate(TD);
11255   }
11256 
11257   void checkInstantiated(CXXRecordDecl *RD) {
11258     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11259     if (!SD)
11260       return;
11261 
11262     auto From = SD->getSpecializedTemplateOrPartial();
11263     if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11264       checkTemplate(TD);
11265     else if (auto *TD =
11266                  From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11267       if (!CheckDeclaration(TD))
11268         diagnose(TD, true);
11269       checkTemplate(TD);
11270     }
11271   }
11272 
11273   void checkInstantiated(VarDecl *RD) {
11274     auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11275     if (!SD)
11276       return;
11277 
11278     auto From = SD->getSpecializedTemplateOrPartial();
11279     if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11280       checkTemplate(TD);
11281     else if (auto *TD =
11282                  From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11283       if (!CheckDeclaration(TD))
11284         diagnose(TD, true);
11285       checkTemplate(TD);
11286     }
11287   }
11288 
11289   void checkInstantiated(EnumDecl *FD) {}
11290 
11291   template<typename TemplDecl>
11292   void checkTemplate(TemplDecl *TD) {
11293     if (TD->getMostRecentDecl()->isMemberSpecialization()) {
11294       if (!CheckMemberSpecialization(TD->getMostRecentDecl()))
11295         diagnose(TD->getMostRecentDecl(), false);
11296     }
11297   }
11298 };
11299 } // end anonymous namespace
11300 
11301 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11302   if (!getLangOpts().Modules)
11303     return;
11304 
11305   ExplicitSpecializationVisibilityChecker(*this, Loc,
11306                                           Sema::AcceptableKind::Visible)
11307       .check(Spec);
11308 }
11309 
11310 void Sema::checkSpecializationReachability(SourceLocation Loc,
11311                                            NamedDecl *Spec) {
11312   if (!getLangOpts().CPlusPlusModules)
11313     return checkSpecializationVisibility(Loc, Spec);
11314 
11315   ExplicitSpecializationVisibilityChecker(*this, Loc,
11316                                           Sema::AcceptableKind::Reachable)
11317       .check(Spec);
11318 }
11319 
11320 SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
11321   if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11322     return N->getLocation();
11323   if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11324     if (!FD->isFunctionTemplateSpecialization())
11325       return FD->getLocation();
11326   } else if (!isa<ClassTemplateSpecializationDecl,
11327                   VarTemplateSpecializationDecl>(N)) {
11328     return N->getLocation();
11329   }
11330   for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11331     if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11332       continue;
11333     return CSC.PointOfInstantiation;
11334   }
11335   return N->getLocation();
11336 }
11337