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