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