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