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