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