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