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