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