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