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