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