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