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