SemaTemplate.cpp revision 67dd1d4df1b28973e12e0981129b2517d2033b66
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 "Sema.h"
13#include "Lookup.h"
14#include "TreeTransform.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/Parse/DeclSpec.h"
20#include "clang/Parse/Template.h"
21#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "llvm/ADT/StringExtras.h"
24using namespace clang;
25
26/// \brief Determine whether the declaration found is acceptable as the name
27/// of a template and, if so, return that template declaration. Otherwise,
28/// returns NULL.
29static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
30  if (!D)
31    return 0;
32
33  if (isa<TemplateDecl>(D))
34    return D;
35
36  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
37    // C++ [temp.local]p1:
38    //   Like normal (non-template) classes, class templates have an
39    //   injected-class-name (Clause 9). The injected-class-name
40    //   can be used with or without a template-argument-list. When
41    //   it is used without a template-argument-list, it is
42    //   equivalent to the injected-class-name followed by the
43    //   template-parameters of the class template enclosed in
44    //   <>. When it is used with a template-argument-list, it
45    //   refers to the specified class template specialization,
46    //   which could be the current specialization or another
47    //   specialization.
48    if (Record->isInjectedClassName()) {
49      Record = cast<CXXRecordDecl>(Record->getDeclContext());
50      if (Record->getDescribedClassTemplate())
51        return Record->getDescribedClassTemplate();
52
53      if (ClassTemplateSpecializationDecl *Spec
54            = dyn_cast<ClassTemplateSpecializationDecl>(Record))
55        return Spec->getSpecializedTemplate();
56    }
57
58    return 0;
59  }
60
61  return 0;
62}
63
64static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
65  LookupResult::Filter filter = R.makeFilter();
66  while (filter.hasNext()) {
67    NamedDecl *Orig = filter.next();
68    NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
69    if (!Repl)
70      filter.erase();
71    else if (Repl != Orig)
72      filter.replace(Repl);
73  }
74  filter.done();
75}
76
77TemplateNameKind Sema::isTemplateName(Scope *S,
78                                      const CXXScopeSpec &SS,
79                                      UnqualifiedId &Name,
80                                      TypeTy *ObjectTypePtr,
81                                      bool EnteringContext,
82                                      TemplateTy &TemplateResult) {
83  DeclarationName TName;
84
85  switch (Name.getKind()) {
86  case UnqualifiedId::IK_Identifier:
87    TName = DeclarationName(Name.Identifier);
88    break;
89
90  case UnqualifiedId::IK_OperatorFunctionId:
91    TName = Context.DeclarationNames.getCXXOperatorName(
92                                              Name.OperatorFunctionId.Operator);
93    break;
94
95  case UnqualifiedId::IK_LiteralOperatorId:
96    TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
97    break;
98
99  default:
100    return TNK_Non_template;
101  }
102
103  QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
104
105  LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
106                 LookupOrdinaryName);
107  R.suppressDiagnostics();
108  LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
109  if (R.empty())
110    return TNK_Non_template;
111
112  TemplateName Template;
113  TemplateNameKind TemplateKind;
114
115  unsigned ResultCount = R.end() - R.begin();
116  if (ResultCount > 1) {
117    // We assume that we'll preserve the qualifier from a function
118    // template name in other ways.
119    Template = Context.getOverloadedTemplateName(R.begin(), R.end());
120    TemplateKind = TNK_Function_template;
121  } else {
122    TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
123
124    if (SS.isSet() && !SS.isInvalid()) {
125      NestedNameSpecifier *Qualifier
126        = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
127      Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
128    } else {
129      Template = TemplateName(TD);
130    }
131
132    if (isa<FunctionTemplateDecl>(TD))
133      TemplateKind = TNK_Function_template;
134    else {
135      assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
136      TemplateKind = TNK_Type_template;
137    }
138  }
139
140  TemplateResult = TemplateTy::make(Template);
141  return TemplateKind;
142}
143
144void Sema::LookupTemplateName(LookupResult &Found,
145                              Scope *S, const CXXScopeSpec &SS,
146                              QualType ObjectType,
147                              bool EnteringContext) {
148  // Determine where to perform name lookup
149  DeclContext *LookupCtx = 0;
150  bool isDependent = false;
151  if (!ObjectType.isNull()) {
152    // This nested-name-specifier occurs in a member access expression, e.g.,
153    // x->B::f, and we are looking into the type of the object.
154    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
155    LookupCtx = computeDeclContext(ObjectType);
156    isDependent = ObjectType->isDependentType();
157    assert((isDependent || !ObjectType->isIncompleteType()) &&
158           "Caller should have completed object type");
159  } else if (SS.isSet()) {
160    // This nested-name-specifier occurs after another nested-name-specifier,
161    // so long into the context associated with the prior nested-name-specifier.
162    LookupCtx = computeDeclContext(SS, EnteringContext);
163    isDependent = isDependentScopeSpecifier(SS);
164
165    // The declaration context must be complete.
166    if (LookupCtx && RequireCompleteDeclContext(SS))
167      return;
168  }
169
170  bool ObjectTypeSearchedInScope = false;
171  if (LookupCtx) {
172    // Perform "qualified" name lookup into the declaration context we
173    // computed, which is either the type of the base of a member access
174    // expression or the declaration context associated with a prior
175    // nested-name-specifier.
176    LookupQualifiedName(Found, LookupCtx);
177
178    if (!ObjectType.isNull() && Found.empty()) {
179      // C++ [basic.lookup.classref]p1:
180      //   In a class member access expression (5.2.5), if the . or -> token is
181      //   immediately followed by an identifier followed by a <, the
182      //   identifier must be looked up to determine whether the < is the
183      //   beginning of a template argument list (14.2) or a less-than operator.
184      //   The identifier is first looked up in the class of the object
185      //   expression. If the identifier is not found, it is then looked up in
186      //   the context of the entire postfix-expression and shall name a class
187      //   or function template.
188      //
189      // FIXME: When we're instantiating a template, do we actually have to
190      // look in the scope of the template? Seems fishy...
191      if (S) LookupName(Found, S);
192      ObjectTypeSearchedInScope = true;
193    }
194  } else if (isDependent) {
195    // We cannot look into a dependent object type or
196    return;
197  } else {
198    // Perform unqualified name lookup in the current scope.
199    LookupName(Found, S);
200  }
201
202  // FIXME: Cope with ambiguous name-lookup results.
203  assert(!Found.isAmbiguous() &&
204         "Cannot handle template name-lookup ambiguities");
205
206  if (Found.empty()) {
207    // If we did not find any names, attempt to correct any typos.
208    DeclarationName Name = Found.getLookupName();
209    if (CorrectTypo(Found, S, &SS, LookupCtx)) {
210      FilterAcceptableTemplateNames(Context, Found);
211      if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
212        if (LookupCtx)
213          Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
214            << Name << LookupCtx << Found.getLookupName() << SS.getRange()
215            << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
216                                          Found.getLookupName().getAsString());
217        else
218          Diag(Found.getNameLoc(), diag::err_no_template_suggest)
219            << Name << Found.getLookupName()
220            << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
221                                          Found.getLookupName().getAsString());
222        if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
223          Diag(Template->getLocation(), diag::note_previous_decl)
224            << Template->getDeclName();
225      } else
226        Found.clear();
227    } else {
228      Found.clear();
229    }
230  }
231
232  FilterAcceptableTemplateNames(Context, Found);
233  if (Found.empty())
234    return;
235
236  if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
237    // C++ [basic.lookup.classref]p1:
238    //   [...] If the lookup in the class of the object expression finds a
239    //   template, the name is also looked up in the context of the entire
240    //   postfix-expression and [...]
241    //
242    LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
243                            LookupOrdinaryName);
244    LookupName(FoundOuter, S);
245    FilterAcceptableTemplateNames(Context, FoundOuter);
246    // FIXME: Handle ambiguities in this lookup better
247
248    if (FoundOuter.empty()) {
249      //   - if the name is not found, the name found in the class of the
250      //     object expression is used, otherwise
251    } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
252      //   - if the name is found in the context of the entire
253      //     postfix-expression and does not name a class template, the name
254      //     found in the class of the object expression is used, otherwise
255    } else {
256      //   - if the name found is a class template, it must refer to the same
257      //     entity as the one found in the class of the object expression,
258      //     otherwise the program is ill-formed.
259      if (!Found.isSingleResult() ||
260          Found.getFoundDecl()->getCanonicalDecl()
261            != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
262        Diag(Found.getNameLoc(),
263             diag::err_nested_name_member_ref_lookup_ambiguous)
264          << Found.getLookupName();
265        Diag(Found.getRepresentativeDecl()->getLocation(),
266             diag::note_ambig_member_ref_object_type)
267          << ObjectType;
268        Diag(FoundOuter.getFoundDecl()->getLocation(),
269             diag::note_ambig_member_ref_scope);
270
271        // Recover by taking the template that we found in the object
272        // expression's type.
273      }
274    }
275  }
276}
277
278/// ActOnDependentIdExpression - Handle a dependent id-expression that
279/// was just parsed.  This is only possible with an explicit scope
280/// specifier naming a dependent type.
281Sema::OwningExprResult
282Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
283                                 DeclarationName Name,
284                                 SourceLocation NameLoc,
285                                 bool isAddressOfOperand,
286                           const TemplateArgumentListInfo *TemplateArgs) {
287  NestedNameSpecifier *Qualifier
288    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
289
290  if (!isAddressOfOperand &&
291      isa<CXXMethodDecl>(CurContext) &&
292      cast<CXXMethodDecl>(CurContext)->isInstance()) {
293    QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
294
295    // Since the 'this' expression is synthesized, we don't need to
296    // perform the double-lookup check.
297    NamedDecl *FirstQualifierInScope = 0;
298
299    return Owned(CXXDependentScopeMemberExpr::Create(Context,
300                                                     /*This*/ 0, ThisType,
301                                                     /*IsArrow*/ true,
302                                                     /*Op*/ SourceLocation(),
303                                                     Qualifier, SS.getRange(),
304                                                     FirstQualifierInScope,
305                                                     Name, NameLoc,
306                                                     TemplateArgs));
307  }
308
309  return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
310}
311
312Sema::OwningExprResult
313Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
314                                DeclarationName Name,
315                                SourceLocation NameLoc,
316                                const TemplateArgumentListInfo *TemplateArgs) {
317  return Owned(DependentScopeDeclRefExpr::Create(Context,
318               static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
319                                                 SS.getRange(),
320                                                 Name, NameLoc,
321                                                 TemplateArgs));
322}
323
324/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
325/// that the template parameter 'PrevDecl' is being shadowed by a new
326/// declaration at location Loc. Returns true to indicate that this is
327/// an error, and false otherwise.
328bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
329  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
330
331  // Microsoft Visual C++ permits template parameters to be shadowed.
332  if (getLangOptions().Microsoft)
333    return false;
334
335  // C++ [temp.local]p4:
336  //   A template-parameter shall not be redeclared within its
337  //   scope (including nested scopes).
338  Diag(Loc, diag::err_template_param_shadow)
339    << cast<NamedDecl>(PrevDecl)->getDeclName();
340  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
341  return true;
342}
343
344/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
345/// the parameter D to reference the templated declaration and return a pointer
346/// to the template declaration. Otherwise, do nothing to D and return null.
347TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
348  if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
349    D = DeclPtrTy::make(Temp->getTemplatedDecl());
350    return Temp;
351  }
352  return 0;
353}
354
355static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
356                                            const ParsedTemplateArgument &Arg) {
357
358  switch (Arg.getKind()) {
359  case ParsedTemplateArgument::Type: {
360    TypeSourceInfo *DI;
361    QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
362    if (!DI)
363      DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
364    return TemplateArgumentLoc(TemplateArgument(T), DI);
365  }
366
367  case ParsedTemplateArgument::NonType: {
368    Expr *E = static_cast<Expr *>(Arg.getAsExpr());
369    return TemplateArgumentLoc(TemplateArgument(E), E);
370  }
371
372  case ParsedTemplateArgument::Template: {
373    TemplateName Template
374      = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
375    return TemplateArgumentLoc(TemplateArgument(Template),
376                               Arg.getScopeSpec().getRange(),
377                               Arg.getLocation());
378  }
379  }
380
381  llvm_unreachable("Unhandled parsed template argument");
382  return TemplateArgumentLoc();
383}
384
385/// \brief Translates template arguments as provided by the parser
386/// into template arguments used by semantic analysis.
387void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
388                                      TemplateArgumentListInfo &TemplateArgs) {
389 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
390   TemplateArgs.addArgument(translateTemplateArgument(*this,
391                                                      TemplateArgsIn[I]));
392}
393
394/// ActOnTypeParameter - Called when a C++ template type parameter
395/// (e.g., "typename T") has been parsed. Typename specifies whether
396/// the keyword "typename" was used to declare the type parameter
397/// (otherwise, "class" was used), and KeyLoc is the location of the
398/// "class" or "typename" keyword. ParamName is the name of the
399/// parameter (NULL indicates an unnamed template parameter) and
400/// ParamName is the location of the parameter name (if any).
401/// If the type parameter has a default argument, it will be added
402/// later via ActOnTypeParameterDefault.
403Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
404                                         SourceLocation EllipsisLoc,
405                                         SourceLocation KeyLoc,
406                                         IdentifierInfo *ParamName,
407                                         SourceLocation ParamNameLoc,
408                                         unsigned Depth, unsigned Position) {
409  assert(S->isTemplateParamScope() &&
410         "Template type parameter not in template parameter scope!");
411  bool Invalid = false;
412
413  if (ParamName) {
414    NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
415    if (PrevDecl && PrevDecl->isTemplateParameter())
416      Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
417                                                           PrevDecl);
418  }
419
420  SourceLocation Loc = ParamNameLoc;
421  if (!ParamName)
422    Loc = KeyLoc;
423
424  TemplateTypeParmDecl *Param
425    = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
426                                   Depth, Position, ParamName, Typename,
427                                   Ellipsis);
428  if (Invalid)
429    Param->setInvalidDecl();
430
431  if (ParamName) {
432    // Add the template parameter into the current scope.
433    S->AddDecl(DeclPtrTy::make(Param));
434    IdResolver.AddDecl(Param);
435  }
436
437  return DeclPtrTy::make(Param);
438}
439
440/// ActOnTypeParameterDefault - Adds a default argument (the type
441/// Default) to the given template type parameter (TypeParam).
442void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
443                                     SourceLocation EqualLoc,
444                                     SourceLocation DefaultLoc,
445                                     TypeTy *DefaultT) {
446  TemplateTypeParmDecl *Parm
447    = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
448
449  TypeSourceInfo *DefaultTInfo;
450  GetTypeFromParser(DefaultT, &DefaultTInfo);
451
452  assert(DefaultTInfo && "expected source information for type");
453
454  // C++0x [temp.param]p9:
455  // A default template-argument may be specified for any kind of
456  // template-parameter that is not a template parameter pack.
457  if (Parm->isParameterPack()) {
458    Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
459    return;
460  }
461
462  // C++ [temp.param]p14:
463  //   A template-parameter shall not be used in its own default argument.
464  // FIXME: Implement this check! Needs a recursive walk over the types.
465
466  // Check the template argument itself.
467  if (CheckTemplateArgument(Parm, DefaultTInfo)) {
468    Parm->setInvalidDecl();
469    return;
470  }
471
472  Parm->setDefaultArgument(DefaultTInfo, false);
473}
474
475/// \brief Check that the type of a non-type template parameter is
476/// well-formed.
477///
478/// \returns the (possibly-promoted) parameter type if valid;
479/// otherwise, produces a diagnostic and returns a NULL type.
480QualType
481Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
482  // C++ [temp.param]p4:
483  //
484  // A non-type template-parameter shall have one of the following
485  // (optionally cv-qualified) types:
486  //
487  //       -- integral or enumeration type,
488  if (T->isIntegralType() || T->isEnumeralType() ||
489      //   -- pointer to object or pointer to function,
490      (T->isPointerType() &&
491       (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
492        T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
493      //   -- reference to object or reference to function,
494      T->isReferenceType() ||
495      //   -- pointer to member.
496      T->isMemberPointerType() ||
497      // If T is a dependent type, we can't do the check now, so we
498      // assume that it is well-formed.
499      T->isDependentType())
500    return T;
501  // C++ [temp.param]p8:
502  //
503  //   A non-type template-parameter of type "array of T" or
504  //   "function returning T" is adjusted to be of type "pointer to
505  //   T" or "pointer to function returning T", respectively.
506  else if (T->isArrayType())
507    // FIXME: Keep the type prior to promotion?
508    return Context.getArrayDecayedType(T);
509  else if (T->isFunctionType())
510    // FIXME: Keep the type prior to promotion?
511    return Context.getPointerType(T);
512
513  Diag(Loc, diag::err_template_nontype_parm_bad_type)
514    << T;
515
516  return QualType();
517}
518
519/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
520/// template parameter (e.g., "int Size" in "template<int Size>
521/// class Array") has been parsed. S is the current scope and D is
522/// the parsed declarator.
523Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
524                                                    unsigned Depth,
525                                                    unsigned Position) {
526  TypeSourceInfo *TInfo = 0;
527  QualType T = GetTypeForDeclarator(D, S, &TInfo);
528
529  assert(S->isTemplateParamScope() &&
530         "Non-type template parameter not in template parameter scope!");
531  bool Invalid = false;
532
533  IdentifierInfo *ParamName = D.getIdentifier();
534  if (ParamName) {
535    NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
536    if (PrevDecl && PrevDecl->isTemplateParameter())
537      Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
538                                                           PrevDecl);
539  }
540
541  T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
542  if (T.isNull()) {
543    T = Context.IntTy; // Recover with an 'int' type.
544    Invalid = true;
545  }
546
547  NonTypeTemplateParmDecl *Param
548    = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
549                                      Depth, Position, ParamName, T, TInfo);
550  if (Invalid)
551    Param->setInvalidDecl();
552
553  if (D.getIdentifier()) {
554    // Add the template parameter into the current scope.
555    S->AddDecl(DeclPtrTy::make(Param));
556    IdResolver.AddDecl(Param);
557  }
558  return DeclPtrTy::make(Param);
559}
560
561/// \brief Adds a default argument to the given non-type template
562/// parameter.
563void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
564                                                SourceLocation EqualLoc,
565                                                ExprArg DefaultE) {
566  NonTypeTemplateParmDecl *TemplateParm
567    = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
568  Expr *Default = static_cast<Expr *>(DefaultE.get());
569
570  // C++ [temp.param]p14:
571  //   A template-parameter shall not be used in its own default argument.
572  // FIXME: Implement this check! Needs a recursive walk over the types.
573
574  // Check the well-formedness of the default template argument.
575  TemplateArgument Converted;
576  if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
577                            Converted)) {
578    TemplateParm->setInvalidDecl();
579    return;
580  }
581
582  TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
583}
584
585
586/// ActOnTemplateTemplateParameter - Called when a C++ template template
587/// parameter (e.g. T in template <template <typename> class T> class array)
588/// has been parsed. S is the current scope.
589Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
590                                                     SourceLocation TmpLoc,
591                                                     TemplateParamsTy *Params,
592                                                     IdentifierInfo *Name,
593                                                     SourceLocation NameLoc,
594                                                     unsigned Depth,
595                                                     unsigned Position) {
596  assert(S->isTemplateParamScope() &&
597         "Template template parameter not in template parameter scope!");
598
599  // Construct the parameter object.
600  TemplateTemplateParmDecl *Param =
601    TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
602                                     Position, Name,
603                                     (TemplateParameterList*)Params);
604
605  // Make sure the parameter is valid.
606  // FIXME: Decl object is not currently invalidated anywhere so this doesn't
607  // do anything yet. However, if the template parameter list or (eventual)
608  // default value is ever invalidated, that will propagate here.
609  bool Invalid = false;
610  if (Invalid) {
611    Param->setInvalidDecl();
612  }
613
614  // If the tt-param has a name, then link the identifier into the scope
615  // and lookup mechanisms.
616  if (Name) {
617    S->AddDecl(DeclPtrTy::make(Param));
618    IdResolver.AddDecl(Param);
619  }
620
621  return DeclPtrTy::make(Param);
622}
623
624/// \brief Adds a default argument to the given template template
625/// parameter.
626void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
627                                                 SourceLocation EqualLoc,
628                                        const ParsedTemplateArgument &Default) {
629  TemplateTemplateParmDecl *TemplateParm
630    = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
631
632  // C++ [temp.param]p14:
633  //   A template-parameter shall not be used in its own default argument.
634  // FIXME: Implement this check! Needs a recursive walk over the types.
635
636  // Check only that we have a template template argument. We don't want to
637  // try to check well-formedness now, because our template template parameter
638  // might have dependent types in its template parameters, which we wouldn't
639  // be able to match now.
640  //
641  // If none of the template template parameter's template arguments mention
642  // other template parameters, we could actually perform more checking here.
643  // However, it isn't worth doing.
644  TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
645  if (DefaultArg.getArgument().getAsTemplate().isNull()) {
646    Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
647      << DefaultArg.getSourceRange();
648    return;
649  }
650
651  TemplateParm->setDefaultArgument(DefaultArg);
652}
653
654/// ActOnTemplateParameterList - Builds a TemplateParameterList that
655/// contains the template parameters in Params/NumParams.
656Sema::TemplateParamsTy *
657Sema::ActOnTemplateParameterList(unsigned Depth,
658                                 SourceLocation ExportLoc,
659                                 SourceLocation TemplateLoc,
660                                 SourceLocation LAngleLoc,
661                                 DeclPtrTy *Params, unsigned NumParams,
662                                 SourceLocation RAngleLoc) {
663  if (ExportLoc.isValid())
664    Diag(ExportLoc, diag::warn_template_export_unsupported);
665
666  return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
667                                       (NamedDecl**)Params, NumParams,
668                                       RAngleLoc);
669}
670
671Sema::DeclResult
672Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
673                         SourceLocation KWLoc, const CXXScopeSpec &SS,
674                         IdentifierInfo *Name, SourceLocation NameLoc,
675                         AttributeList *Attr,
676                         TemplateParameterList *TemplateParams,
677                         AccessSpecifier AS) {
678  assert(TemplateParams && TemplateParams->size() > 0 &&
679         "No template parameters");
680  assert(TUK != TUK_Reference && "Can only declare or define class templates");
681  bool Invalid = false;
682
683  // Check that we can declare a template here.
684  if (CheckTemplateDeclScope(S, TemplateParams))
685    return true;
686
687  TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
688  assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
689
690  // There is no such thing as an unnamed class template.
691  if (!Name) {
692    Diag(KWLoc, diag::err_template_unnamed_class);
693    return true;
694  }
695
696  // Find any previous declaration with this name.
697  DeclContext *SemanticContext;
698  LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
699                        ForRedeclaration);
700  if (SS.isNotEmpty() && !SS.isInvalid()) {
701    if (RequireCompleteDeclContext(SS))
702      return true;
703
704    SemanticContext = computeDeclContext(SS, true);
705    if (!SemanticContext) {
706      // FIXME: Produce a reasonable diagnostic here
707      return true;
708    }
709
710    LookupQualifiedName(Previous, SemanticContext);
711  } else {
712    SemanticContext = CurContext;
713    LookupName(Previous, S);
714  }
715
716  assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
717  NamedDecl *PrevDecl = 0;
718  if (Previous.begin() != Previous.end())
719    PrevDecl = *Previous.begin();
720
721  // If there is a previous declaration with the same name, check
722  // whether this is a valid redeclaration.
723  ClassTemplateDecl *PrevClassTemplate
724    = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
725
726  // We may have found the injected-class-name of a class template,
727  // class template partial specialization, or class template specialization.
728  // In these cases, grab the template that is being defined or specialized.
729  if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
730      cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
731    PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
732    PrevClassTemplate
733      = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
734    if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
735      PrevClassTemplate
736        = cast<ClassTemplateSpecializationDecl>(PrevDecl)
737            ->getSpecializedTemplate();
738    }
739  }
740
741  if (TUK == TUK_Friend) {
742    // C++ [namespace.memdef]p3:
743    //   [...] When looking for a prior declaration of a class or a function
744    //   declared as a friend, and when the name of the friend class or
745    //   function is neither a qualified name nor a template-id, scopes outside
746    //   the innermost enclosing namespace scope are not considered.
747    DeclContext *OutermostContext = CurContext;
748    while (!OutermostContext->isFileContext())
749      OutermostContext = OutermostContext->getLookupParent();
750
751    if (PrevDecl &&
752        (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
753         OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
754      SemanticContext = PrevDecl->getDeclContext();
755    } else {
756      // Declarations in outer scopes don't matter. However, the outermost
757      // context we computed is the semantic context for our new
758      // declaration.
759      PrevDecl = PrevClassTemplate = 0;
760      SemanticContext = OutermostContext;
761    }
762
763    if (CurContext->isDependentContext()) {
764      // If this is a dependent context, we don't want to link the friend
765      // class template to the template in scope, because that would perform
766      // checking of the template parameter lists that can't be performed
767      // until the outer context is instantiated.
768      PrevDecl = PrevClassTemplate = 0;
769    }
770  } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
771    PrevDecl = PrevClassTemplate = 0;
772
773  if (PrevClassTemplate) {
774    // Ensure that the template parameter lists are compatible.
775    if (!TemplateParameterListsAreEqual(TemplateParams,
776                                   PrevClassTemplate->getTemplateParameters(),
777                                        /*Complain=*/true,
778                                        TPL_TemplateMatch))
779      return true;
780
781    // C++ [temp.class]p4:
782    //   In a redeclaration, partial specialization, explicit
783    //   specialization or explicit instantiation of a class template,
784    //   the class-key shall agree in kind with the original class
785    //   template declaration (7.1.5.3).
786    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
787    if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
788      Diag(KWLoc, diag::err_use_with_wrong_tag)
789        << Name
790        << CodeModificationHint::CreateReplacement(KWLoc,
791                            PrevRecordDecl->getKindName());
792      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
793      Kind = PrevRecordDecl->getTagKind();
794    }
795
796    // Check for redefinition of this class template.
797    if (TUK == TUK_Definition) {
798      if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
799        Diag(NameLoc, diag::err_redefinition) << Name;
800        Diag(Def->getLocation(), diag::note_previous_definition);
801        // FIXME: Would it make sense to try to "forget" the previous
802        // definition, as part of error recovery?
803        return true;
804      }
805    }
806  } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
807    // Maybe we will complain about the shadowed template parameter.
808    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
809    // Just pretend that we didn't see the previous declaration.
810    PrevDecl = 0;
811  } else if (PrevDecl) {
812    // C++ [temp]p5:
813    //   A class template shall not have the same name as any other
814    //   template, class, function, object, enumeration, enumerator,
815    //   namespace, or type in the same scope (3.3), except as specified
816    //   in (14.5.4).
817    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
818    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
819    return true;
820  }
821
822  // Check the template parameter list of this declaration, possibly
823  // merging in the template parameter list from the previous class
824  // template declaration.
825  if (CheckTemplateParameterList(TemplateParams,
826            PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
827                                 TPC_ClassTemplate))
828    Invalid = true;
829
830  // FIXME: If we had a scope specifier, we better have a previous template
831  // declaration!
832
833  CXXRecordDecl *NewClass =
834    CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
835                          PrevClassTemplate?
836                            PrevClassTemplate->getTemplatedDecl() : 0,
837                          /*DelayTypeCreation=*/true);
838
839  ClassTemplateDecl *NewTemplate
840    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
841                                DeclarationName(Name), TemplateParams,
842                                NewClass, PrevClassTemplate);
843  NewClass->setDescribedClassTemplate(NewTemplate);
844
845  // Build the type for the class template declaration now.
846  QualType T =
847    Context.getTypeDeclType(NewClass,
848                            PrevClassTemplate?
849                              PrevClassTemplate->getTemplatedDecl() : 0);
850  assert(T->isDependentType() && "Class template type is not dependent?");
851  (void)T;
852
853  // If we are providing an explicit specialization of a member that is a
854  // class template, make a note of that.
855  if (PrevClassTemplate &&
856      PrevClassTemplate->getInstantiatedFromMemberTemplate())
857    PrevClassTemplate->setMemberSpecialization();
858
859  // Set the access specifier.
860  if (!Invalid && TUK != TUK_Friend)
861    SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
862
863  // Set the lexical context of these templates
864  NewClass->setLexicalDeclContext(CurContext);
865  NewTemplate->setLexicalDeclContext(CurContext);
866
867  if (TUK == TUK_Definition)
868    NewClass->startDefinition();
869
870  if (Attr)
871    ProcessDeclAttributeList(S, NewClass, Attr);
872
873  if (TUK != TUK_Friend)
874    PushOnScopeChains(NewTemplate, S);
875  else {
876    if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
877      NewTemplate->setAccess(PrevClassTemplate->getAccess());
878      NewClass->setAccess(PrevClassTemplate->getAccess());
879    }
880
881    NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
882                                       PrevClassTemplate != NULL);
883
884    // Friend templates are visible in fairly strange ways.
885    if (!CurContext->isDependentContext()) {
886      DeclContext *DC = SemanticContext->getLookupContext();
887      DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
888      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
889        PushOnScopeChains(NewTemplate, EnclosingScope,
890                          /* AddToContext = */ false);
891    }
892
893    FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
894                                            NewClass->getLocation(),
895                                            NewTemplate,
896                                    /*FIXME:*/NewClass->getLocation());
897    Friend->setAccess(AS_public);
898    CurContext->addDecl(Friend);
899  }
900
901  if (Invalid) {
902    NewTemplate->setInvalidDecl();
903    NewClass->setInvalidDecl();
904  }
905  return DeclPtrTy::make(NewTemplate);
906}
907
908/// \brief Diagnose the presence of a default template argument on a
909/// template parameter, which is ill-formed in certain contexts.
910///
911/// \returns true if the default template argument should be dropped.
912static bool DiagnoseDefaultTemplateArgument(Sema &S,
913                                            Sema::TemplateParamListContext TPC,
914                                            SourceLocation ParamLoc,
915                                            SourceRange DefArgRange) {
916  switch (TPC) {
917  case Sema::TPC_ClassTemplate:
918    return false;
919
920  case Sema::TPC_FunctionTemplate:
921    // C++ [temp.param]p9:
922    //   A default template-argument shall not be specified in a
923    //   function template declaration or a function template
924    //   definition [...]
925    // (This sentence is not in C++0x, per DR226).
926    if (!S.getLangOptions().CPlusPlus0x)
927      S.Diag(ParamLoc,
928             diag::err_template_parameter_default_in_function_template)
929        << DefArgRange;
930    return false;
931
932  case Sema::TPC_ClassTemplateMember:
933    // C++0x [temp.param]p9:
934    //   A default template-argument shall not be specified in the
935    //   template-parameter-lists of the definition of a member of a
936    //   class template that appears outside of the member's class.
937    S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
938      << DefArgRange;
939    return true;
940
941  case Sema::TPC_FriendFunctionTemplate:
942    // C++ [temp.param]p9:
943    //   A default template-argument shall not be specified in a
944    //   friend template declaration.
945    S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
946      << DefArgRange;
947    return true;
948
949    // FIXME: C++0x [temp.param]p9 allows default template-arguments
950    // for friend function templates if there is only a single
951    // declaration (and it is a definition). Strange!
952  }
953
954  return false;
955}
956
957/// \brief Checks the validity of a template parameter list, possibly
958/// considering the template parameter list from a previous
959/// declaration.
960///
961/// If an "old" template parameter list is provided, it must be
962/// equivalent (per TemplateParameterListsAreEqual) to the "new"
963/// template parameter list.
964///
965/// \param NewParams Template parameter list for a new template
966/// declaration. This template parameter list will be updated with any
967/// default arguments that are carried through from the previous
968/// template parameter list.
969///
970/// \param OldParams If provided, template parameter list from a
971/// previous declaration of the same template. Default template
972/// arguments will be merged from the old template parameter list to
973/// the new template parameter list.
974///
975/// \param TPC Describes the context in which we are checking the given
976/// template parameter list.
977///
978/// \returns true if an error occurred, false otherwise.
979bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
980                                      TemplateParameterList *OldParams,
981                                      TemplateParamListContext TPC) {
982  bool Invalid = false;
983
984  // C++ [temp.param]p10:
985  //   The set of default template-arguments available for use with a
986  //   template declaration or definition is obtained by merging the
987  //   default arguments from the definition (if in scope) and all
988  //   declarations in scope in the same way default function
989  //   arguments are (8.3.6).
990  bool SawDefaultArgument = false;
991  SourceLocation PreviousDefaultArgLoc;
992
993  bool SawParameterPack = false;
994  SourceLocation ParameterPackLoc;
995
996  // Dummy initialization to avoid warnings.
997  TemplateParameterList::iterator OldParam = NewParams->end();
998  if (OldParams)
999    OldParam = OldParams->begin();
1000
1001  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1002                                    NewParamEnd = NewParams->end();
1003       NewParam != NewParamEnd; ++NewParam) {
1004    // Variables used to diagnose redundant default arguments
1005    bool RedundantDefaultArg = false;
1006    SourceLocation OldDefaultLoc;
1007    SourceLocation NewDefaultLoc;
1008
1009    // Variables used to diagnose missing default arguments
1010    bool MissingDefaultArg = false;
1011
1012    // C++0x [temp.param]p11:
1013    // If a template parameter of a class template is a template parameter pack,
1014    // it must be the last template parameter.
1015    if (SawParameterPack) {
1016      Diag(ParameterPackLoc,
1017           diag::err_template_param_pack_must_be_last_template_parameter);
1018      Invalid = true;
1019    }
1020
1021    if (TemplateTypeParmDecl *NewTypeParm
1022          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1023      // Check the presence of a default argument here.
1024      if (NewTypeParm->hasDefaultArgument() &&
1025          DiagnoseDefaultTemplateArgument(*this, TPC,
1026                                          NewTypeParm->getLocation(),
1027               NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1028                                                       .getFullSourceRange()))
1029        NewTypeParm->removeDefaultArgument();
1030
1031      // Merge default arguments for template type parameters.
1032      TemplateTypeParmDecl *OldTypeParm
1033          = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
1034
1035      if (NewTypeParm->isParameterPack()) {
1036        assert(!NewTypeParm->hasDefaultArgument() &&
1037               "Parameter packs can't have a default argument!");
1038        SawParameterPack = true;
1039        ParameterPackLoc = NewTypeParm->getLocation();
1040      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1041                 NewTypeParm->hasDefaultArgument()) {
1042        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1043        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1044        SawDefaultArgument = true;
1045        RedundantDefaultArg = true;
1046        PreviousDefaultArgLoc = NewDefaultLoc;
1047      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1048        // Merge the default argument from the old declaration to the
1049        // new declaration.
1050        SawDefaultArgument = true;
1051        NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1052                                        true);
1053        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1054      } else if (NewTypeParm->hasDefaultArgument()) {
1055        SawDefaultArgument = true;
1056        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1057      } else if (SawDefaultArgument)
1058        MissingDefaultArg = true;
1059    } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1060               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1061      // Check the presence of a default argument here.
1062      if (NewNonTypeParm->hasDefaultArgument() &&
1063          DiagnoseDefaultTemplateArgument(*this, TPC,
1064                                          NewNonTypeParm->getLocation(),
1065                    NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1066        NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1067        NewNonTypeParm->setDefaultArgument(0);
1068      }
1069
1070      // Merge default arguments for non-type template parameters
1071      NonTypeTemplateParmDecl *OldNonTypeParm
1072        = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
1073      if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1074          NewNonTypeParm->hasDefaultArgument()) {
1075        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1076        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1077        SawDefaultArgument = true;
1078        RedundantDefaultArg = true;
1079        PreviousDefaultArgLoc = NewDefaultLoc;
1080      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1081        // Merge the default argument from the old declaration to the
1082        // new declaration.
1083        SawDefaultArgument = true;
1084        // FIXME: We need to create a new kind of "default argument"
1085        // expression that points to a previous template template
1086        // parameter.
1087        NewNonTypeParm->setDefaultArgument(
1088                                        OldNonTypeParm->getDefaultArgument());
1089        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1090      } else if (NewNonTypeParm->hasDefaultArgument()) {
1091        SawDefaultArgument = true;
1092        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1093      } else if (SawDefaultArgument)
1094        MissingDefaultArg = true;
1095    } else {
1096      // Check the presence of a default argument here.
1097      TemplateTemplateParmDecl *NewTemplateParm
1098        = cast<TemplateTemplateParmDecl>(*NewParam);
1099      if (NewTemplateParm->hasDefaultArgument() &&
1100          DiagnoseDefaultTemplateArgument(*this, TPC,
1101                                          NewTemplateParm->getLocation(),
1102                     NewTemplateParm->getDefaultArgument().getSourceRange()))
1103        NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1104
1105      // Merge default arguments for template template parameters
1106      TemplateTemplateParmDecl *OldTemplateParm
1107        = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
1108      if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1109          NewTemplateParm->hasDefaultArgument()) {
1110        OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1111        NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1112        SawDefaultArgument = true;
1113        RedundantDefaultArg = true;
1114        PreviousDefaultArgLoc = NewDefaultLoc;
1115      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1116        // Merge the default argument from the old declaration to the
1117        // new declaration.
1118        SawDefaultArgument = true;
1119        // FIXME: We need to create a new kind of "default argument" expression
1120        // that points to a previous template template parameter.
1121        NewTemplateParm->setDefaultArgument(
1122                                        OldTemplateParm->getDefaultArgument());
1123        PreviousDefaultArgLoc
1124          = OldTemplateParm->getDefaultArgument().getLocation();
1125      } else if (NewTemplateParm->hasDefaultArgument()) {
1126        SawDefaultArgument = true;
1127        PreviousDefaultArgLoc
1128          = NewTemplateParm->getDefaultArgument().getLocation();
1129      } else if (SawDefaultArgument)
1130        MissingDefaultArg = true;
1131    }
1132
1133    if (RedundantDefaultArg) {
1134      // C++ [temp.param]p12:
1135      //   A template-parameter shall not be given default arguments
1136      //   by two different declarations in the same scope.
1137      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1138      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1139      Invalid = true;
1140    } else if (MissingDefaultArg) {
1141      // C++ [temp.param]p11:
1142      //   If a template-parameter has a default template-argument,
1143      //   all subsequent template-parameters shall have a default
1144      //   template-argument supplied.
1145      Diag((*NewParam)->getLocation(),
1146           diag::err_template_param_default_arg_missing);
1147      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1148      Invalid = true;
1149    }
1150
1151    // If we have an old template parameter list that we're merging
1152    // in, move on to the next parameter.
1153    if (OldParams)
1154      ++OldParam;
1155  }
1156
1157  return Invalid;
1158}
1159
1160/// \brief Match the given template parameter lists to the given scope
1161/// specifier, returning the template parameter list that applies to the
1162/// name.
1163///
1164/// \param DeclStartLoc the start of the declaration that has a scope
1165/// specifier or a template parameter list.
1166///
1167/// \param SS the scope specifier that will be matched to the given template
1168/// parameter lists. This scope specifier precedes a qualified name that is
1169/// being declared.
1170///
1171/// \param ParamLists the template parameter lists, from the outermost to the
1172/// innermost template parameter lists.
1173///
1174/// \param NumParamLists the number of template parameter lists in ParamLists.
1175///
1176/// \param IsExplicitSpecialization will be set true if the entity being
1177/// declared is an explicit specialization, false otherwise.
1178///
1179/// \returns the template parameter list, if any, that corresponds to the
1180/// name that is preceded by the scope specifier @p SS. This template
1181/// parameter list may be have template parameters (if we're declaring a
1182/// template) or may have no template parameters (if we're declaring a
1183/// template specialization), or may be NULL (if we were's declaring isn't
1184/// itself a template).
1185TemplateParameterList *
1186Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1187                                              const CXXScopeSpec &SS,
1188                                          TemplateParameterList **ParamLists,
1189                                              unsigned NumParamLists,
1190                                              bool &IsExplicitSpecialization) {
1191  IsExplicitSpecialization = false;
1192
1193  // Find the template-ids that occur within the nested-name-specifier. These
1194  // template-ids will match up with the template parameter lists.
1195  llvm::SmallVector<const TemplateSpecializationType *, 4>
1196    TemplateIdsInSpecifier;
1197  llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1198    ExplicitSpecializationsInSpecifier;
1199  for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1200       NNS; NNS = NNS->getPrefix()) {
1201    const Type *T = NNS->getAsType();
1202    if (!T) break;
1203
1204    // C++0x [temp.expl.spec]p17:
1205    //   A member or a member template may be nested within many
1206    //   enclosing class templates. In an explicit specialization for
1207    //   such a member, the member declaration shall be preceded by a
1208    //   template<> for each enclosing class template that is
1209    //   explicitly specialized.
1210    // We interpret this as forbidding typedefs of template
1211    // specializations in the scope specifiers of out-of-line decls.
1212    if (const TypedefType *TT = dyn_cast<TypedefType>(T)) {
1213      const Type *UnderlyingT = TT->LookThroughTypedefs().getTypePtr();
1214      if (isa<TemplateSpecializationType>(UnderlyingT))
1215        // FIXME: better source location information.
1216        Diag(DeclStartLoc, diag::err_typedef_in_def_scope) << QualType(T,0);
1217      T = UnderlyingT;
1218    }
1219
1220    if (const TemplateSpecializationType *SpecType
1221          = dyn_cast<TemplateSpecializationType>(T)) {
1222      TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1223      if (!Template)
1224        continue; // FIXME: should this be an error? probably...
1225
1226      if (const RecordType *Record = SpecType->getAs<RecordType>()) {
1227        ClassTemplateSpecializationDecl *SpecDecl
1228          = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1229        // If the nested name specifier refers to an explicit specialization,
1230        // we don't need a template<> header.
1231        if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1232          ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
1233          continue;
1234        }
1235      }
1236
1237      TemplateIdsInSpecifier.push_back(SpecType);
1238    }
1239  }
1240
1241  // Reverse the list of template-ids in the scope specifier, so that we can
1242  // more easily match up the template-ids and the template parameter lists.
1243  std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
1244
1245  SourceLocation FirstTemplateLoc = DeclStartLoc;
1246  if (NumParamLists)
1247    FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
1248
1249  // Match the template-ids found in the specifier to the template parameter
1250  // lists.
1251  unsigned Idx = 0;
1252  for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1253       Idx != NumTemplateIds; ++Idx) {
1254    QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1255    bool DependentTemplateId = TemplateId->isDependentType();
1256    if (Idx >= NumParamLists) {
1257      // We have a template-id without a corresponding template parameter
1258      // list.
1259      if (DependentTemplateId) {
1260        // FIXME: the location information here isn't great.
1261        Diag(SS.getRange().getBegin(),
1262             diag::err_template_spec_needs_template_parameters)
1263          << TemplateId
1264          << SS.getRange();
1265      } else {
1266        Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1267          << SS.getRange()
1268          << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1269                                                   "template<> ");
1270        IsExplicitSpecialization = true;
1271      }
1272      return 0;
1273    }
1274
1275    // Check the template parameter list against its corresponding template-id.
1276    if (DependentTemplateId) {
1277      TemplateDecl *Template
1278        = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1279
1280      if (ClassTemplateDecl *ClassTemplate
1281            = dyn_cast<ClassTemplateDecl>(Template)) {
1282        TemplateParameterList *ExpectedTemplateParams = 0;
1283        // Is this template-id naming the primary template?
1284        if (Context.hasSameType(TemplateId,
1285                             ClassTemplate->getInjectedClassNameType(Context)))
1286          ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1287        // ... or a partial specialization?
1288        else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1289                   = ClassTemplate->findPartialSpecialization(TemplateId))
1290          ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1291
1292        if (ExpectedTemplateParams)
1293          TemplateParameterListsAreEqual(ParamLists[Idx],
1294                                         ExpectedTemplateParams,
1295                                         true, TPL_TemplateMatch);
1296      }
1297
1298      CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
1299    } else if (ParamLists[Idx]->size() > 0)
1300      Diag(ParamLists[Idx]->getTemplateLoc(),
1301           diag::err_template_param_list_matches_nontemplate)
1302        << TemplateId
1303        << ParamLists[Idx]->getSourceRange();
1304    else
1305      IsExplicitSpecialization = true;
1306  }
1307
1308  // If there were at least as many template-ids as there were template
1309  // parameter lists, then there are no template parameter lists remaining for
1310  // the declaration itself.
1311  if (Idx >= NumParamLists)
1312    return 0;
1313
1314  // If there were too many template parameter lists, complain about that now.
1315  if (Idx != NumParamLists - 1) {
1316    while (Idx < NumParamLists - 1) {
1317      bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
1318      Diag(ParamLists[Idx]->getTemplateLoc(),
1319           isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1320                               : diag::err_template_spec_extra_headers)
1321        << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1322                       ParamLists[Idx]->getRAngleLoc());
1323
1324      if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1325        Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1326             diag::note_explicit_template_spec_does_not_need_header)
1327          << ExplicitSpecializationsInSpecifier.back();
1328        ExplicitSpecializationsInSpecifier.pop_back();
1329      }
1330
1331      ++Idx;
1332    }
1333  }
1334
1335  // Return the last template parameter list, which corresponds to the
1336  // entity being declared.
1337  return ParamLists[NumParamLists - 1];
1338}
1339
1340QualType Sema::CheckTemplateIdType(TemplateName Name,
1341                                   SourceLocation TemplateLoc,
1342                              const TemplateArgumentListInfo &TemplateArgs) {
1343  TemplateDecl *Template = Name.getAsTemplateDecl();
1344  if (!Template) {
1345    // The template name does not resolve to a template, so we just
1346    // build a dependent template-id type.
1347    return Context.getTemplateSpecializationType(Name, TemplateArgs);
1348  }
1349
1350  // Check that the template argument list is well-formed for this
1351  // template.
1352  TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1353                                        TemplateArgs.size());
1354  if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
1355                                false, Converted))
1356    return QualType();
1357
1358  assert((Converted.structuredSize() ==
1359            Template->getTemplateParameters()->size()) &&
1360         "Converted template argument list is too short!");
1361
1362  QualType CanonType;
1363
1364  if (Name.isDependent() ||
1365      TemplateSpecializationType::anyDependentTemplateArguments(
1366                                                      TemplateArgs)) {
1367    // This class template specialization is a dependent
1368    // type. Therefore, its canonical type is another class template
1369    // specialization type that contains all of the converted
1370    // arguments in canonical form. This ensures that, e.g., A<T> and
1371    // A<T, T> have identical types when A is declared as:
1372    //
1373    //   template<typename T, typename U = T> struct A;
1374    TemplateName CanonName = Context.getCanonicalTemplateName(Name);
1375    CanonType = Context.getTemplateSpecializationType(CanonName,
1376                                                   Converted.getFlatArguments(),
1377                                                   Converted.flatSize());
1378
1379    // FIXME: CanonType is not actually the canonical type, and unfortunately
1380    // it is a TemplateSpecializationType that we will never use again.
1381    // In the future, we need to teach getTemplateSpecializationType to only
1382    // build the canonical type and return that to us.
1383    CanonType = Context.getCanonicalType(CanonType);
1384  } else if (ClassTemplateDecl *ClassTemplate
1385               = dyn_cast<ClassTemplateDecl>(Template)) {
1386    // Find the class template specialization declaration that
1387    // corresponds to these arguments.
1388    llvm::FoldingSetNodeID ID;
1389    ClassTemplateSpecializationDecl::Profile(ID,
1390                                             Converted.getFlatArguments(),
1391                                             Converted.flatSize(),
1392                                             Context);
1393    void *InsertPos = 0;
1394    ClassTemplateSpecializationDecl *Decl
1395      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1396    if (!Decl) {
1397      // This is the first time we have referenced this class template
1398      // specialization. Create the canonical declaration and add it to
1399      // the set of specializations.
1400      Decl = ClassTemplateSpecializationDecl::Create(Context,
1401                                    ClassTemplate->getDeclContext(),
1402                                    ClassTemplate->getLocation(),
1403                                    ClassTemplate,
1404                                    Converted, 0);
1405      ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1406      Decl->setLexicalDeclContext(CurContext);
1407    }
1408
1409    CanonType = Context.getTypeDeclType(Decl);
1410  }
1411
1412  // Build the fully-sugared type for this class template
1413  // specialization, which refers back to the class template
1414  // specialization we created or found.
1415  return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
1416}
1417
1418Action::TypeResult
1419Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1420                          SourceLocation LAngleLoc,
1421                          ASTTemplateArgsPtr TemplateArgsIn,
1422                          SourceLocation RAngleLoc) {
1423  TemplateName Template = TemplateD.getAsVal<TemplateName>();
1424
1425  // Translate the parser's template argument list in our AST format.
1426  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
1427  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
1428
1429  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
1430  TemplateArgsIn.release();
1431
1432  if (Result.isNull())
1433    return true;
1434
1435  TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
1436  TemplateSpecializationTypeLoc TL
1437    = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1438  TL.setTemplateNameLoc(TemplateLoc);
1439  TL.setLAngleLoc(LAngleLoc);
1440  TL.setRAngleLoc(RAngleLoc);
1441  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1442    TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1443
1444  return CreateLocInfoType(Result, DI).getAsOpaquePtr();
1445}
1446
1447Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1448                                              TagUseKind TUK,
1449                                              DeclSpec::TST TagSpec,
1450                                              SourceLocation TagLoc) {
1451  if (TypeResult.isInvalid())
1452    return Sema::TypeResult();
1453
1454  // FIXME: preserve source info, ideally without copying the DI.
1455  TypeSourceInfo *DI;
1456  QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
1457
1458  // Verify the tag specifier.
1459  TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
1460
1461  if (const RecordType *RT = Type->getAs<RecordType>()) {
1462    RecordDecl *D = RT->getDecl();
1463
1464    IdentifierInfo *Id = D->getIdentifier();
1465    assert(Id && "templated class must have an identifier");
1466
1467    if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1468      Diag(TagLoc, diag::err_use_with_wrong_tag)
1469        << Type
1470        << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1471                                                   D->getKindName());
1472      Diag(D->getLocation(), diag::note_previous_use);
1473    }
1474  }
1475
1476  QualType ElabType = Context.getElaboratedType(Type, TagKind);
1477
1478  return ElabType.getAsOpaquePtr();
1479}
1480
1481Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1482                                                 LookupResult &R,
1483                                                 bool RequiresADL,
1484                                 const TemplateArgumentListInfo &TemplateArgs) {
1485  // FIXME: Can we do any checking at this point? I guess we could check the
1486  // template arguments that we have against the template name, if the template
1487  // name refers to a single template. That's not a terribly common case,
1488  // though.
1489
1490  // These should be filtered out by our callers.
1491  assert(!R.empty() && "empty lookup results when building templateid");
1492  assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1493
1494  NestedNameSpecifier *Qualifier = 0;
1495  SourceRange QualifierRange;
1496  if (SS.isSet()) {
1497    Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1498    QualifierRange = SS.getRange();
1499  }
1500
1501  bool Dependent
1502    = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1503                                              &TemplateArgs);
1504  UnresolvedLookupExpr *ULE
1505    = UnresolvedLookupExpr::Create(Context, Dependent,
1506                                   Qualifier, QualifierRange,
1507                                   R.getLookupName(), R.getNameLoc(),
1508                                   RequiresADL, TemplateArgs);
1509  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1510    ULE->addDecl(*I);
1511
1512  return Owned(ULE);
1513}
1514
1515// We actually only call this from template instantiation.
1516Sema::OwningExprResult
1517Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1518                                   DeclarationName Name,
1519                                   SourceLocation NameLoc,
1520                             const TemplateArgumentListInfo &TemplateArgs) {
1521  DeclContext *DC;
1522  if (!(DC = computeDeclContext(SS, false)) ||
1523      DC->isDependentContext() ||
1524      RequireCompleteDeclContext(SS))
1525    return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
1526
1527  LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1528  LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
1529
1530  if (R.isAmbiguous())
1531    return ExprError();
1532
1533  if (R.empty()) {
1534    Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1535      << Name << SS.getRange();
1536    return ExprError();
1537  }
1538
1539  if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1540    Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1541      << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1542    Diag(Temp->getLocation(), diag::note_referenced_class_template);
1543    return ExprError();
1544  }
1545
1546  return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
1547}
1548
1549/// \brief Form a dependent template name.
1550///
1551/// This action forms a dependent template name given the template
1552/// name and its (presumably dependent) scope specifier. For
1553/// example, given "MetaFun::template apply", the scope specifier \p
1554/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1555/// of the "template" keyword, and "apply" is the \p Name.
1556Sema::TemplateTy
1557Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1558                                 const CXXScopeSpec &SS,
1559                                 UnqualifiedId &Name,
1560                                 TypeTy *ObjectType,
1561                                 bool EnteringContext) {
1562  if ((ObjectType &&
1563       computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1564      (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
1565    // C++0x [temp.names]p5:
1566    //   If a name prefixed by the keyword template is not the name of
1567    //   a template, the program is ill-formed. [Note: the keyword
1568    //   template may not be applied to non-template members of class
1569    //   templates. -end note ] [ Note: as is the case with the
1570    //   typename prefix, the template prefix is allowed in cases
1571    //   where it is not strictly necessary; i.e., when the
1572    //   nested-name-specifier or the expression on the left of the ->
1573    //   or . is not dependent on a template-parameter, or the use
1574    //   does not appear in the scope of a template. -end note]
1575    //
1576    // Note: C++03 was more strict here, because it banned the use of
1577    // the "template" keyword prior to a template-name that was not a
1578    // dependent name. C++ DR468 relaxed this requirement (the
1579    // "template" keyword is now permitted). We follow the C++0x
1580    // rules, even in C++03 mode, retroactively applying the DR.
1581    TemplateTy Template;
1582    TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
1583                                          EnteringContext, Template);
1584    if (TNK == TNK_Non_template) {
1585      Diag(Name.getSourceRange().getBegin(),
1586           diag::err_template_kw_refers_to_non_template)
1587        << GetNameFromUnqualifiedId(Name)
1588        << Name.getSourceRange();
1589      return TemplateTy();
1590    }
1591
1592    return Template;
1593  }
1594
1595  NestedNameSpecifier *Qualifier
1596    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1597
1598  switch (Name.getKind()) {
1599  case UnqualifiedId::IK_Identifier:
1600    return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1601                                                             Name.Identifier));
1602
1603  case UnqualifiedId::IK_OperatorFunctionId:
1604    return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1605                                             Name.OperatorFunctionId.Operator));
1606
1607  case UnqualifiedId::IK_LiteralOperatorId:
1608    assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1609
1610  default:
1611    break;
1612  }
1613
1614  Diag(Name.getSourceRange().getBegin(),
1615       diag::err_template_kw_refers_to_non_template)
1616    << GetNameFromUnqualifiedId(Name)
1617    << Name.getSourceRange();
1618  return TemplateTy();
1619}
1620
1621bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1622                                     const TemplateArgumentLoc &AL,
1623                                     TemplateArgumentListBuilder &Converted) {
1624  const TemplateArgument &Arg = AL.getArgument();
1625
1626  // Check template type parameter.
1627  if (Arg.getKind() != TemplateArgument::Type) {
1628    // C++ [temp.arg.type]p1:
1629    //   A template-argument for a template-parameter which is a
1630    //   type shall be a type-id.
1631
1632    // We have a template type parameter but the template argument
1633    // is not a type.
1634    SourceRange SR = AL.getSourceRange();
1635    Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
1636    Diag(Param->getLocation(), diag::note_template_param_here);
1637
1638    return true;
1639  }
1640
1641  if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
1642    return true;
1643
1644  // Add the converted template type argument.
1645  Converted.Append(
1646                 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
1647  return false;
1648}
1649
1650/// \brief Substitute template arguments into the default template argument for
1651/// the given template type parameter.
1652///
1653/// \param SemaRef the semantic analysis object for which we are performing
1654/// the substitution.
1655///
1656/// \param Template the template that we are synthesizing template arguments
1657/// for.
1658///
1659/// \param TemplateLoc the location of the template name that started the
1660/// template-id we are checking.
1661///
1662/// \param RAngleLoc the location of the right angle bracket ('>') that
1663/// terminates the template-id.
1664///
1665/// \param Param the template template parameter whose default we are
1666/// substituting into.
1667///
1668/// \param Converted the list of template arguments provided for template
1669/// parameters that precede \p Param in the template parameter list.
1670///
1671/// \returns the substituted template argument, or NULL if an error occurred.
1672static TypeSourceInfo *
1673SubstDefaultTemplateArgument(Sema &SemaRef,
1674                             TemplateDecl *Template,
1675                             SourceLocation TemplateLoc,
1676                             SourceLocation RAngleLoc,
1677                             TemplateTypeParmDecl *Param,
1678                             TemplateArgumentListBuilder &Converted) {
1679  TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
1680
1681  // If the argument type is dependent, instantiate it now based
1682  // on the previously-computed template arguments.
1683  if (ArgType->getType()->isDependentType()) {
1684    TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1685                                      /*TakeArgs=*/false);
1686
1687    MultiLevelTemplateArgumentList AllTemplateArgs
1688      = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1689
1690    Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1691                                     Template, Converted.getFlatArguments(),
1692                                     Converted.flatSize(),
1693                                     SourceRange(TemplateLoc, RAngleLoc));
1694
1695    ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1696                                Param->getDefaultArgumentLoc(),
1697                                Param->getDeclName());
1698  }
1699
1700  return ArgType;
1701}
1702
1703/// \brief Substitute template arguments into the default template argument for
1704/// the given non-type template parameter.
1705///
1706/// \param SemaRef the semantic analysis object for which we are performing
1707/// the substitution.
1708///
1709/// \param Template the template that we are synthesizing template arguments
1710/// for.
1711///
1712/// \param TemplateLoc the location of the template name that started the
1713/// template-id we are checking.
1714///
1715/// \param RAngleLoc the location of the right angle bracket ('>') that
1716/// terminates the template-id.
1717///
1718/// \param Param the non-type template parameter whose default we are
1719/// substituting into.
1720///
1721/// \param Converted the list of template arguments provided for template
1722/// parameters that precede \p Param in the template parameter list.
1723///
1724/// \returns the substituted template argument, or NULL if an error occurred.
1725static Sema::OwningExprResult
1726SubstDefaultTemplateArgument(Sema &SemaRef,
1727                             TemplateDecl *Template,
1728                             SourceLocation TemplateLoc,
1729                             SourceLocation RAngleLoc,
1730                             NonTypeTemplateParmDecl *Param,
1731                             TemplateArgumentListBuilder &Converted) {
1732  TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1733                                    /*TakeArgs=*/false);
1734
1735  MultiLevelTemplateArgumentList AllTemplateArgs
1736    = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1737
1738  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1739                                   Template, Converted.getFlatArguments(),
1740                                   Converted.flatSize(),
1741                                   SourceRange(TemplateLoc, RAngleLoc));
1742
1743  return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1744}
1745
1746/// \brief Substitute template arguments into the default template argument for
1747/// the given template template parameter.
1748///
1749/// \param SemaRef the semantic analysis object for which we are performing
1750/// the substitution.
1751///
1752/// \param Template the template that we are synthesizing template arguments
1753/// for.
1754///
1755/// \param TemplateLoc the location of the template name that started the
1756/// template-id we are checking.
1757///
1758/// \param RAngleLoc the location of the right angle bracket ('>') that
1759/// terminates the template-id.
1760///
1761/// \param Param the template template parameter whose default we are
1762/// substituting into.
1763///
1764/// \param Converted the list of template arguments provided for template
1765/// parameters that precede \p Param in the template parameter list.
1766///
1767/// \returns the substituted template argument, or NULL if an error occurred.
1768static TemplateName
1769SubstDefaultTemplateArgument(Sema &SemaRef,
1770                             TemplateDecl *Template,
1771                             SourceLocation TemplateLoc,
1772                             SourceLocation RAngleLoc,
1773                             TemplateTemplateParmDecl *Param,
1774                             TemplateArgumentListBuilder &Converted) {
1775  TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1776                                    /*TakeArgs=*/false);
1777
1778  MultiLevelTemplateArgumentList AllTemplateArgs
1779    = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1780
1781  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1782                                   Template, Converted.getFlatArguments(),
1783                                   Converted.flatSize(),
1784                                   SourceRange(TemplateLoc, RAngleLoc));
1785
1786  return SemaRef.SubstTemplateName(
1787                      Param->getDefaultArgument().getArgument().getAsTemplate(),
1788                              Param->getDefaultArgument().getTemplateNameLoc(),
1789                                   AllTemplateArgs);
1790}
1791
1792/// \brief If the given template parameter has a default template
1793/// argument, substitute into that default template argument and
1794/// return the corresponding template argument.
1795TemplateArgumentLoc
1796Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1797                                              SourceLocation TemplateLoc,
1798                                              SourceLocation RAngleLoc,
1799                                              Decl *Param,
1800                                     TemplateArgumentListBuilder &Converted) {
1801  if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1802    if (!TypeParm->hasDefaultArgument())
1803      return TemplateArgumentLoc();
1804
1805    TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
1806                                                      TemplateLoc,
1807                                                      RAngleLoc,
1808                                                      TypeParm,
1809                                                      Converted);
1810    if (DI)
1811      return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1812
1813    return TemplateArgumentLoc();
1814  }
1815
1816  if (NonTypeTemplateParmDecl *NonTypeParm
1817        = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1818    if (!NonTypeParm->hasDefaultArgument())
1819      return TemplateArgumentLoc();
1820
1821    OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1822                                                        TemplateLoc,
1823                                                        RAngleLoc,
1824                                                        NonTypeParm,
1825                                                        Converted);
1826    if (Arg.isInvalid())
1827      return TemplateArgumentLoc();
1828
1829    Expr *ArgE = Arg.takeAs<Expr>();
1830    return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1831  }
1832
1833  TemplateTemplateParmDecl *TempTempParm
1834    = cast<TemplateTemplateParmDecl>(Param);
1835  if (!TempTempParm->hasDefaultArgument())
1836    return TemplateArgumentLoc();
1837
1838  TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1839                                                    TemplateLoc,
1840                                                    RAngleLoc,
1841                                                    TempTempParm,
1842                                                    Converted);
1843  if (TName.isNull())
1844    return TemplateArgumentLoc();
1845
1846  return TemplateArgumentLoc(TemplateArgument(TName),
1847                TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1848                TempTempParm->getDefaultArgument().getTemplateNameLoc());
1849}
1850
1851/// \brief Check that the given template argument corresponds to the given
1852/// template parameter.
1853bool Sema::CheckTemplateArgument(NamedDecl *Param,
1854                                 const TemplateArgumentLoc &Arg,
1855                                 TemplateDecl *Template,
1856                                 SourceLocation TemplateLoc,
1857                                 SourceLocation RAngleLoc,
1858                                 TemplateArgumentListBuilder &Converted) {
1859  // Check template type parameters.
1860  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
1861    return CheckTemplateTypeArgument(TTP, Arg, Converted);
1862
1863  // Check non-type template parameters.
1864  if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1865    // Do substitution on the type of the non-type template parameter
1866    // with the template arguments we've seen thus far.
1867    QualType NTTPType = NTTP->getType();
1868    if (NTTPType->isDependentType()) {
1869      // Do substitution on the type of the non-type template parameter.
1870      InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1871                                 NTTP, Converted.getFlatArguments(),
1872                                 Converted.flatSize(),
1873                                 SourceRange(TemplateLoc, RAngleLoc));
1874
1875      TemplateArgumentList TemplateArgs(Context, Converted,
1876                                        /*TakeArgs=*/false);
1877      NTTPType = SubstType(NTTPType,
1878                           MultiLevelTemplateArgumentList(TemplateArgs),
1879                           NTTP->getLocation(),
1880                           NTTP->getDeclName());
1881      // If that worked, check the non-type template parameter type
1882      // for validity.
1883      if (!NTTPType.isNull())
1884        NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1885                                                     NTTP->getLocation());
1886      if (NTTPType.isNull())
1887        return true;
1888    }
1889
1890    switch (Arg.getArgument().getKind()) {
1891    case TemplateArgument::Null:
1892      assert(false && "Should never see a NULL template argument here");
1893      return true;
1894
1895    case TemplateArgument::Expression: {
1896      Expr *E = Arg.getArgument().getAsExpr();
1897      TemplateArgument Result;
1898      if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1899        return true;
1900
1901      Converted.Append(Result);
1902      break;
1903    }
1904
1905    case TemplateArgument::Declaration:
1906    case TemplateArgument::Integral:
1907      // We've already checked this template argument, so just copy
1908      // it to the list of converted arguments.
1909      Converted.Append(Arg.getArgument());
1910      break;
1911
1912    case TemplateArgument::Template:
1913      // We were given a template template argument. It may not be ill-formed;
1914      // see below.
1915      if (DependentTemplateName *DTN
1916            = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1917        // We have a template argument such as \c T::template X, which we
1918        // parsed as a template template argument. However, since we now
1919        // know that we need a non-type template argument, convert this
1920        // template name into an expression.
1921        Expr *E = DependentScopeDeclRefExpr::Create(Context,
1922                                                    DTN->getQualifier(),
1923                                               Arg.getTemplateQualifierRange(),
1924                                                    DTN->getIdentifier(),
1925                                                    Arg.getTemplateNameLoc());
1926
1927        TemplateArgument Result;
1928        if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1929          return true;
1930
1931        Converted.Append(Result);
1932        break;
1933      }
1934
1935      // We have a template argument that actually does refer to a class
1936      // template, template alias, or template template parameter, and
1937      // therefore cannot be a non-type template argument.
1938      Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1939        << Arg.getSourceRange();
1940
1941      Diag(Param->getLocation(), diag::note_template_param_here);
1942      return true;
1943
1944    case TemplateArgument::Type: {
1945      // We have a non-type template parameter but the template
1946      // argument is a type.
1947
1948      // C++ [temp.arg]p2:
1949      //   In a template-argument, an ambiguity between a type-id and
1950      //   an expression is resolved to a type-id, regardless of the
1951      //   form of the corresponding template-parameter.
1952      //
1953      // We warn specifically about this case, since it can be rather
1954      // confusing for users.
1955      QualType T = Arg.getArgument().getAsType();
1956      SourceRange SR = Arg.getSourceRange();
1957      if (T->isFunctionType())
1958        Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1959      else
1960        Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1961      Diag(Param->getLocation(), diag::note_template_param_here);
1962      return true;
1963    }
1964
1965    case TemplateArgument::Pack:
1966      llvm_unreachable("Caller must expand template argument packs");
1967      break;
1968    }
1969
1970    return false;
1971  }
1972
1973
1974  // Check template template parameters.
1975  TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1976
1977  // Substitute into the template parameter list of the template
1978  // template parameter, since previously-supplied template arguments
1979  // may appear within the template template parameter.
1980  {
1981    // Set up a template instantiation context.
1982    LocalInstantiationScope Scope(*this);
1983    InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1984                               TempParm, Converted.getFlatArguments(),
1985                               Converted.flatSize(),
1986                               SourceRange(TemplateLoc, RAngleLoc));
1987
1988    TemplateArgumentList TemplateArgs(Context, Converted,
1989                                      /*TakeArgs=*/false);
1990    TempParm = cast_or_null<TemplateTemplateParmDecl>(
1991                      SubstDecl(TempParm, CurContext,
1992                                MultiLevelTemplateArgumentList(TemplateArgs)));
1993    if (!TempParm)
1994      return true;
1995
1996    // FIXME: TempParam is leaked.
1997  }
1998
1999  switch (Arg.getArgument().getKind()) {
2000  case TemplateArgument::Null:
2001    assert(false && "Should never see a NULL template argument here");
2002    return true;
2003
2004  case TemplateArgument::Template:
2005    if (CheckTemplateArgument(TempParm, Arg))
2006      return true;
2007
2008    Converted.Append(Arg.getArgument());
2009    break;
2010
2011  case TemplateArgument::Expression:
2012  case TemplateArgument::Type:
2013    // We have a template template parameter but the template
2014    // argument does not refer to a template.
2015    Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2016    return true;
2017
2018  case TemplateArgument::Declaration:
2019    llvm_unreachable(
2020                       "Declaration argument with template template parameter");
2021    break;
2022  case TemplateArgument::Integral:
2023    llvm_unreachable(
2024                          "Integral argument with template template parameter");
2025    break;
2026
2027  case TemplateArgument::Pack:
2028    llvm_unreachable("Caller must expand template argument packs");
2029    break;
2030  }
2031
2032  return false;
2033}
2034
2035/// \brief Check that the given template argument list is well-formed
2036/// for specializing the given template.
2037bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2038                                     SourceLocation TemplateLoc,
2039                                const TemplateArgumentListInfo &TemplateArgs,
2040                                     bool PartialTemplateArgs,
2041                                     TemplateArgumentListBuilder &Converted) {
2042  TemplateParameterList *Params = Template->getTemplateParameters();
2043  unsigned NumParams = Params->size();
2044  unsigned NumArgs = TemplateArgs.size();
2045  bool Invalid = false;
2046
2047  SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2048
2049  bool HasParameterPack =
2050    NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
2051
2052  if ((NumArgs > NumParams && !HasParameterPack) ||
2053      (NumArgs < Params->getMinRequiredArguments() &&
2054       !PartialTemplateArgs)) {
2055    // FIXME: point at either the first arg beyond what we can handle,
2056    // or the '>', depending on whether we have too many or too few
2057    // arguments.
2058    SourceRange Range;
2059    if (NumArgs > NumParams)
2060      Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
2061    Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2062      << (NumArgs > NumParams)
2063      << (isa<ClassTemplateDecl>(Template)? 0 :
2064          isa<FunctionTemplateDecl>(Template)? 1 :
2065          isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2066      << Template << Range;
2067    Diag(Template->getLocation(), diag::note_template_decl_here)
2068      << Params->getSourceRange();
2069    Invalid = true;
2070  }
2071
2072  // C++ [temp.arg]p1:
2073  //   [...] The type and form of each template-argument specified in
2074  //   a template-id shall match the type and form specified for the
2075  //   corresponding parameter declared by the template in its
2076  //   template-parameter-list.
2077  unsigned ArgIdx = 0;
2078  for (TemplateParameterList::iterator Param = Params->begin(),
2079                                       ParamEnd = Params->end();
2080       Param != ParamEnd; ++Param, ++ArgIdx) {
2081    if (ArgIdx > NumArgs && PartialTemplateArgs)
2082      break;
2083
2084    // If we have a template parameter pack, check every remaining template
2085    // argument against that template parameter pack.
2086    if ((*Param)->isTemplateParameterPack()) {
2087      Converted.BeginPack();
2088      for (; ArgIdx < NumArgs; ++ArgIdx) {
2089        if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2090                                  TemplateLoc, RAngleLoc, Converted)) {
2091          Invalid = true;
2092          break;
2093        }
2094      }
2095      Converted.EndPack();
2096      continue;
2097    }
2098
2099    if (ArgIdx < NumArgs) {
2100      // Check the template argument we were given.
2101      if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2102                                TemplateLoc, RAngleLoc, Converted))
2103        return true;
2104
2105      continue;
2106    }
2107
2108    // We have a default template argument that we will use.
2109    TemplateArgumentLoc Arg;
2110
2111    // Retrieve the default template argument from the template
2112    // parameter. For each kind of template parameter, we substitute the
2113    // template arguments provided thus far and any "outer" template arguments
2114    // (when the template parameter was part of a nested template) into
2115    // the default argument.
2116    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2117      if (!TTP->hasDefaultArgument()) {
2118        assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2119        break;
2120      }
2121
2122      TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
2123                                                             Template,
2124                                                             TemplateLoc,
2125                                                             RAngleLoc,
2126                                                             TTP,
2127                                                             Converted);
2128      if (!ArgType)
2129        return true;
2130
2131      Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2132                                ArgType);
2133    } else if (NonTypeTemplateParmDecl *NTTP
2134                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2135      if (!NTTP->hasDefaultArgument()) {
2136        assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2137        break;
2138      }
2139
2140      Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2141                                                              TemplateLoc,
2142                                                              RAngleLoc,
2143                                                              NTTP,
2144                                                              Converted);
2145      if (E.isInvalid())
2146        return true;
2147
2148      Expr *Ex = E.takeAs<Expr>();
2149      Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2150    } else {
2151      TemplateTemplateParmDecl *TempParm
2152        = cast<TemplateTemplateParmDecl>(*Param);
2153
2154      if (!TempParm->hasDefaultArgument()) {
2155        assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2156        break;
2157      }
2158
2159      TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2160                                                       TemplateLoc,
2161                                                       RAngleLoc,
2162                                                       TempParm,
2163                                                       Converted);
2164      if (Name.isNull())
2165        return true;
2166
2167      Arg = TemplateArgumentLoc(TemplateArgument(Name),
2168                  TempParm->getDefaultArgument().getTemplateQualifierRange(),
2169                  TempParm->getDefaultArgument().getTemplateNameLoc());
2170    }
2171
2172    // Introduce an instantiation record that describes where we are using
2173    // the default template argument.
2174    InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2175                                        Converted.getFlatArguments(),
2176                                        Converted.flatSize(),
2177                                        SourceRange(TemplateLoc, RAngleLoc));
2178
2179    // Check the default template argument.
2180    if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
2181                              RAngleLoc, Converted))
2182      return true;
2183  }
2184
2185  return Invalid;
2186}
2187
2188/// \brief Check a template argument against its corresponding
2189/// template type parameter.
2190///
2191/// This routine implements the semantics of C++ [temp.arg.type]. It
2192/// returns true if an error occurred, and false otherwise.
2193bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
2194                                 TypeSourceInfo *ArgInfo) {
2195  assert(ArgInfo && "invalid TypeSourceInfo");
2196  QualType Arg = ArgInfo->getType();
2197
2198  // C++ [temp.arg.type]p2:
2199  //   A local type, a type with no linkage, an unnamed type or a type
2200  //   compounded from any of these types shall not be used as a
2201  //   template-argument for a template type-parameter.
2202  //
2203  // FIXME: Perform the recursive and no-linkage type checks.
2204  const TagType *Tag = 0;
2205  if (const EnumType *EnumT = Arg->getAs<EnumType>())
2206    Tag = EnumT;
2207  else if (const RecordType *RecordT = Arg->getAs<RecordType>())
2208    Tag = RecordT;
2209  if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2210    SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2211    return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2212      << QualType(Tag, 0) << SR;
2213  } else if (Tag && !Tag->getDecl()->getDeclName() &&
2214           !Tag->getDecl()->getTypedefForAnonDecl()) {
2215    SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2216    Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
2217    Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2218    return true;
2219  } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2220    SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2221    return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
2222  }
2223
2224  return false;
2225}
2226
2227/// \brief Checks whether the given template argument is the address
2228/// of an object or function according to C++ [temp.arg.nontype]p1.
2229bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2230                                                          NamedDecl *&Entity) {
2231  bool Invalid = false;
2232
2233  // See through any implicit casts we added to fix the type.
2234  while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
2235    Arg = Cast->getSubExpr();
2236
2237  // C++0x allows nullptr, and there's no further checking to be done for that.
2238  if (Arg->getType()->isNullPtrType())
2239    return false;
2240
2241  // C++ [temp.arg.nontype]p1:
2242  //
2243  //   A template-argument for a non-type, non-template
2244  //   template-parameter shall be one of: [...]
2245  //
2246  //     -- the address of an object or function with external
2247  //        linkage, including function templates and function
2248  //        template-ids but excluding non-static class members,
2249  //        expressed as & id-expression where the & is optional if
2250  //        the name refers to a function or array, or if the
2251  //        corresponding template-parameter is a reference; or
2252  DeclRefExpr *DRE = 0;
2253
2254  // Ignore (and complain about) any excess parentheses.
2255  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2256    if (!Invalid) {
2257      Diag(Arg->getSourceRange().getBegin(),
2258           diag::err_template_arg_extra_parens)
2259        << Arg->getSourceRange();
2260      Invalid = true;
2261    }
2262
2263    Arg = Parens->getSubExpr();
2264  }
2265
2266  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2267    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2268      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2269  } else
2270    DRE = dyn_cast<DeclRefExpr>(Arg);
2271
2272  if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
2273    return Diag(Arg->getSourceRange().getBegin(),
2274                diag::err_template_arg_not_object_or_func_form)
2275      << Arg->getSourceRange();
2276
2277  // Cannot refer to non-static data members
2278  if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2279    return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2280      << Field << Arg->getSourceRange();
2281
2282  // Cannot refer to non-static member functions
2283  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2284    if (!Method->isStatic())
2285      return Diag(Arg->getSourceRange().getBegin(),
2286                  diag::err_template_arg_method)
2287        << Method << Arg->getSourceRange();
2288
2289  // Functions must have external linkage.
2290  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2291    if (Func->getLinkage() != NamedDecl::ExternalLinkage) {
2292      Diag(Arg->getSourceRange().getBegin(),
2293           diag::err_template_arg_function_not_extern)
2294        << Func << Arg->getSourceRange();
2295      Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2296        << true;
2297      return true;
2298    }
2299
2300    // Okay: we've named a function with external linkage.
2301    Entity = Func;
2302    return Invalid;
2303  }
2304
2305  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2306    if (Var->getLinkage() != NamedDecl::ExternalLinkage) {
2307      Diag(Arg->getSourceRange().getBegin(),
2308           diag::err_template_arg_object_not_extern)
2309        << Var << Arg->getSourceRange();
2310      Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2311        << true;
2312      return true;
2313    }
2314
2315    // Okay: we've named an object with external linkage
2316    Entity = Var;
2317    return Invalid;
2318  }
2319
2320  // We found something else, but we don't know specifically what it is.
2321  Diag(Arg->getSourceRange().getBegin(),
2322       diag::err_template_arg_not_object_or_func)
2323      << Arg->getSourceRange();
2324  Diag(DRE->getDecl()->getLocation(),
2325       diag::note_template_arg_refers_here);
2326  return true;
2327}
2328
2329/// \brief Checks whether the given template argument is a pointer to
2330/// member constant according to C++ [temp.arg.nontype]p1.
2331bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2332                                                TemplateArgument &Converted) {
2333  bool Invalid = false;
2334
2335  // See through any implicit casts we added to fix the type.
2336  while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
2337    Arg = Cast->getSubExpr();
2338
2339  // C++0x allows nullptr, and there's no further checking to be done for that.
2340  if (Arg->getType()->isNullPtrType())
2341    return false;
2342
2343  // C++ [temp.arg.nontype]p1:
2344  //
2345  //   A template-argument for a non-type, non-template
2346  //   template-parameter shall be one of: [...]
2347  //
2348  //     -- a pointer to member expressed as described in 5.3.1.
2349  DeclRefExpr *DRE = 0;
2350
2351  // Ignore (and complain about) any excess parentheses.
2352  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2353    if (!Invalid) {
2354      Diag(Arg->getSourceRange().getBegin(),
2355           diag::err_template_arg_extra_parens)
2356        << Arg->getSourceRange();
2357      Invalid = true;
2358    }
2359
2360    Arg = Parens->getSubExpr();
2361  }
2362
2363  // A pointer-to-member constant written &Class::member.
2364  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2365    if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2366      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2367      if (DRE && !DRE->getQualifier())
2368        DRE = 0;
2369    }
2370  }
2371  // A constant of pointer-to-member type.
2372  else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2373    if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2374      if (VD->getType()->isMemberPointerType()) {
2375        if (isa<NonTypeTemplateParmDecl>(VD) ||
2376            (isa<VarDecl>(VD) &&
2377             Context.getCanonicalType(VD->getType()).isConstQualified())) {
2378          if (Arg->isTypeDependent() || Arg->isValueDependent())
2379            Converted = TemplateArgument(Arg->Retain());
2380          else
2381            Converted = TemplateArgument(VD->getCanonicalDecl());
2382          return Invalid;
2383        }
2384      }
2385    }
2386
2387    DRE = 0;
2388  }
2389
2390  if (!DRE)
2391    return Diag(Arg->getSourceRange().getBegin(),
2392                diag::err_template_arg_not_pointer_to_member_form)
2393      << Arg->getSourceRange();
2394
2395  if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2396    assert((isa<FieldDecl>(DRE->getDecl()) ||
2397            !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2398           "Only non-static member pointers can make it here");
2399
2400    // Okay: this is the address of a non-static member, and therefore
2401    // a member pointer constant.
2402    if (Arg->isTypeDependent() || Arg->isValueDependent())
2403      Converted = TemplateArgument(Arg->Retain());
2404    else
2405      Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
2406    return Invalid;
2407  }
2408
2409  // We found something else, but we don't know specifically what it is.
2410  Diag(Arg->getSourceRange().getBegin(),
2411       diag::err_template_arg_not_pointer_to_member_form)
2412      << Arg->getSourceRange();
2413  Diag(DRE->getDecl()->getLocation(),
2414       diag::note_template_arg_refers_here);
2415  return true;
2416}
2417
2418/// \brief Check a template argument against its corresponding
2419/// non-type template parameter.
2420///
2421/// This routine implements the semantics of C++ [temp.arg.nontype].
2422/// It returns true if an error occurred, and false otherwise. \p
2423/// InstantiatedParamType is the type of the non-type template
2424/// parameter after it has been instantiated.
2425///
2426/// If no error was detected, Converted receives the converted template argument.
2427bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
2428                                 QualType InstantiatedParamType, Expr *&Arg,
2429                                 TemplateArgument &Converted) {
2430  SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2431
2432  // If either the parameter has a dependent type or the argument is
2433  // type-dependent, there's nothing we can check now.
2434  // FIXME: Add template argument to Converted!
2435  if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2436    // FIXME: Produce a cloned, canonical expression?
2437    Converted = TemplateArgument(Arg);
2438    return false;
2439  }
2440
2441  // C++ [temp.arg.nontype]p5:
2442  //   The following conversions are performed on each expression used
2443  //   as a non-type template-argument. If a non-type
2444  //   template-argument cannot be converted to the type of the
2445  //   corresponding template-parameter then the program is
2446  //   ill-formed.
2447  //
2448  //     -- for a non-type template-parameter of integral or
2449  //        enumeration type, integral promotions (4.5) and integral
2450  //        conversions (4.7) are applied.
2451  QualType ParamType = InstantiatedParamType;
2452  QualType ArgType = Arg->getType();
2453  if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
2454    // C++ [temp.arg.nontype]p1:
2455    //   A template-argument for a non-type, non-template
2456    //   template-parameter shall be one of:
2457    //
2458    //     -- an integral constant-expression of integral or enumeration
2459    //        type; or
2460    //     -- the name of a non-type template-parameter; or
2461    SourceLocation NonConstantLoc;
2462    llvm::APSInt Value;
2463    if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
2464      Diag(Arg->getSourceRange().getBegin(),
2465           diag::err_template_arg_not_integral_or_enumeral)
2466        << ArgType << Arg->getSourceRange();
2467      Diag(Param->getLocation(), diag::note_template_param_here);
2468      return true;
2469    } else if (!Arg->isValueDependent() &&
2470               !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
2471      Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2472        << ArgType << Arg->getSourceRange();
2473      return true;
2474    }
2475
2476    // FIXME: We need some way to more easily get the unqualified form
2477    // of the types without going all the way to the
2478    // canonical type.
2479    if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2480      ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2481    if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2482      ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2483
2484    // Try to convert the argument to the parameter's type.
2485    if (Context.hasSameType(ParamType, ArgType)) {
2486      // Okay: no conversion necessary
2487    } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2488               !ParamType->isEnumeralType()) {
2489      // This is an integral promotion or conversion.
2490      ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
2491    } else {
2492      // We can't perform this conversion.
2493      Diag(Arg->getSourceRange().getBegin(),
2494           diag::err_template_arg_not_convertible)
2495        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2496      Diag(Param->getLocation(), diag::note_template_param_here);
2497      return true;
2498    }
2499
2500    QualType IntegerType = Context.getCanonicalType(ParamType);
2501    if (const EnumType *Enum = IntegerType->getAs<EnumType>())
2502      IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
2503
2504    if (!Arg->isValueDependent()) {
2505      // Check that an unsigned parameter does not receive a negative
2506      // value.
2507      if (IntegerType->isUnsignedIntegerType()
2508          && (Value.isSigned() && Value.isNegative())) {
2509        Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2510          << Value.toString(10) << Param->getType()
2511          << Arg->getSourceRange();
2512        Diag(Param->getLocation(), diag::note_template_param_here);
2513        return true;
2514      }
2515
2516      // Check that we don't overflow the template parameter type.
2517      unsigned AllowedBits = Context.getTypeSize(IntegerType);
2518      unsigned RequiredBits;
2519      if (IntegerType->isUnsignedIntegerType())
2520        RequiredBits = Value.getActiveBits();
2521      else if (Value.isUnsigned())
2522        RequiredBits = Value.getActiveBits() + 1;
2523      else
2524        RequiredBits = Value.getMinSignedBits();
2525      if (RequiredBits > AllowedBits) {
2526        Diag(Arg->getSourceRange().getBegin(),
2527             diag::err_template_arg_too_large)
2528          << Value.toString(10) << Param->getType()
2529          << Arg->getSourceRange();
2530        Diag(Param->getLocation(), diag::note_template_param_here);
2531        return true;
2532      }
2533
2534      if (Value.getBitWidth() != AllowedBits)
2535        Value.extOrTrunc(AllowedBits);
2536      Value.setIsSigned(IntegerType->isSignedIntegerType());
2537    }
2538
2539    // Add the value of this argument to the list of converted
2540    // arguments. We use the bitwidth and signedness of the template
2541    // parameter.
2542    if (Arg->isValueDependent()) {
2543      // The argument is value-dependent. Create a new
2544      // TemplateArgument with the converted expression.
2545      Converted = TemplateArgument(Arg);
2546      return false;
2547    }
2548
2549    Converted = TemplateArgument(Value,
2550                                 ParamType->isEnumeralType() ? ParamType
2551                                                             : IntegerType);
2552    return false;
2553  }
2554
2555  // Handle pointer-to-function, reference-to-function, and
2556  // pointer-to-member-function all in (roughly) the same way.
2557  if (// -- For a non-type template-parameter of type pointer to
2558      //    function, only the function-to-pointer conversion (4.3) is
2559      //    applied. If the template-argument represents a set of
2560      //    overloaded functions (or a pointer to such), the matching
2561      //    function is selected from the set (13.4).
2562      // In C++0x, any std::nullptr_t value can be converted.
2563      (ParamType->isPointerType() &&
2564       ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
2565      // -- For a non-type template-parameter of type reference to
2566      //    function, no conversions apply. If the template-argument
2567      //    represents a set of overloaded functions, the matching
2568      //    function is selected from the set (13.4).
2569      (ParamType->isReferenceType() &&
2570       ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
2571      // -- For a non-type template-parameter of type pointer to
2572      //    member function, no conversions apply. If the
2573      //    template-argument represents a set of overloaded member
2574      //    functions, the matching member function is selected from
2575      //    the set (13.4).
2576      // Again, C++0x allows a std::nullptr_t value.
2577      (ParamType->isMemberPointerType() &&
2578       ParamType->getAs<MemberPointerType>()->getPointeeType()
2579         ->isFunctionType())) {
2580    if (Context.hasSameUnqualifiedType(ArgType,
2581                                       ParamType.getNonReferenceType())) {
2582      // We don't have to do anything: the types already match.
2583    } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2584                 ParamType->isMemberPointerType())) {
2585      ArgType = ParamType;
2586      if (ParamType->isMemberPointerType())
2587        ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2588      else
2589        ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
2590    } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
2591      ArgType = Context.getPointerType(ArgType);
2592      ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
2593    } else if (FunctionDecl *Fn
2594                 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
2595      if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2596        return true;
2597
2598      Arg = FixOverloadedFunctionReference(Arg, Fn);
2599      ArgType = Arg->getType();
2600      if (ArgType->isFunctionType() && ParamType->isPointerType()) {
2601        ArgType = Context.getPointerType(Arg->getType());
2602        ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
2603      }
2604    }
2605
2606    if (!Context.hasSameUnqualifiedType(ArgType,
2607                                        ParamType.getNonReferenceType())) {
2608      // We can't perform this conversion.
2609      Diag(Arg->getSourceRange().getBegin(),
2610           diag::err_template_arg_not_convertible)
2611        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2612      Diag(Param->getLocation(), diag::note_template_param_here);
2613      return true;
2614    }
2615
2616    if (ParamType->isMemberPointerType())
2617      return CheckTemplateArgumentPointerToMember(Arg, Converted);
2618
2619    NamedDecl *Entity = 0;
2620    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2621      return true;
2622
2623    if (Entity)
2624      Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2625    Converted = TemplateArgument(Entity);
2626    return false;
2627  }
2628
2629  if (ParamType->isPointerType()) {
2630    //   -- for a non-type template-parameter of type pointer to
2631    //      object, qualification conversions (4.4) and the
2632    //      array-to-pointer conversion (4.2) are applied.
2633    // C++0x also allows a value of std::nullptr_t.
2634    assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
2635           "Only object pointers allowed here");
2636
2637    if (ArgType->isNullPtrType()) {
2638      ArgType = ParamType;
2639      ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
2640    } else if (ArgType->isArrayType()) {
2641      ArgType = Context.getArrayDecayedType(ArgType);
2642      ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
2643    }
2644
2645    if (IsQualificationConversion(ArgType, ParamType)) {
2646      ArgType = ParamType;
2647      ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
2648    }
2649
2650    if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2651      // We can't perform this conversion.
2652      Diag(Arg->getSourceRange().getBegin(),
2653           diag::err_template_arg_not_convertible)
2654        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2655      Diag(Param->getLocation(), diag::note_template_param_here);
2656      return true;
2657    }
2658
2659    NamedDecl *Entity = 0;
2660    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2661      return true;
2662
2663    if (Entity)
2664      Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2665    Converted = TemplateArgument(Entity);
2666    return false;
2667  }
2668
2669  if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
2670    //   -- For a non-type template-parameter of type reference to
2671    //      object, no conversions apply. The type referred to by the
2672    //      reference may be more cv-qualified than the (otherwise
2673    //      identical) type of the template-argument. The
2674    //      template-parameter is bound directly to the
2675    //      template-argument, which must be an lvalue.
2676    assert(ParamRefType->getPointeeType()->isObjectType() &&
2677           "Only object references allowed here");
2678
2679    if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
2680      Diag(Arg->getSourceRange().getBegin(),
2681           diag::err_template_arg_no_ref_bind)
2682        << InstantiatedParamType << Arg->getType()
2683        << Arg->getSourceRange();
2684      Diag(Param->getLocation(), diag::note_template_param_here);
2685      return true;
2686    }
2687
2688    unsigned ParamQuals
2689      = Context.getCanonicalType(ParamType).getCVRQualifiers();
2690    unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
2691
2692    if ((ParamQuals | ArgQuals) != ParamQuals) {
2693      Diag(Arg->getSourceRange().getBegin(),
2694           diag::err_template_arg_ref_bind_ignores_quals)
2695        << InstantiatedParamType << Arg->getType()
2696        << Arg->getSourceRange();
2697      Diag(Param->getLocation(), diag::note_template_param_here);
2698      return true;
2699    }
2700
2701    NamedDecl *Entity = 0;
2702    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2703      return true;
2704
2705    Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2706    Converted = TemplateArgument(Entity);
2707    return false;
2708  }
2709
2710  //     -- For a non-type template-parameter of type pointer to data
2711  //        member, qualification conversions (4.4) are applied.
2712  // C++0x allows std::nullptr_t values.
2713  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2714
2715  if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
2716    // Types match exactly: nothing more to do here.
2717  } else if (ArgType->isNullPtrType()) {
2718    ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2719  } else if (IsQualificationConversion(ArgType, ParamType)) {
2720    ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
2721  } else {
2722    // We can't perform this conversion.
2723    Diag(Arg->getSourceRange().getBegin(),
2724         diag::err_template_arg_not_convertible)
2725      << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2726    Diag(Param->getLocation(), diag::note_template_param_here);
2727    return true;
2728  }
2729
2730  return CheckTemplateArgumentPointerToMember(Arg, Converted);
2731}
2732
2733/// \brief Check a template argument against its corresponding
2734/// template template parameter.
2735///
2736/// This routine implements the semantics of C++ [temp.arg.template].
2737/// It returns true if an error occurred, and false otherwise.
2738bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2739                                 const TemplateArgumentLoc &Arg) {
2740  TemplateName Name = Arg.getArgument().getAsTemplate();
2741  TemplateDecl *Template = Name.getAsTemplateDecl();
2742  if (!Template) {
2743    // Any dependent template name is fine.
2744    assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2745    return false;
2746  }
2747
2748  // C++ [temp.arg.template]p1:
2749  //   A template-argument for a template template-parameter shall be
2750  //   the name of a class template, expressed as id-expression. Only
2751  //   primary class templates are considered when matching the
2752  //   template template argument with the corresponding parameter;
2753  //   partial specializations are not considered even if their
2754  //   parameter lists match that of the template template parameter.
2755  //
2756  // Note that we also allow template template parameters here, which
2757  // will happen when we are dealing with, e.g., class template
2758  // partial specializations.
2759  if (!isa<ClassTemplateDecl>(Template) &&
2760      !isa<TemplateTemplateParmDecl>(Template)) {
2761    assert(isa<FunctionTemplateDecl>(Template) &&
2762           "Only function templates are possible here");
2763    Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
2764    Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
2765      << Template;
2766  }
2767
2768  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2769                                         Param->getTemplateParameters(),
2770                                         true,
2771                                         TPL_TemplateTemplateArgumentMatch,
2772                                         Arg.getLocation());
2773}
2774
2775/// \brief Determine whether the given template parameter lists are
2776/// equivalent.
2777///
2778/// \param New  The new template parameter list, typically written in the
2779/// source code as part of a new template declaration.
2780///
2781/// \param Old  The old template parameter list, typically found via
2782/// name lookup of the template declared with this template parameter
2783/// list.
2784///
2785/// \param Complain  If true, this routine will produce a diagnostic if
2786/// the template parameter lists are not equivalent.
2787///
2788/// \param Kind describes how we are to match the template parameter lists.
2789///
2790/// \param TemplateArgLoc If this source location is valid, then we
2791/// are actually checking the template parameter list of a template
2792/// argument (New) against the template parameter list of its
2793/// corresponding template template parameter (Old). We produce
2794/// slightly different diagnostics in this scenario.
2795///
2796/// \returns True if the template parameter lists are equal, false
2797/// otherwise.
2798bool
2799Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2800                                     TemplateParameterList *Old,
2801                                     bool Complain,
2802                                     TemplateParameterListEqualKind Kind,
2803                                     SourceLocation TemplateArgLoc) {
2804  if (Old->size() != New->size()) {
2805    if (Complain) {
2806      unsigned NextDiag = diag::err_template_param_list_different_arity;
2807      if (TemplateArgLoc.isValid()) {
2808        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2809        NextDiag = diag::note_template_param_list_different_arity;
2810      }
2811      Diag(New->getTemplateLoc(), NextDiag)
2812          << (New->size() > Old->size())
2813          << (Kind != TPL_TemplateMatch)
2814          << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
2815      Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2816        << (Kind != TPL_TemplateMatch)
2817        << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2818    }
2819
2820    return false;
2821  }
2822
2823  for (TemplateParameterList::iterator OldParm = Old->begin(),
2824         OldParmEnd = Old->end(), NewParm = New->begin();
2825       OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2826    if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
2827      if (Complain) {
2828        unsigned NextDiag = diag::err_template_param_different_kind;
2829        if (TemplateArgLoc.isValid()) {
2830          Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2831          NextDiag = diag::note_template_param_different_kind;
2832        }
2833        Diag((*NewParm)->getLocation(), NextDiag)
2834          << (Kind != TPL_TemplateMatch);
2835        Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2836          << (Kind != TPL_TemplateMatch);
2837      }
2838      return false;
2839    }
2840
2841    if (isa<TemplateTypeParmDecl>(*OldParm)) {
2842      // Okay; all template type parameters are equivalent (since we
2843      // know we're at the same index).
2844    } else if (NonTypeTemplateParmDecl *OldNTTP
2845                 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2846      // The types of non-type template parameters must agree.
2847      NonTypeTemplateParmDecl *NewNTTP
2848        = cast<NonTypeTemplateParmDecl>(*NewParm);
2849
2850      // If we are matching a template template argument to a template
2851      // template parameter and one of the non-type template parameter types
2852      // is dependent, then we must wait until template instantiation time
2853      // to actually compare the arguments.
2854      if (Kind == TPL_TemplateTemplateArgumentMatch &&
2855          (OldNTTP->getType()->isDependentType() ||
2856           NewNTTP->getType()->isDependentType()))
2857        continue;
2858
2859      if (Context.getCanonicalType(OldNTTP->getType()) !=
2860            Context.getCanonicalType(NewNTTP->getType())) {
2861        if (Complain) {
2862          unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2863          if (TemplateArgLoc.isValid()) {
2864            Diag(TemplateArgLoc,
2865                 diag::err_template_arg_template_params_mismatch);
2866            NextDiag = diag::note_template_nontype_parm_different_type;
2867          }
2868          Diag(NewNTTP->getLocation(), NextDiag)
2869            << NewNTTP->getType()
2870            << (Kind != TPL_TemplateMatch);
2871          Diag(OldNTTP->getLocation(),
2872               diag::note_template_nontype_parm_prev_declaration)
2873            << OldNTTP->getType();
2874        }
2875        return false;
2876      }
2877    } else {
2878      // The template parameter lists of template template
2879      // parameters must agree.
2880      assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2881             "Only template template parameters handled here");
2882      TemplateTemplateParmDecl *OldTTP
2883        = cast<TemplateTemplateParmDecl>(*OldParm);
2884      TemplateTemplateParmDecl *NewTTP
2885        = cast<TemplateTemplateParmDecl>(*NewParm);
2886      if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2887                                          OldTTP->getTemplateParameters(),
2888                                          Complain,
2889              (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
2890                                          TemplateArgLoc))
2891        return false;
2892    }
2893  }
2894
2895  return true;
2896}
2897
2898/// \brief Check whether a template can be declared within this scope.
2899///
2900/// If the template declaration is valid in this scope, returns
2901/// false. Otherwise, issues a diagnostic and returns true.
2902bool
2903Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
2904  // Find the nearest enclosing declaration scope.
2905  while ((S->getFlags() & Scope::DeclScope) == 0 ||
2906         (S->getFlags() & Scope::TemplateParamScope) != 0)
2907    S = S->getParent();
2908
2909  // C++ [temp]p2:
2910  //   A template-declaration can appear only as a namespace scope or
2911  //   class scope declaration.
2912  DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
2913  if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2914      cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2915    return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
2916             << TemplateParams->getSourceRange();
2917
2918  while (Ctx && isa<LinkageSpecDecl>(Ctx))
2919    Ctx = Ctx->getParent();
2920
2921  if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2922    return false;
2923
2924  return Diag(TemplateParams->getTemplateLoc(),
2925              diag::err_template_outside_namespace_or_class_scope)
2926    << TemplateParams->getSourceRange();
2927}
2928
2929/// \brief Determine what kind of template specialization the given declaration
2930/// is.
2931static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2932  if (!D)
2933    return TSK_Undeclared;
2934
2935  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2936    return Record->getTemplateSpecializationKind();
2937  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2938    return Function->getTemplateSpecializationKind();
2939  if (VarDecl *Var = dyn_cast<VarDecl>(D))
2940    return Var->getTemplateSpecializationKind();
2941
2942  return TSK_Undeclared;
2943}
2944
2945/// \brief Check whether a specialization is well-formed in the current
2946/// context.
2947///
2948/// This routine determines whether a template specialization can be declared
2949/// in the current context (C++ [temp.expl.spec]p2).
2950///
2951/// \param S the semantic analysis object for which this check is being
2952/// performed.
2953///
2954/// \param Specialized the entity being specialized or instantiated, which
2955/// may be a kind of template (class template, function template, etc.) or
2956/// a member of a class template (member function, static data member,
2957/// member class).
2958///
2959/// \param PrevDecl the previous declaration of this entity, if any.
2960///
2961/// \param Loc the location of the explicit specialization or instantiation of
2962/// this entity.
2963///
2964/// \param IsPartialSpecialization whether this is a partial specialization of
2965/// a class template.
2966///
2967/// \returns true if there was an error that we cannot recover from, false
2968/// otherwise.
2969static bool CheckTemplateSpecializationScope(Sema &S,
2970                                             NamedDecl *Specialized,
2971                                             NamedDecl *PrevDecl,
2972                                             SourceLocation Loc,
2973                                             bool IsPartialSpecialization) {
2974  // Keep these "kind" numbers in sync with the %select statements in the
2975  // various diagnostics emitted by this routine.
2976  int EntityKind = 0;
2977  bool isTemplateSpecialization = false;
2978  if (isa<ClassTemplateDecl>(Specialized)) {
2979    EntityKind = IsPartialSpecialization? 1 : 0;
2980    isTemplateSpecialization = true;
2981  } else if (isa<FunctionTemplateDecl>(Specialized)) {
2982    EntityKind = 2;
2983    isTemplateSpecialization = true;
2984  } else if (isa<CXXMethodDecl>(Specialized))
2985    EntityKind = 3;
2986  else if (isa<VarDecl>(Specialized))
2987    EntityKind = 4;
2988  else if (isa<RecordDecl>(Specialized))
2989    EntityKind = 5;
2990  else {
2991    S.Diag(Loc, diag::err_template_spec_unknown_kind);
2992    S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2993    return true;
2994  }
2995
2996  // C++ [temp.expl.spec]p2:
2997  //   An explicit specialization shall be declared in the namespace
2998  //   of which the template is a member, or, for member templates, in
2999  //   the namespace of which the enclosing class or enclosing class
3000  //   template is a member. An explicit specialization of a member
3001  //   function, member class or static data member of a class
3002  //   template shall be declared in the namespace of which the class
3003  //   template is a member. Such a declaration may also be a
3004  //   definition. If the declaration is not a definition, the
3005  //   specialization may be defined later in the name- space in which
3006  //   the explicit specialization was declared, or in a namespace
3007  //   that encloses the one in which the explicit specialization was
3008  //   declared.
3009  if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3010    S.Diag(Loc, diag::err_template_spec_decl_function_scope)
3011      << Specialized;
3012    return true;
3013  }
3014
3015  if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3016    S.Diag(Loc, diag::err_template_spec_decl_class_scope)
3017      << Specialized;
3018    return true;
3019  }
3020
3021  // C++ [temp.class.spec]p6:
3022  //   A class template partial specialization may be declared or redeclared
3023  //   in any namespace scope in which its definition may be defined (14.5.1
3024  //   and 14.5.2).
3025  bool ComplainedAboutScope = false;
3026  DeclContext *SpecializedContext
3027    = Specialized->getDeclContext()->getEnclosingNamespaceContext();
3028  DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
3029  if ((!PrevDecl ||
3030       getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3031       getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3032    // There is no prior declaration of this entity, so this
3033    // specialization must be in the same context as the template
3034    // itself.
3035    if (!DC->Equals(SpecializedContext)) {
3036      if (isa<TranslationUnitDecl>(SpecializedContext))
3037        S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3038        << EntityKind << Specialized;
3039      else if (isa<NamespaceDecl>(SpecializedContext))
3040        S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3041        << EntityKind << Specialized
3042        << cast<NamedDecl>(SpecializedContext);
3043
3044      S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3045      ComplainedAboutScope = true;
3046    }
3047  }
3048
3049  // Make sure that this redeclaration (or definition) occurs in an enclosing
3050  // namespace.
3051  // Note that HandleDeclarator() performs this check for explicit
3052  // specializations of function templates, static data members, and member
3053  // functions, so we skip the check here for those kinds of entities.
3054  // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
3055  // Should we refactor that check, so that it occurs later?
3056  if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
3057      !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3058        isa<FunctionDecl>(Specialized))) {
3059    if (isa<TranslationUnitDecl>(SpecializedContext))
3060      S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3061        << EntityKind << Specialized;
3062    else if (isa<NamespaceDecl>(SpecializedContext))
3063      S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3064        << EntityKind << Specialized
3065        << cast<NamedDecl>(SpecializedContext);
3066
3067    S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3068  }
3069
3070  // FIXME: check for specialization-after-instantiation errors and such.
3071
3072  return false;
3073}
3074
3075/// \brief Check the non-type template arguments of a class template
3076/// partial specialization according to C++ [temp.class.spec]p9.
3077///
3078/// \param TemplateParams the template parameters of the primary class
3079/// template.
3080///
3081/// \param TemplateArg the template arguments of the class template
3082/// partial specialization.
3083///
3084/// \param MirrorsPrimaryTemplate will be set true if the class
3085/// template partial specialization arguments are identical to the
3086/// implicit template arguments of the primary template. This is not
3087/// necessarily an error (C++0x), and it is left to the caller to diagnose
3088/// this condition when it is an error.
3089///
3090/// \returns true if there was an error, false otherwise.
3091bool Sema::CheckClassTemplatePartialSpecializationArgs(
3092                                        TemplateParameterList *TemplateParams,
3093                             const TemplateArgumentListBuilder &TemplateArgs,
3094                                        bool &MirrorsPrimaryTemplate) {
3095  // FIXME: the interface to this function will have to change to
3096  // accommodate variadic templates.
3097  MirrorsPrimaryTemplate = true;
3098
3099  const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
3100
3101  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3102    // Determine whether the template argument list of the partial
3103    // specialization is identical to the implicit argument list of
3104    // the primary template. The caller may need to diagnostic this as
3105    // an error per C++ [temp.class.spec]p9b3.
3106    if (MirrorsPrimaryTemplate) {
3107      if (TemplateTypeParmDecl *TTP
3108            = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3109        if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
3110              Context.getCanonicalType(ArgList[I].getAsType()))
3111          MirrorsPrimaryTemplate = false;
3112      } else if (TemplateTemplateParmDecl *TTP
3113                   = dyn_cast<TemplateTemplateParmDecl>(
3114                                                 TemplateParams->getParam(I))) {
3115        TemplateName Name = ArgList[I].getAsTemplate();
3116        TemplateTemplateParmDecl *ArgDecl
3117          = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
3118        if (!ArgDecl ||
3119            ArgDecl->getIndex() != TTP->getIndex() ||
3120            ArgDecl->getDepth() != TTP->getDepth())
3121          MirrorsPrimaryTemplate = false;
3122      }
3123    }
3124
3125    NonTypeTemplateParmDecl *Param
3126      = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
3127    if (!Param) {
3128      continue;
3129    }
3130
3131    Expr *ArgExpr = ArgList[I].getAsExpr();
3132    if (!ArgExpr) {
3133      MirrorsPrimaryTemplate = false;
3134      continue;
3135    }
3136
3137    // C++ [temp.class.spec]p8:
3138    //   A non-type argument is non-specialized if it is the name of a
3139    //   non-type parameter. All other non-type arguments are
3140    //   specialized.
3141    //
3142    // Below, we check the two conditions that only apply to
3143    // specialized non-type arguments, so skip any non-specialized
3144    // arguments.
3145    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
3146      if (NonTypeTemplateParmDecl *NTTP
3147            = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
3148        if (MirrorsPrimaryTemplate &&
3149            (Param->getIndex() != NTTP->getIndex() ||
3150             Param->getDepth() != NTTP->getDepth()))
3151          MirrorsPrimaryTemplate = false;
3152
3153        continue;
3154      }
3155
3156    // C++ [temp.class.spec]p9:
3157    //   Within the argument list of a class template partial
3158    //   specialization, the following restrictions apply:
3159    //     -- A partially specialized non-type argument expression
3160    //        shall not involve a template parameter of the partial
3161    //        specialization except when the argument expression is a
3162    //        simple identifier.
3163    if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
3164      Diag(ArgExpr->getLocStart(),
3165           diag::err_dependent_non_type_arg_in_partial_spec)
3166        << ArgExpr->getSourceRange();
3167      return true;
3168    }
3169
3170    //     -- The type of a template parameter corresponding to a
3171    //        specialized non-type argument shall not be dependent on a
3172    //        parameter of the specialization.
3173    if (Param->getType()->isDependentType()) {
3174      Diag(ArgExpr->getLocStart(),
3175           diag::err_dependent_typed_non_type_arg_in_partial_spec)
3176        << Param->getType()
3177        << ArgExpr->getSourceRange();
3178      Diag(Param->getLocation(), diag::note_template_param_here);
3179      return true;
3180    }
3181
3182    MirrorsPrimaryTemplate = false;
3183  }
3184
3185  return false;
3186}
3187
3188Sema::DeclResult
3189Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3190                                       TagUseKind TUK,
3191                                       SourceLocation KWLoc,
3192                                       const CXXScopeSpec &SS,
3193                                       TemplateTy TemplateD,
3194                                       SourceLocation TemplateNameLoc,
3195                                       SourceLocation LAngleLoc,
3196                                       ASTTemplateArgsPtr TemplateArgsIn,
3197                                       SourceLocation RAngleLoc,
3198                                       AttributeList *Attr,
3199                               MultiTemplateParamsArg TemplateParameterLists) {
3200  assert(TUK != TUK_Reference && "References are not specializations");
3201
3202  // Find the class template we're specializing
3203  TemplateName Name = TemplateD.getAsVal<TemplateName>();
3204  ClassTemplateDecl *ClassTemplate
3205    = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3206
3207  if (!ClassTemplate) {
3208    Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3209      << (Name.getAsTemplateDecl() &&
3210          isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3211    return true;
3212  }
3213
3214  bool isExplicitSpecialization = false;
3215  bool isPartialSpecialization = false;
3216
3217  // Check the validity of the template headers that introduce this
3218  // template.
3219  // FIXME: We probably shouldn't complain about these headers for
3220  // friend declarations.
3221  TemplateParameterList *TemplateParams
3222    = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3223                        (TemplateParameterList**)TemplateParameterLists.get(),
3224                                              TemplateParameterLists.size(),
3225                                              isExplicitSpecialization);
3226  if (TemplateParams && TemplateParams->size() > 0) {
3227    isPartialSpecialization = true;
3228
3229    // C++ [temp.class.spec]p10:
3230    //   The template parameter list of a specialization shall not
3231    //   contain default template argument values.
3232    for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3233      Decl *Param = TemplateParams->getParam(I);
3234      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3235        if (TTP->hasDefaultArgument()) {
3236          Diag(TTP->getDefaultArgumentLoc(),
3237               diag::err_default_arg_in_partial_spec);
3238          TTP->removeDefaultArgument();
3239        }
3240      } else if (NonTypeTemplateParmDecl *NTTP
3241                   = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3242        if (Expr *DefArg = NTTP->getDefaultArgument()) {
3243          Diag(NTTP->getDefaultArgumentLoc(),
3244               diag::err_default_arg_in_partial_spec)
3245            << DefArg->getSourceRange();
3246          NTTP->setDefaultArgument(0);
3247          DefArg->Destroy(Context);
3248        }
3249      } else {
3250        TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
3251        if (TTP->hasDefaultArgument()) {
3252          Diag(TTP->getDefaultArgument().getLocation(),
3253               diag::err_default_arg_in_partial_spec)
3254            << TTP->getDefaultArgument().getSourceRange();
3255          TTP->setDefaultArgument(TemplateArgumentLoc());
3256        }
3257      }
3258    }
3259  } else if (TemplateParams) {
3260    if (TUK == TUK_Friend)
3261      Diag(KWLoc, diag::err_template_spec_friend)
3262        << CodeModificationHint::CreateRemoval(
3263                                SourceRange(TemplateParams->getTemplateLoc(),
3264                                            TemplateParams->getRAngleLoc()))
3265        << SourceRange(LAngleLoc, RAngleLoc);
3266    else
3267      isExplicitSpecialization = true;
3268  } else if (TUK != TUK_Friend) {
3269    Diag(KWLoc, diag::err_template_spec_needs_header)
3270      << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
3271    isExplicitSpecialization = true;
3272  }
3273
3274  // Check that the specialization uses the same tag kind as the
3275  // original template.
3276  TagDecl::TagKind Kind;
3277  switch (TagSpec) {
3278  default: assert(0 && "Unknown tag type!");
3279  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3280  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
3281  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
3282  }
3283  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
3284                                    Kind, KWLoc,
3285                                    *ClassTemplate->getIdentifier())) {
3286    Diag(KWLoc, diag::err_use_with_wrong_tag)
3287      << ClassTemplate
3288      << CodeModificationHint::CreateReplacement(KWLoc,
3289                            ClassTemplate->getTemplatedDecl()->getKindName());
3290    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
3291         diag::note_previous_use);
3292    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3293  }
3294
3295  // Translate the parser's template argument list in our AST format.
3296  TemplateArgumentListInfo TemplateArgs;
3297  TemplateArgs.setLAngleLoc(LAngleLoc);
3298  TemplateArgs.setRAngleLoc(RAngleLoc);
3299  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3300
3301  // Check that the template argument list is well-formed for this
3302  // template.
3303  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3304                                        TemplateArgs.size());
3305  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3306                                TemplateArgs, false, Converted))
3307    return true;
3308
3309  assert((Converted.structuredSize() ==
3310            ClassTemplate->getTemplateParameters()->size()) &&
3311         "Converted template argument list is too short!");
3312
3313  // Find the class template (partial) specialization declaration that
3314  // corresponds to these arguments.
3315  llvm::FoldingSetNodeID ID;
3316  if (isPartialSpecialization) {
3317    bool MirrorsPrimaryTemplate;
3318    if (CheckClassTemplatePartialSpecializationArgs(
3319                                         ClassTemplate->getTemplateParameters(),
3320                                         Converted, MirrorsPrimaryTemplate))
3321      return true;
3322
3323    if (MirrorsPrimaryTemplate) {
3324      // C++ [temp.class.spec]p9b3:
3325      //
3326      //   -- The argument list of the specialization shall not be identical
3327      //      to the implicit argument list of the primary template.
3328      Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3329        << (TUK == TUK_Definition)
3330        << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
3331                                                           RAngleLoc));
3332      return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
3333                                ClassTemplate->getIdentifier(),
3334                                TemplateNameLoc,
3335                                Attr,
3336                                TemplateParams,
3337                                AS_none);
3338    }
3339
3340    // FIXME: Diagnose friend partial specializations
3341
3342    // FIXME: Template parameter list matters, too
3343    ClassTemplatePartialSpecializationDecl::Profile(ID,
3344                                                   Converted.getFlatArguments(),
3345                                                   Converted.flatSize(),
3346                                                    Context);
3347  } else
3348    ClassTemplateSpecializationDecl::Profile(ID,
3349                                             Converted.getFlatArguments(),
3350                                             Converted.flatSize(),
3351                                             Context);
3352  void *InsertPos = 0;
3353  ClassTemplateSpecializationDecl *PrevDecl = 0;
3354
3355  if (isPartialSpecialization)
3356    PrevDecl
3357      = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
3358                                                                    InsertPos);
3359  else
3360    PrevDecl
3361      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3362
3363  ClassTemplateSpecializationDecl *Specialization = 0;
3364
3365  // Check whether we can declare a class template specialization in
3366  // the current scope.
3367  if (TUK != TUK_Friend &&
3368      CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
3369                                       TemplateNameLoc,
3370                                       isPartialSpecialization))
3371    return true;
3372
3373  // The canonical type
3374  QualType CanonType;
3375  if (PrevDecl &&
3376      (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3377       TUK == TUK_Friend)) {
3378    // Since the only prior class template specialization with these
3379    // arguments was referenced but not declared, or we're only
3380    // referencing this specialization as a friend, reuse that
3381    // declaration node as our own, updating its source location to
3382    // reflect our new declaration.
3383    Specialization = PrevDecl;
3384    Specialization->setLocation(TemplateNameLoc);
3385    PrevDecl = 0;
3386    CanonType = Context.getTypeDeclType(Specialization);
3387  } else if (isPartialSpecialization) {
3388    // Build the canonical type that describes the converted template
3389    // arguments of the class template partial specialization.
3390    CanonType = Context.getTemplateSpecializationType(
3391                                                  TemplateName(ClassTemplate),
3392                                                  Converted.getFlatArguments(),
3393                                                  Converted.flatSize());
3394
3395    // Create a new class template partial specialization declaration node.
3396    ClassTemplatePartialSpecializationDecl *PrevPartial
3397      = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
3398    ClassTemplatePartialSpecializationDecl *Partial
3399      = ClassTemplatePartialSpecializationDecl::Create(Context,
3400                                             ClassTemplate->getDeclContext(),
3401                                                       TemplateNameLoc,
3402                                                       TemplateParams,
3403                                                       ClassTemplate,
3404                                                       Converted,
3405                                                       TemplateArgs,
3406                                                       PrevPartial);
3407
3408    if (PrevPartial) {
3409      ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3410      ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3411    } else {
3412      ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3413    }
3414    Specialization = Partial;
3415
3416    // If we are providing an explicit specialization of a member class
3417    // template specialization, make a note of that.
3418    if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3419      PrevPartial->setMemberSpecialization();
3420
3421    // Check that all of the template parameters of the class template
3422    // partial specialization are deducible from the template
3423    // arguments. If not, this class template partial specialization
3424    // will never be used.
3425    llvm::SmallVector<bool, 8> DeducibleParams;
3426    DeducibleParams.resize(TemplateParams->size());
3427    MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3428                               TemplateParams->getDepth(),
3429                               DeducibleParams);
3430    unsigned NumNonDeducible = 0;
3431    for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3432      if (!DeducibleParams[I])
3433        ++NumNonDeducible;
3434
3435    if (NumNonDeducible) {
3436      Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3437        << (NumNonDeducible > 1)
3438        << SourceRange(TemplateNameLoc, RAngleLoc);
3439      for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3440        if (!DeducibleParams[I]) {
3441          NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3442          if (Param->getDeclName())
3443            Diag(Param->getLocation(),
3444                 diag::note_partial_spec_unused_parameter)
3445              << Param->getDeclName();
3446          else
3447            Diag(Param->getLocation(),
3448                 diag::note_partial_spec_unused_parameter)
3449              << std::string("<anonymous>");
3450        }
3451      }
3452    }
3453  } else {
3454    // Create a new class template specialization declaration node for
3455    // this explicit specialization or friend declaration.
3456    Specialization
3457      = ClassTemplateSpecializationDecl::Create(Context,
3458                                             ClassTemplate->getDeclContext(),
3459                                                TemplateNameLoc,
3460                                                ClassTemplate,
3461                                                Converted,
3462                                                PrevDecl);
3463
3464    if (PrevDecl) {
3465      ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3466      ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3467    } else {
3468      ClassTemplate->getSpecializations().InsertNode(Specialization,
3469                                                     InsertPos);
3470    }
3471
3472    CanonType = Context.getTypeDeclType(Specialization);
3473  }
3474
3475  // C++ [temp.expl.spec]p6:
3476  //   If a template, a member template or the member of a class template is
3477  //   explicitly specialized then that specialization shall be declared
3478  //   before the first use of that specialization that would cause an implicit
3479  //   instantiation to take place, in every translation unit in which such a
3480  //   use occurs; no diagnostic is required.
3481  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3482    SourceRange Range(TemplateNameLoc, RAngleLoc);
3483    Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3484      << Context.getTypeDeclType(Specialization) << Range;
3485
3486    Diag(PrevDecl->getPointOfInstantiation(),
3487         diag::note_instantiation_required_here)
3488      << (PrevDecl->getTemplateSpecializationKind()
3489                                                != TSK_ImplicitInstantiation);
3490    return true;
3491  }
3492
3493  // If this is not a friend, note that this is an explicit specialization.
3494  if (TUK != TUK_Friend)
3495    Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3496
3497  // Check that this isn't a redefinition of this specialization.
3498  if (TUK == TUK_Definition) {
3499    if (RecordDecl *Def = Specialization->getDefinition(Context)) {
3500      SourceRange Range(TemplateNameLoc, RAngleLoc);
3501      Diag(TemplateNameLoc, diag::err_redefinition)
3502        << Context.getTypeDeclType(Specialization) << Range;
3503      Diag(Def->getLocation(), diag::note_previous_definition);
3504      Specialization->setInvalidDecl();
3505      return true;
3506    }
3507  }
3508
3509  // Build the fully-sugared type for this class template
3510  // specialization as the user wrote in the specialization
3511  // itself. This means that we'll pretty-print the type retrieved
3512  // from the specialization's declaration the way that the user
3513  // actually wrote the specialization, rather than formatting the
3514  // name based on the "canonical" representation used to store the
3515  // template arguments in the specialization.
3516  QualType WrittenTy
3517    = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3518  if (TUK != TUK_Friend)
3519    Specialization->setTypeAsWritten(WrittenTy);
3520  TemplateArgsIn.release();
3521
3522  // C++ [temp.expl.spec]p9:
3523  //   A template explicit specialization is in the scope of the
3524  //   namespace in which the template was defined.
3525  //
3526  // We actually implement this paragraph where we set the semantic
3527  // context (in the creation of the ClassTemplateSpecializationDecl),
3528  // but we also maintain the lexical context where the actual
3529  // definition occurs.
3530  Specialization->setLexicalDeclContext(CurContext);
3531
3532  // We may be starting the definition of this specialization.
3533  if (TUK == TUK_Definition)
3534    Specialization->startDefinition();
3535
3536  if (TUK == TUK_Friend) {
3537    FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3538                                            TemplateNameLoc,
3539                                            WrittenTy.getTypePtr(),
3540                                            /*FIXME:*/KWLoc);
3541    Friend->setAccess(AS_public);
3542    CurContext->addDecl(Friend);
3543  } else {
3544    // Add the specialization into its lexical context, so that it can
3545    // be seen when iterating through the list of declarations in that
3546    // context. However, specializations are not found by name lookup.
3547    CurContext->addDecl(Specialization);
3548  }
3549  return DeclPtrTy::make(Specialization);
3550}
3551
3552Sema::DeclPtrTy
3553Sema::ActOnTemplateDeclarator(Scope *S,
3554                              MultiTemplateParamsArg TemplateParameterLists,
3555                              Declarator &D) {
3556  return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3557}
3558
3559Sema::DeclPtrTy
3560Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
3561                               MultiTemplateParamsArg TemplateParameterLists,
3562                                      Declarator &D) {
3563  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3564  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3565         "Not a function declarator!");
3566  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3567
3568  if (FTI.hasPrototype) {
3569    // FIXME: Diagnose arguments without names in C.
3570  }
3571
3572  Scope *ParentScope = FnBodyScope->getParent();
3573
3574  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
3575                                  move(TemplateParameterLists),
3576                                  /*IsFunctionDefinition=*/true);
3577  if (FunctionTemplateDecl *FunctionTemplate
3578        = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
3579    return ActOnStartOfFunctionDef(FnBodyScope,
3580                      DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
3581  if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3582    return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
3583  return DeclPtrTy();
3584}
3585
3586/// \brief Diagnose cases where we have an explicit template specialization
3587/// before/after an explicit template instantiation, producing diagnostics
3588/// for those cases where they are required and determining whether the
3589/// new specialization/instantiation will have any effect.
3590///
3591/// \param NewLoc the location of the new explicit specialization or
3592/// instantiation.
3593///
3594/// \param NewTSK the kind of the new explicit specialization or instantiation.
3595///
3596/// \param PrevDecl the previous declaration of the entity.
3597///
3598/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3599///
3600/// \param PrevPointOfInstantiation if valid, indicates where the previus
3601/// declaration was instantiated (either implicitly or explicitly).
3602///
3603/// \param SuppressNew will be set to true to indicate that the new
3604/// specialization or instantiation has no effect and should be ignored.
3605///
3606/// \returns true if there was an error that should prevent the introduction of
3607/// the new declaration into the AST, false otherwise.
3608bool
3609Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3610                                             TemplateSpecializationKind NewTSK,
3611                                             NamedDecl *PrevDecl,
3612                                             TemplateSpecializationKind PrevTSK,
3613                                        SourceLocation PrevPointOfInstantiation,
3614                                             bool &SuppressNew) {
3615  SuppressNew = false;
3616
3617  switch (NewTSK) {
3618  case TSK_Undeclared:
3619  case TSK_ImplicitInstantiation:
3620    assert(false && "Don't check implicit instantiations here");
3621    return false;
3622
3623  case TSK_ExplicitSpecialization:
3624    switch (PrevTSK) {
3625    case TSK_Undeclared:
3626    case TSK_ExplicitSpecialization:
3627      // Okay, we're just specializing something that is either already
3628      // explicitly specialized or has merely been mentioned without any
3629      // instantiation.
3630      return false;
3631
3632    case TSK_ImplicitInstantiation:
3633      if (PrevPointOfInstantiation.isInvalid()) {
3634        // The declaration itself has not actually been instantiated, so it is
3635        // still okay to specialize it.
3636        return false;
3637      }
3638      // Fall through
3639
3640    case TSK_ExplicitInstantiationDeclaration:
3641    case TSK_ExplicitInstantiationDefinition:
3642      assert((PrevTSK == TSK_ImplicitInstantiation ||
3643              PrevPointOfInstantiation.isValid()) &&
3644             "Explicit instantiation without point of instantiation?");
3645
3646      // C++ [temp.expl.spec]p6:
3647      //   If a template, a member template or the member of a class template
3648      //   is explicitly specialized then that specialization shall be declared
3649      //   before the first use of that specialization that would cause an
3650      //   implicit instantiation to take place, in every translation unit in
3651      //   which such a use occurs; no diagnostic is required.
3652      Diag(NewLoc, diag::err_specialization_after_instantiation)
3653        << PrevDecl;
3654      Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
3655        << (PrevTSK != TSK_ImplicitInstantiation);
3656
3657      return true;
3658    }
3659    break;
3660
3661  case TSK_ExplicitInstantiationDeclaration:
3662    switch (PrevTSK) {
3663    case TSK_ExplicitInstantiationDeclaration:
3664      // This explicit instantiation declaration is redundant (that's okay).
3665      SuppressNew = true;
3666      return false;
3667
3668    case TSK_Undeclared:
3669    case TSK_ImplicitInstantiation:
3670      // We're explicitly instantiating something that may have already been
3671      // implicitly instantiated; that's fine.
3672      return false;
3673
3674    case TSK_ExplicitSpecialization:
3675      // C++0x [temp.explicit]p4:
3676      //   For a given set of template parameters, if an explicit instantiation
3677      //   of a template appears after a declaration of an explicit
3678      //   specialization for that template, the explicit instantiation has no
3679      //   effect.
3680      return false;
3681
3682    case TSK_ExplicitInstantiationDefinition:
3683      // C++0x [temp.explicit]p10:
3684      //   If an entity is the subject of both an explicit instantiation
3685      //   declaration and an explicit instantiation definition in the same
3686      //   translation unit, the definition shall follow the declaration.
3687      Diag(NewLoc,
3688           diag::err_explicit_instantiation_declaration_after_definition);
3689      Diag(PrevPointOfInstantiation,
3690           diag::note_explicit_instantiation_definition_here);
3691      assert(PrevPointOfInstantiation.isValid() &&
3692             "Explicit instantiation without point of instantiation?");
3693      SuppressNew = true;
3694      return false;
3695    }
3696    break;
3697
3698  case TSK_ExplicitInstantiationDefinition:
3699    switch (PrevTSK) {
3700    case TSK_Undeclared:
3701    case TSK_ImplicitInstantiation:
3702      // We're explicitly instantiating something that may have already been
3703      // implicitly instantiated; that's fine.
3704      return false;
3705
3706    case TSK_ExplicitSpecialization:
3707      // C++ DR 259, C++0x [temp.explicit]p4:
3708      //   For a given set of template parameters, if an explicit
3709      //   instantiation of a template appears after a declaration of
3710      //   an explicit specialization for that template, the explicit
3711      //   instantiation has no effect.
3712      //
3713      // In C++98/03 mode, we only give an extension warning here, because it
3714      // is not not harmful to try to explicitly instantiate something that
3715      // has been explicitly specialized.
3716      if (!getLangOptions().CPlusPlus0x) {
3717        Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
3718          << PrevDecl;
3719        Diag(PrevDecl->getLocation(),
3720             diag::note_previous_template_specialization);
3721      }
3722      SuppressNew = true;
3723      return false;
3724
3725    case TSK_ExplicitInstantiationDeclaration:
3726      // We're explicity instantiating a definition for something for which we
3727      // were previously asked to suppress instantiations. That's fine.
3728      return false;
3729
3730    case TSK_ExplicitInstantiationDefinition:
3731      // C++0x [temp.spec]p5:
3732      //   For a given template and a given set of template-arguments,
3733      //     - an explicit instantiation definition shall appear at most once
3734      //       in a program,
3735      Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
3736        << PrevDecl;
3737      Diag(PrevPointOfInstantiation,
3738           diag::note_previous_explicit_instantiation);
3739      SuppressNew = true;
3740      return false;
3741    }
3742    break;
3743  }
3744
3745  assert(false && "Missing specialization/instantiation case?");
3746
3747  return false;
3748}
3749
3750/// \brief Perform semantic analysis for the given function template
3751/// specialization.
3752///
3753/// This routine performs all of the semantic analysis required for an
3754/// explicit function template specialization. On successful completion,
3755/// the function declaration \p FD will become a function template
3756/// specialization.
3757///
3758/// \param FD the function declaration, which will be updated to become a
3759/// function template specialization.
3760///
3761/// \param HasExplicitTemplateArgs whether any template arguments were
3762/// explicitly provided.
3763///
3764/// \param LAngleLoc the location of the left angle bracket ('<'), if
3765/// template arguments were explicitly provided.
3766///
3767/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3768/// if any.
3769///
3770/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3771/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3772/// true as in, e.g., \c void sort<>(char*, char*);
3773///
3774/// \param RAngleLoc the location of the right angle bracket ('>'), if
3775/// template arguments were explicitly provided.
3776///
3777/// \param PrevDecl the set of declarations that
3778bool
3779Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3780                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
3781                                          LookupResult &Previous) {
3782  // The set of function template specializations that could match this
3783  // explicit function template specialization.
3784  typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3785  CandidateSet Candidates;
3786
3787  DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3788  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3789         I != E; ++I) {
3790    NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3791    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
3792      // Only consider templates found within the same semantic lookup scope as
3793      // FD.
3794      if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3795        continue;
3796
3797      // C++ [temp.expl.spec]p11:
3798      //   A trailing template-argument can be left unspecified in the
3799      //   template-id naming an explicit function template specialization
3800      //   provided it can be deduced from the function argument type.
3801      // Perform template argument deduction to determine whether we may be
3802      // specializing this template.
3803      // FIXME: It is somewhat wasteful to build
3804      TemplateDeductionInfo Info(Context);
3805      FunctionDecl *Specialization = 0;
3806      if (TemplateDeductionResult TDK
3807            = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
3808                                      FD->getType(),
3809                                      Specialization,
3810                                      Info)) {
3811        // FIXME: Template argument deduction failed; record why it failed, so
3812        // that we can provide nifty diagnostics.
3813        (void)TDK;
3814        continue;
3815      }
3816
3817      // Record this candidate.
3818      Candidates.push_back(Specialization);
3819    }
3820  }
3821
3822  // Find the most specialized function template.
3823  FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3824                                                    Candidates.size(),
3825                                                    TPOC_Other,
3826                                                    FD->getLocation(),
3827                  PartialDiagnostic(diag::err_function_template_spec_no_match)
3828                    << FD->getDeclName(),
3829                  PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3830                    << FD->getDeclName() << (ExplicitTemplateArgs != 0),
3831                  PartialDiagnostic(diag::note_function_template_spec_matched));
3832  if (!Specialization)
3833    return true;
3834
3835  // FIXME: Check if the prior specialization has a point of instantiation.
3836  // If so, we have run afoul of .
3837
3838  // Check the scope of this explicit specialization.
3839  if (CheckTemplateSpecializationScope(*this,
3840                                       Specialization->getPrimaryTemplate(),
3841                                       Specialization, FD->getLocation(),
3842                                       false))
3843    return true;
3844
3845  // C++ [temp.expl.spec]p6:
3846  //   If a template, a member template or the member of a class template is
3847  //   explicitly specialized then that specialization shall be declared
3848  //   before the first use of that specialization that would cause an implicit
3849  //   instantiation to take place, in every translation unit in which such a
3850  //   use occurs; no diagnostic is required.
3851  FunctionTemplateSpecializationInfo *SpecInfo
3852    = Specialization->getTemplateSpecializationInfo();
3853  assert(SpecInfo && "Function template specialization info missing?");
3854  if (SpecInfo->getPointOfInstantiation().isValid()) {
3855    Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3856      << FD;
3857    Diag(SpecInfo->getPointOfInstantiation(),
3858         diag::note_instantiation_required_here)
3859      << (Specialization->getTemplateSpecializationKind()
3860                                                != TSK_ImplicitInstantiation);
3861    return true;
3862  }
3863
3864  // Mark the prior declaration as an explicit specialization, so that later
3865  // clients know that this is an explicit specialization.
3866  SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
3867
3868  // Turn the given function declaration into a function template
3869  // specialization, with the template arguments from the previous
3870  // specialization.
3871  FD->setFunctionTemplateSpecialization(Context,
3872                                        Specialization->getPrimaryTemplate(),
3873                         new (Context) TemplateArgumentList(
3874                             *Specialization->getTemplateSpecializationArgs()),
3875                                        /*InsertPos=*/0,
3876                                        TSK_ExplicitSpecialization);
3877
3878  // The "previous declaration" for this function template specialization is
3879  // the prior function template specialization.
3880  Previous.clear();
3881  Previous.addDecl(Specialization);
3882  return false;
3883}
3884
3885/// \brief Perform semantic analysis for the given non-template member
3886/// specialization.
3887///
3888/// This routine performs all of the semantic analysis required for an
3889/// explicit member function specialization. On successful completion,
3890/// the function declaration \p FD will become a member function
3891/// specialization.
3892///
3893/// \param Member the member declaration, which will be updated to become a
3894/// specialization.
3895///
3896/// \param Previous the set of declarations, one of which may be specialized
3897/// by this function specialization;  the set will be modified to contain the
3898/// redeclared member.
3899bool
3900Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
3901  assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3902
3903  // Try to find the member we are instantiating.
3904  NamedDecl *Instantiation = 0;
3905  NamedDecl *InstantiatedFrom = 0;
3906  MemberSpecializationInfo *MSInfo = 0;
3907
3908  if (Previous.empty()) {
3909    // Nowhere to look anyway.
3910  } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3911    for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3912           I != E; ++I) {
3913      NamedDecl *D = (*I)->getUnderlyingDecl();
3914      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3915        if (Context.hasSameType(Function->getType(), Method->getType())) {
3916          Instantiation = Method;
3917          InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
3918          MSInfo = Method->getMemberSpecializationInfo();
3919          break;
3920        }
3921      }
3922    }
3923  } else if (isa<VarDecl>(Member)) {
3924    VarDecl *PrevVar;
3925    if (Previous.isSingleResult() &&
3926        (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
3927      if (PrevVar->isStaticDataMember()) {
3928        Instantiation = PrevVar;
3929        InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
3930        MSInfo = PrevVar->getMemberSpecializationInfo();
3931      }
3932  } else if (isa<RecordDecl>(Member)) {
3933    CXXRecordDecl *PrevRecord;
3934    if (Previous.isSingleResult() &&
3935        (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3936      Instantiation = PrevRecord;
3937      InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
3938      MSInfo = PrevRecord->getMemberSpecializationInfo();
3939    }
3940  }
3941
3942  if (!Instantiation) {
3943    // There is no previous declaration that matches. Since member
3944    // specializations are always out-of-line, the caller will complain about
3945    // this mismatch later.
3946    return false;
3947  }
3948
3949  // Make sure that this is a specialization of a member.
3950  if (!InstantiatedFrom) {
3951    Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3952      << Member;
3953    Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3954    return true;
3955  }
3956
3957  // C++ [temp.expl.spec]p6:
3958  //   If a template, a member template or the member of a class template is
3959  //   explicitly specialized then that spe- cialization shall be declared
3960  //   before the first use of that specialization that would cause an implicit
3961  //   instantiation to take place, in every translation unit in which such a
3962  //   use occurs; no diagnostic is required.
3963  assert(MSInfo && "Member specialization info missing?");
3964  if (MSInfo->getPointOfInstantiation().isValid()) {
3965    Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3966      << Member;
3967    Diag(MSInfo->getPointOfInstantiation(),
3968         diag::note_instantiation_required_here)
3969      << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3970    return true;
3971  }
3972
3973  // Check the scope of this explicit specialization.
3974  if (CheckTemplateSpecializationScope(*this,
3975                                       InstantiatedFrom,
3976                                       Instantiation, Member->getLocation(),
3977                                       false))
3978    return true;
3979
3980  // Note that this is an explicit instantiation of a member.
3981  // the original declaration to note that it is an explicit specialization
3982  // (if it was previously an implicit instantiation). This latter step
3983  // makes bookkeeping easier.
3984  if (isa<FunctionDecl>(Member)) {
3985    FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3986    if (InstantiationFunction->getTemplateSpecializationKind() ==
3987          TSK_ImplicitInstantiation) {
3988      InstantiationFunction->setTemplateSpecializationKind(
3989                                                  TSK_ExplicitSpecialization);
3990      InstantiationFunction->setLocation(Member->getLocation());
3991    }
3992
3993    cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3994                                        cast<CXXMethodDecl>(InstantiatedFrom),
3995                                                  TSK_ExplicitSpecialization);
3996  } else if (isa<VarDecl>(Member)) {
3997    VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3998    if (InstantiationVar->getTemplateSpecializationKind() ==
3999          TSK_ImplicitInstantiation) {
4000      InstantiationVar->setTemplateSpecializationKind(
4001                                                  TSK_ExplicitSpecialization);
4002      InstantiationVar->setLocation(Member->getLocation());
4003    }
4004
4005    Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4006                                                cast<VarDecl>(InstantiatedFrom),
4007                                                TSK_ExplicitSpecialization);
4008  } else {
4009    assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
4010    CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4011    if (InstantiationClass->getTemplateSpecializationKind() ==
4012          TSK_ImplicitInstantiation) {
4013      InstantiationClass->setTemplateSpecializationKind(
4014                                                   TSK_ExplicitSpecialization);
4015      InstantiationClass->setLocation(Member->getLocation());
4016    }
4017
4018    cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4019                                        cast<CXXRecordDecl>(InstantiatedFrom),
4020                                                   TSK_ExplicitSpecialization);
4021  }
4022
4023  // Save the caller the trouble of having to figure out which declaration
4024  // this specialization matches.
4025  Previous.clear();
4026  Previous.addDecl(Instantiation);
4027  return false;
4028}
4029
4030/// \brief Check the scope of an explicit instantiation.
4031static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4032                                            SourceLocation InstLoc,
4033                                            bool WasQualifiedName) {
4034  DeclContext *ExpectedContext
4035    = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4036  DeclContext *CurContext = S.CurContext->getLookupContext();
4037
4038  // C++0x [temp.explicit]p2:
4039  //   An explicit instantiation shall appear in an enclosing namespace of its
4040  //   template.
4041  //
4042  // This is DR275, which we do not retroactively apply to C++98/03.
4043  if (S.getLangOptions().CPlusPlus0x &&
4044      !CurContext->Encloses(ExpectedContext)) {
4045    if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4046      S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4047        << D << NS;
4048    else
4049      S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4050        << D;
4051    S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4052    return;
4053  }
4054
4055  // C++0x [temp.explicit]p2:
4056  //   If the name declared in the explicit instantiation is an unqualified
4057  //   name, the explicit instantiation shall appear in the namespace where
4058  //   its template is declared or, if that namespace is inline (7.3.1), any
4059  //   namespace from its enclosing namespace set.
4060  if (WasQualifiedName)
4061    return;
4062
4063  if (CurContext->Equals(ExpectedContext))
4064    return;
4065
4066  S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4067    << D << ExpectedContext;
4068  S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4069}
4070
4071/// \brief Determine whether the given scope specifier has a template-id in it.
4072static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4073  if (!SS.isSet())
4074    return false;
4075
4076  // C++0x [temp.explicit]p2:
4077  //   If the explicit instantiation is for a member function, a member class
4078  //   or a static data member of a class template specialization, the name of
4079  //   the class template specialization in the qualified-id for the member
4080  //   name shall be a simple-template-id.
4081  //
4082  // C++98 has the same restriction, just worded differently.
4083  for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4084       NNS; NNS = NNS->getPrefix())
4085    if (Type *T = NNS->getAsType())
4086      if (isa<TemplateSpecializationType>(T))
4087        return true;
4088
4089  return false;
4090}
4091
4092// Explicit instantiation of a class template specialization
4093// FIXME: Implement extern template semantics
4094Sema::DeclResult
4095Sema::ActOnExplicitInstantiation(Scope *S,
4096                                 SourceLocation ExternLoc,
4097                                 SourceLocation TemplateLoc,
4098                                 unsigned TagSpec,
4099                                 SourceLocation KWLoc,
4100                                 const CXXScopeSpec &SS,
4101                                 TemplateTy TemplateD,
4102                                 SourceLocation TemplateNameLoc,
4103                                 SourceLocation LAngleLoc,
4104                                 ASTTemplateArgsPtr TemplateArgsIn,
4105                                 SourceLocation RAngleLoc,
4106                                 AttributeList *Attr) {
4107  // Find the class template we're specializing
4108  TemplateName Name = TemplateD.getAsVal<TemplateName>();
4109  ClassTemplateDecl *ClassTemplate
4110    = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4111
4112  // Check that the specialization uses the same tag kind as the
4113  // original template.
4114  TagDecl::TagKind Kind;
4115  switch (TagSpec) {
4116  default: assert(0 && "Unknown tag type!");
4117  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4118  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
4119  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
4120  }
4121  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
4122                                    Kind, KWLoc,
4123                                    *ClassTemplate->getIdentifier())) {
4124    Diag(KWLoc, diag::err_use_with_wrong_tag)
4125      << ClassTemplate
4126      << CodeModificationHint::CreateReplacement(KWLoc,
4127                            ClassTemplate->getTemplatedDecl()->getKindName());
4128    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
4129         diag::note_previous_use);
4130    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4131  }
4132
4133  // C++0x [temp.explicit]p2:
4134  //   There are two forms of explicit instantiation: an explicit instantiation
4135  //   definition and an explicit instantiation declaration. An explicit
4136  //   instantiation declaration begins with the extern keyword. [...]
4137  TemplateSpecializationKind TSK
4138    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4139                           : TSK_ExplicitInstantiationDeclaration;
4140
4141  // Translate the parser's template argument list in our AST format.
4142  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4143  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4144
4145  // Check that the template argument list is well-formed for this
4146  // template.
4147  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4148                                        TemplateArgs.size());
4149  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4150                                TemplateArgs, false, Converted))
4151    return true;
4152
4153  assert((Converted.structuredSize() ==
4154            ClassTemplate->getTemplateParameters()->size()) &&
4155         "Converted template argument list is too short!");
4156
4157  // Find the class template specialization declaration that
4158  // corresponds to these arguments.
4159  llvm::FoldingSetNodeID ID;
4160  ClassTemplateSpecializationDecl::Profile(ID,
4161                                           Converted.getFlatArguments(),
4162                                           Converted.flatSize(),
4163                                           Context);
4164  void *InsertPos = 0;
4165  ClassTemplateSpecializationDecl *PrevDecl
4166    = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4167
4168  // C++0x [temp.explicit]p2:
4169  //   [...] An explicit instantiation shall appear in an enclosing
4170  //   namespace of its template. [...]
4171  //
4172  // This is C++ DR 275.
4173  CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4174                                  SS.isSet());
4175
4176  ClassTemplateSpecializationDecl *Specialization = 0;
4177
4178  bool ReusedDecl = false;
4179  if (PrevDecl) {
4180    bool SuppressNew = false;
4181    if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
4182                                               PrevDecl,
4183                                              PrevDecl->getSpecializationKind(),
4184                                            PrevDecl->getPointOfInstantiation(),
4185                                               SuppressNew))
4186      return DeclPtrTy::make(PrevDecl);
4187
4188    if (SuppressNew)
4189      return DeclPtrTy::make(PrevDecl);
4190
4191    if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4192        PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4193      // Since the only prior class template specialization with these
4194      // arguments was referenced but not declared, reuse that
4195      // declaration node as our own, updating its source location to
4196      // reflect our new declaration.
4197      Specialization = PrevDecl;
4198      Specialization->setLocation(TemplateNameLoc);
4199      PrevDecl = 0;
4200      ReusedDecl = true;
4201    }
4202  }
4203
4204  if (!Specialization) {
4205    // Create a new class template specialization declaration node for
4206    // this explicit specialization.
4207    Specialization
4208      = ClassTemplateSpecializationDecl::Create(Context,
4209                                             ClassTemplate->getDeclContext(),
4210                                                TemplateNameLoc,
4211                                                ClassTemplate,
4212                                                Converted, PrevDecl);
4213
4214    if (PrevDecl) {
4215      // Remove the previous declaration from the folding set, since we want
4216      // to introduce a new declaration.
4217      ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4218      ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4219    }
4220
4221    // Insert the new specialization.
4222    ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
4223  }
4224
4225  // Build the fully-sugared type for this explicit instantiation as
4226  // the user wrote in the explicit instantiation itself. This means
4227  // that we'll pretty-print the type retrieved from the
4228  // specialization's declaration the way that the user actually wrote
4229  // the explicit instantiation, rather than formatting the name based
4230  // on the "canonical" representation used to store the template
4231  // arguments in the specialization.
4232  QualType WrittenTy
4233    = Context.getTemplateSpecializationType(Name, TemplateArgs,
4234                                  Context.getTypeDeclType(Specialization));
4235  Specialization->setTypeAsWritten(WrittenTy);
4236  TemplateArgsIn.release();
4237
4238  if (!ReusedDecl) {
4239    // Add the explicit instantiation into its lexical context. However,
4240    // since explicit instantiations are never found by name lookup, we
4241    // just put it into the declaration context directly.
4242    Specialization->setLexicalDeclContext(CurContext);
4243    CurContext->addDecl(Specialization);
4244  }
4245
4246  // C++ [temp.explicit]p3:
4247  //   A definition of a class template or class member template
4248  //   shall be in scope at the point of the explicit instantiation of
4249  //   the class template or class member template.
4250  //
4251  // This check comes when we actually try to perform the
4252  // instantiation.
4253  ClassTemplateSpecializationDecl *Def
4254    = cast_or_null<ClassTemplateSpecializationDecl>(
4255                                        Specialization->getDefinition(Context));
4256  if (!Def)
4257    InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
4258
4259  // Instantiate the members of this class template specialization.
4260  Def = cast_or_null<ClassTemplateSpecializationDecl>(
4261                                       Specialization->getDefinition(Context));
4262  if (Def)
4263    InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
4264
4265  return DeclPtrTy::make(Specialization);
4266}
4267
4268// Explicit instantiation of a member class of a class template.
4269Sema::DeclResult
4270Sema::ActOnExplicitInstantiation(Scope *S,
4271                                 SourceLocation ExternLoc,
4272                                 SourceLocation TemplateLoc,
4273                                 unsigned TagSpec,
4274                                 SourceLocation KWLoc,
4275                                 const CXXScopeSpec &SS,
4276                                 IdentifierInfo *Name,
4277                                 SourceLocation NameLoc,
4278                                 AttributeList *Attr) {
4279
4280  bool Owned = false;
4281  bool IsDependent = false;
4282  DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
4283                            KWLoc, SS, Name, NameLoc, Attr, AS_none,
4284                            MultiTemplateParamsArg(*this, 0, 0),
4285                            Owned, IsDependent);
4286  assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4287
4288  if (!TagD)
4289    return true;
4290
4291  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4292  if (Tag->isEnum()) {
4293    Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4294      << Context.getTypeDeclType(Tag);
4295    return true;
4296  }
4297
4298  if (Tag->isInvalidDecl())
4299    return true;
4300
4301  CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4302  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4303  if (!Pattern) {
4304    Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4305      << Context.getTypeDeclType(Record);
4306    Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4307    return true;
4308  }
4309
4310  // C++0x [temp.explicit]p2:
4311  //   If the explicit instantiation is for a class or member class, the
4312  //   elaborated-type-specifier in the declaration shall include a
4313  //   simple-template-id.
4314  //
4315  // C++98 has the same restriction, just worded differently.
4316  if (!ScopeSpecifierHasTemplateId(SS))
4317    Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4318      << Record << SS.getRange();
4319
4320  // C++0x [temp.explicit]p2:
4321  //   There are two forms of explicit instantiation: an explicit instantiation
4322  //   definition and an explicit instantiation declaration. An explicit
4323  //   instantiation declaration begins with the extern keyword. [...]
4324  TemplateSpecializationKind TSK
4325    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4326                           : TSK_ExplicitInstantiationDeclaration;
4327
4328  // C++0x [temp.explicit]p2:
4329  //   [...] An explicit instantiation shall appear in an enclosing
4330  //   namespace of its template. [...]
4331  //
4332  // This is C++ DR 275.
4333  CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
4334
4335  // Verify that it is okay to explicitly instantiate here.
4336  CXXRecordDecl *PrevDecl
4337    = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4338  if (!PrevDecl && Record->getDefinition(Context))
4339    PrevDecl = Record;
4340  if (PrevDecl) {
4341    MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4342    bool SuppressNew = false;
4343    assert(MSInfo && "No member specialization information?");
4344    if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
4345                                               PrevDecl,
4346                                        MSInfo->getTemplateSpecializationKind(),
4347                                             MSInfo->getPointOfInstantiation(),
4348                                               SuppressNew))
4349      return true;
4350    if (SuppressNew)
4351      return TagD;
4352  }
4353
4354  CXXRecordDecl *RecordDef
4355    = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4356  if (!RecordDef) {
4357    // C++ [temp.explicit]p3:
4358    //   A definition of a member class of a class template shall be in scope
4359    //   at the point of an explicit instantiation of the member class.
4360    CXXRecordDecl *Def
4361      = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4362    if (!Def) {
4363      Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4364        << 0 << Record->getDeclName() << Record->getDeclContext();
4365      Diag(Pattern->getLocation(), diag::note_forward_declaration)
4366        << Pattern;
4367      return true;
4368    } else {
4369      if (InstantiateClass(NameLoc, Record, Def,
4370                           getTemplateInstantiationArgs(Record),
4371                           TSK))
4372        return true;
4373
4374      RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4375      if (!RecordDef)
4376        return true;
4377    }
4378  }
4379
4380  // Instantiate all of the members of the class.
4381  InstantiateClassMembers(NameLoc, RecordDef,
4382                          getTemplateInstantiationArgs(Record), TSK);
4383
4384  // FIXME: We don't have any representation for explicit instantiations of
4385  // member classes. Such a representation is not needed for compilation, but it
4386  // should be available for clients that want to see all of the declarations in
4387  // the source code.
4388  return TagD;
4389}
4390
4391Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4392                                                  SourceLocation ExternLoc,
4393                                                  SourceLocation TemplateLoc,
4394                                                  Declarator &D) {
4395  // Explicit instantiations always require a name.
4396  DeclarationName Name = GetNameForDeclarator(D);
4397  if (!Name) {
4398    if (!D.isInvalidType())
4399      Diag(D.getDeclSpec().getSourceRange().getBegin(),
4400           diag::err_explicit_instantiation_requires_name)
4401        << D.getDeclSpec().getSourceRange()
4402        << D.getSourceRange();
4403
4404    return true;
4405  }
4406
4407  // The scope passed in may not be a decl scope.  Zip up the scope tree until
4408  // we find one that is.
4409  while ((S->getFlags() & Scope::DeclScope) == 0 ||
4410         (S->getFlags() & Scope::TemplateParamScope) != 0)
4411    S = S->getParent();
4412
4413  // Determine the type of the declaration.
4414  QualType R = GetTypeForDeclarator(D, S, 0);
4415  if (R.isNull())
4416    return true;
4417
4418  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4419    // Cannot explicitly instantiate a typedef.
4420    Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4421      << Name;
4422    return true;
4423  }
4424
4425  // C++0x [temp.explicit]p1:
4426  //   [...] An explicit instantiation of a function template shall not use the
4427  //   inline or constexpr specifiers.
4428  // Presumably, this also applies to member functions of class templates as
4429  // well.
4430  if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4431    Diag(D.getDeclSpec().getInlineSpecLoc(),
4432         diag::err_explicit_instantiation_inline)
4433      <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
4434
4435  // FIXME: check for constexpr specifier.
4436
4437  // C++0x [temp.explicit]p2:
4438  //   There are two forms of explicit instantiation: an explicit instantiation
4439  //   definition and an explicit instantiation declaration. An explicit
4440  //   instantiation declaration begins with the extern keyword. [...]
4441  TemplateSpecializationKind TSK
4442    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4443                           : TSK_ExplicitInstantiationDeclaration;
4444
4445  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4446  LookupParsedName(Previous, S, &D.getCXXScopeSpec());
4447
4448  if (!R->isFunctionType()) {
4449    // C++ [temp.explicit]p1:
4450    //   A [...] static data member of a class template can be explicitly
4451    //   instantiated from the member definition associated with its class
4452    //   template.
4453    if (Previous.isAmbiguous())
4454      return true;
4455
4456    VarDecl *Prev = Previous.getAsSingle<VarDecl>();
4457    if (!Prev || !Prev->isStaticDataMember()) {
4458      // We expect to see a data data member here.
4459      Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4460        << Name;
4461      for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4462           P != PEnd; ++P)
4463        Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
4464      return true;
4465    }
4466
4467    if (!Prev->getInstantiatedFromStaticDataMember()) {
4468      // FIXME: Check for explicit specialization?
4469      Diag(D.getIdentifierLoc(),
4470           diag::err_explicit_instantiation_data_member_not_instantiated)
4471        << Prev;
4472      Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4473      // FIXME: Can we provide a note showing where this was declared?
4474      return true;
4475    }
4476
4477    // C++0x [temp.explicit]p2:
4478    //   If the explicit instantiation is for a member function, a member class
4479    //   or a static data member of a class template specialization, the name of
4480    //   the class template specialization in the qualified-id for the member
4481    //   name shall be a simple-template-id.
4482    //
4483    // C++98 has the same restriction, just worded differently.
4484    if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4485      Diag(D.getIdentifierLoc(),
4486           diag::err_explicit_instantiation_without_qualified_id)
4487        << Prev << D.getCXXScopeSpec().getRange();
4488
4489    // Check the scope of this explicit instantiation.
4490    CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4491
4492    // Verify that it is okay to explicitly instantiate here.
4493    MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4494    assert(MSInfo && "Missing static data member specialization info?");
4495    bool SuppressNew = false;
4496    if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
4497                                        MSInfo->getTemplateSpecializationKind(),
4498                                              MSInfo->getPointOfInstantiation(),
4499                                               SuppressNew))
4500      return true;
4501    if (SuppressNew)
4502      return DeclPtrTy();
4503
4504    // Instantiate static data member.
4505    Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4506    if (TSK == TSK_ExplicitInstantiationDefinition)
4507      InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4508                                            /*DefinitionRequired=*/true);
4509
4510    // FIXME: Create an ExplicitInstantiation node?
4511    return DeclPtrTy();
4512  }
4513
4514  // If the declarator is a template-id, translate the parser's template
4515  // argument list into our AST format.
4516  bool HasExplicitTemplateArgs = false;
4517  TemplateArgumentListInfo TemplateArgs;
4518  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4519    TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4520    TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4521    TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
4522    ASTTemplateArgsPtr TemplateArgsPtr(*this,
4523                                       TemplateId->getTemplateArgs(),
4524                                       TemplateId->NumArgs);
4525    translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
4526    HasExplicitTemplateArgs = true;
4527    TemplateArgsPtr.release();
4528  }
4529
4530  // C++ [temp.explicit]p1:
4531  //   A [...] function [...] can be explicitly instantiated from its template.
4532  //   A member function [...] of a class template can be explicitly
4533  //  instantiated from the member definition associated with its class
4534  //  template.
4535  llvm::SmallVector<FunctionDecl *, 8> Matches;
4536  for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4537       P != PEnd; ++P) {
4538    NamedDecl *Prev = *P;
4539    if (!HasExplicitTemplateArgs) {
4540      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4541        if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4542          Matches.clear();
4543          Matches.push_back(Method);
4544          break;
4545        }
4546      }
4547    }
4548
4549    FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4550    if (!FunTmpl)
4551      continue;
4552
4553    TemplateDeductionInfo Info(Context);
4554    FunctionDecl *Specialization = 0;
4555    if (TemplateDeductionResult TDK
4556          = DeduceTemplateArguments(FunTmpl,
4557                               (HasExplicitTemplateArgs ? &TemplateArgs : 0),
4558                                    R, Specialization, Info)) {
4559      // FIXME: Keep track of almost-matches?
4560      (void)TDK;
4561      continue;
4562    }
4563
4564    Matches.push_back(Specialization);
4565  }
4566
4567  // Find the most specialized function template specialization.
4568  FunctionDecl *Specialization
4569    = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4570                         D.getIdentifierLoc(),
4571          PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4572          PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4573                PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4574
4575  if (!Specialization)
4576    return true;
4577
4578  if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
4579    Diag(D.getIdentifierLoc(),
4580         diag::err_explicit_instantiation_member_function_not_instantiated)
4581      << Specialization
4582      << (Specialization->getTemplateSpecializationKind() ==
4583          TSK_ExplicitSpecialization);
4584    Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4585    return true;
4586  }
4587
4588  FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
4589  if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4590    PrevDecl = Specialization;
4591
4592  if (PrevDecl) {
4593    bool SuppressNew = false;
4594    if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
4595                                               PrevDecl,
4596                                     PrevDecl->getTemplateSpecializationKind(),
4597                                          PrevDecl->getPointOfInstantiation(),
4598                                               SuppressNew))
4599      return true;
4600
4601    // FIXME: We may still want to build some representation of this
4602    // explicit specialization.
4603    if (SuppressNew)
4604      return DeclPtrTy();
4605  }
4606
4607  Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4608
4609  if (TSK == TSK_ExplicitInstantiationDefinition)
4610    InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4611                                  false, /*DefinitionRequired=*/true);
4612
4613  // C++0x [temp.explicit]p2:
4614  //   If the explicit instantiation is for a member function, a member class
4615  //   or a static data member of a class template specialization, the name of
4616  //   the class template specialization in the qualified-id for the member
4617  //   name shall be a simple-template-id.
4618  //
4619  // C++98 has the same restriction, just worded differently.
4620  FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
4621  if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
4622      D.getCXXScopeSpec().isSet() &&
4623      !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4624    Diag(D.getIdentifierLoc(),
4625         diag::err_explicit_instantiation_without_qualified_id)
4626    << Specialization << D.getCXXScopeSpec().getRange();
4627
4628  CheckExplicitInstantiationScope(*this,
4629                   FunTmpl? (NamedDecl *)FunTmpl
4630                          : Specialization->getInstantiatedFromMemberFunction(),
4631                                  D.getIdentifierLoc(),
4632                                  D.getCXXScopeSpec().isSet());
4633
4634  // FIXME: Create some kind of ExplicitInstantiationDecl here.
4635  return DeclPtrTy();
4636}
4637
4638Sema::TypeResult
4639Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4640                        const CXXScopeSpec &SS, IdentifierInfo *Name,
4641                        SourceLocation TagLoc, SourceLocation NameLoc) {
4642  // This has to hold, because SS is expected to be defined.
4643  assert(Name && "Expected a name in a dependent tag");
4644
4645  NestedNameSpecifier *NNS
4646    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4647  if (!NNS)
4648    return true;
4649
4650  QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4651  if (T.isNull())
4652    return true;
4653
4654  TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4655  QualType ElabType = Context.getElaboratedType(T, TagKind);
4656
4657  return ElabType.getAsOpaquePtr();
4658}
4659
4660Sema::TypeResult
4661Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4662                        const IdentifierInfo &II, SourceLocation IdLoc) {
4663  NestedNameSpecifier *NNS
4664    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4665  if (!NNS)
4666    return true;
4667
4668  QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
4669  if (T.isNull())
4670    return true;
4671  return T.getAsOpaquePtr();
4672}
4673
4674Sema::TypeResult
4675Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4676                        SourceLocation TemplateLoc, TypeTy *Ty) {
4677  QualType T = GetTypeFromParser(Ty);
4678  NestedNameSpecifier *NNS
4679    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4680  const TemplateSpecializationType *TemplateId
4681    = T->getAs<TemplateSpecializationType>();
4682  assert(TemplateId && "Expected a template specialization type");
4683
4684  if (computeDeclContext(SS, false)) {
4685    // If we can compute a declaration context, then the "typename"
4686    // keyword was superfluous. Just build a QualifiedNameType to keep
4687    // track of the nested-name-specifier.
4688
4689    // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4690    return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4691  }
4692
4693  return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
4694}
4695
4696/// \brief Build the type that describes a C++ typename specifier,
4697/// e.g., "typename T::type".
4698QualType
4699Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4700                        SourceRange Range) {
4701  CXXRecordDecl *CurrentInstantiation = 0;
4702  if (NNS->isDependent()) {
4703    CurrentInstantiation = getCurrentInstantiationOf(NNS);
4704
4705    // If the nested-name-specifier does not refer to the current
4706    // instantiation, then build a typename type.
4707    if (!CurrentInstantiation)
4708      return Context.getTypenameType(NNS, &II);
4709
4710    // The nested-name-specifier refers to the current instantiation, so the
4711    // "typename" keyword itself is superfluous. In C++03, the program is
4712    // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
4713    // extraneous "typename" keywords, and we retroactively apply this DR to
4714    // C++03 code.
4715  }
4716
4717  DeclContext *Ctx = 0;
4718
4719  if (CurrentInstantiation)
4720    Ctx = CurrentInstantiation;
4721  else {
4722    CXXScopeSpec SS;
4723    SS.setScopeRep(NNS);
4724    SS.setRange(Range);
4725    if (RequireCompleteDeclContext(SS))
4726      return QualType();
4727
4728    Ctx = computeDeclContext(SS);
4729  }
4730  assert(Ctx && "No declaration context?");
4731
4732  DeclarationName Name(&II);
4733  LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4734  LookupQualifiedName(Result, Ctx);
4735  unsigned DiagID = 0;
4736  Decl *Referenced = 0;
4737  switch (Result.getResultKind()) {
4738  case LookupResult::NotFound:
4739    DiagID = diag::err_typename_nested_not_found;
4740    break;
4741
4742  case LookupResult::Found:
4743    if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
4744      // We found a type. Build a QualifiedNameType, since the
4745      // typename-specifier was just sugar. FIXME: Tell
4746      // QualifiedNameType that it has a "typename" prefix.
4747      return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4748    }
4749
4750    DiagID = diag::err_typename_nested_not_type;
4751    Referenced = Result.getFoundDecl();
4752    break;
4753
4754  case LookupResult::FoundUnresolvedValue:
4755    llvm_unreachable("unresolved using decl in non-dependent context");
4756    return QualType();
4757
4758  case LookupResult::FoundOverloaded:
4759    DiagID = diag::err_typename_nested_not_type;
4760    Referenced = *Result.begin();
4761    break;
4762
4763  case LookupResult::Ambiguous:
4764    return QualType();
4765  }
4766
4767  // If we get here, it's because name lookup did not find a
4768  // type. Emit an appropriate diagnostic and return an error.
4769  Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
4770  if (Referenced)
4771    Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4772      << Name;
4773  return QualType();
4774}
4775
4776namespace {
4777  // See Sema::RebuildTypeInCurrentInstantiation
4778  class CurrentInstantiationRebuilder
4779    : public TreeTransform<CurrentInstantiationRebuilder> {
4780    SourceLocation Loc;
4781    DeclarationName Entity;
4782
4783  public:
4784    CurrentInstantiationRebuilder(Sema &SemaRef,
4785                                  SourceLocation Loc,
4786                                  DeclarationName Entity)
4787    : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
4788      Loc(Loc), Entity(Entity) { }
4789
4790    /// \brief Determine whether the given type \p T has already been
4791    /// transformed.
4792    ///
4793    /// For the purposes of type reconstruction, a type has already been
4794    /// transformed if it is NULL or if it is not dependent.
4795    bool AlreadyTransformed(QualType T) {
4796      return T.isNull() || !T->isDependentType();
4797    }
4798
4799    /// \brief Returns the location of the entity whose type is being
4800    /// rebuilt.
4801    SourceLocation getBaseLocation() { return Loc; }
4802
4803    /// \brief Returns the name of the entity whose type is being rebuilt.
4804    DeclarationName getBaseEntity() { return Entity; }
4805
4806    /// \brief Sets the "base" location and entity when that
4807    /// information is known based on another transformation.
4808    void setBase(SourceLocation Loc, DeclarationName Entity) {
4809      this->Loc = Loc;
4810      this->Entity = Entity;
4811    }
4812
4813    /// \brief Transforms an expression by returning the expression itself
4814    /// (an identity function).
4815    ///
4816    /// FIXME: This is completely unsafe; we will need to actually clone the
4817    /// expressions.
4818    Sema::OwningExprResult TransformExpr(Expr *E) {
4819      return getSema().Owned(E);
4820    }
4821
4822    /// \brief Transforms a typename type by determining whether the type now
4823    /// refers to a member of the current instantiation, and then
4824    /// type-checking and building a QualifiedNameType (when possible).
4825    QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
4826  };
4827}
4828
4829QualType
4830CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4831                                                     TypenameTypeLoc TL) {
4832  TypenameType *T = TL.getTypePtr();
4833
4834  NestedNameSpecifier *NNS
4835    = TransformNestedNameSpecifier(T->getQualifier(),
4836                              /*FIXME:*/SourceRange(getBaseLocation()));
4837  if (!NNS)
4838    return QualType();
4839
4840  // If the nested-name-specifier did not change, and we cannot compute the
4841  // context corresponding to the nested-name-specifier, then this
4842  // typename type will not change; exit early.
4843  CXXScopeSpec SS;
4844  SS.setRange(SourceRange(getBaseLocation()));
4845  SS.setScopeRep(NNS);
4846
4847  QualType Result;
4848  if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
4849    Result = QualType(T, 0);
4850
4851  // Rebuild the typename type, which will probably turn into a
4852  // QualifiedNameType.
4853  else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
4854    QualType NewTemplateId
4855      = TransformType(QualType(TemplateId, 0));
4856    if (NewTemplateId.isNull())
4857      return QualType();
4858
4859    if (NNS == T->getQualifier() &&
4860        NewTemplateId == QualType(TemplateId, 0))
4861      Result = QualType(T, 0);
4862    else
4863      Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4864  } else
4865    Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4866                                              SourceRange(TL.getNameLoc()));
4867
4868  TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4869  NewTL.setNameLoc(TL.getNameLoc());
4870  return Result;
4871}
4872
4873/// \brief Rebuilds a type within the context of the current instantiation.
4874///
4875/// The type \p T is part of the type of an out-of-line member definition of
4876/// a class template (or class template partial specialization) that was parsed
4877/// and constructed before we entered the scope of the class template (or
4878/// partial specialization thereof). This routine will rebuild that type now
4879/// that we have entered the declarator's scope, which may produce different
4880/// canonical types, e.g.,
4881///
4882/// \code
4883/// template<typename T>
4884/// struct X {
4885///   typedef T* pointer;
4886///   pointer data();
4887/// };
4888///
4889/// template<typename T>
4890/// typename X<T>::pointer X<T>::data() { ... }
4891/// \endcode
4892///
4893/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4894/// since we do not know that we can look into X<T> when we parsed the type.
4895/// This function will rebuild the type, performing the lookup of "pointer"
4896/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4897/// as the canonical type of T*, allowing the return types of the out-of-line
4898/// definition and the declaration to match.
4899QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4900                                                 DeclarationName Name) {
4901  if (T.isNull() || !T->isDependentType())
4902    return T;
4903
4904  CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4905  return Rebuilder.TransformType(T);
4906}
4907
4908/// \brief Produces a formatted string that describes the binding of
4909/// template parameters to template arguments.
4910std::string
4911Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4912                                      const TemplateArgumentList &Args) {
4913  // FIXME: For variadic templates, we'll need to get the structured list.
4914  return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4915                                         Args.flat_size());
4916}
4917
4918std::string
4919Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4920                                      const TemplateArgument *Args,
4921                                      unsigned NumArgs) {
4922  std::string Result;
4923
4924  if (!Params || Params->size() == 0 || NumArgs == 0)
4925    return Result;
4926
4927  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4928    if (I >= NumArgs)
4929      break;
4930
4931    if (I == 0)
4932      Result += "[with ";
4933    else
4934      Result += ", ";
4935
4936    if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4937      Result += Id->getName();
4938    } else {
4939      Result += '$';
4940      Result += llvm::utostr(I);
4941    }
4942
4943    Result += " = ";
4944
4945    switch (Args[I].getKind()) {
4946      case TemplateArgument::Null:
4947        Result += "<no value>";
4948        break;
4949
4950      case TemplateArgument::Type: {
4951        std::string TypeStr;
4952        Args[I].getAsType().getAsStringInternal(TypeStr,
4953                                                Context.PrintingPolicy);
4954        Result += TypeStr;
4955        break;
4956      }
4957
4958      case TemplateArgument::Declaration: {
4959        bool Unnamed = true;
4960        if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4961          if (ND->getDeclName()) {
4962            Unnamed = false;
4963            Result += ND->getNameAsString();
4964          }
4965        }
4966
4967        if (Unnamed) {
4968          Result += "<anonymous>";
4969        }
4970        break;
4971      }
4972
4973      case TemplateArgument::Template: {
4974        std::string Str;
4975        llvm::raw_string_ostream OS(Str);
4976        Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4977        Result += OS.str();
4978        break;
4979      }
4980
4981      case TemplateArgument::Integral: {
4982        Result += Args[I].getAsIntegral()->toString(10);
4983        break;
4984      }
4985
4986      case TemplateArgument::Expression: {
4987        assert(false && "No expressions in deduced template arguments!");
4988        Result += "<expression>";
4989        break;
4990      }
4991
4992      case TemplateArgument::Pack:
4993        // FIXME: Format template argument packs
4994        Result += "<template argument pack>";
4995        break;
4996    }
4997  }
4998
4999  Result += ']';
5000  return Result;
5001}
5002