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