SemaTemplate.cpp revision 6946baf3542dcb1ed0d98d0fdda451d1c39a49c2
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 "TreeTransform.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
20#include "llvm/Support/Compiler.h"
21
22using namespace clang;
23
24/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
29TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
30                                      const CXXScopeSpec *SS,
31                                      bool EnteringContext,
32                                      TemplateTy &TemplateResult) {
33  LookupResult Found = LookupParsedName(S, SS, &II, LookupOrdinaryName,
34                                        false, false, SourceLocation(),
35                                        EnteringContext);
36
37  // FIXME: Cope with ambiguous name-lookup results.
38  assert(!Found.isAmbiguous() &&
39         "Cannot handle template name-lookup ambiguities");
40
41  NamedDecl *IIDecl = Found;
42
43  TemplateNameKind TNK = TNK_Non_template;
44  TemplateDecl *Template = 0;
45
46  if (IIDecl) {
47    if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
48      if (isa<FunctionTemplateDecl>(IIDecl))
49        TNK = TNK_Function_template;
50      else if (isa<ClassTemplateDecl>(IIDecl) ||
51               isa<TemplateTemplateParmDecl>(IIDecl))
52        TNK = TNK_Type_template;
53      else
54        assert(false && "Unknown template declaration kind");
55    } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
56      // C++ [temp.local]p1:
57      //   Like normal (non-template) classes, class templates have an
58      //   injected-class-name (Clause 9). The injected-class-name
59      //   can be used with or without a template-argument-list. When
60      //   it is used without a template-argument-list, it is
61      //   equivalent to the injected-class-name followed by the
62      //   template-parameters of the class template enclosed in
63      //   <>. When it is used with a template-argument-list, it
64      //   refers to the specified class template specialization,
65      //   which could be the current specialization or another
66      //   specialization.
67      if (Record->isInjectedClassName()) {
68        Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
69        if ((Template = Record->getDescribedClassTemplate()))
70          TNK = TNK_Type_template;
71        else if (ClassTemplateSpecializationDecl *Spec
72                   = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
73          Template = Spec->getSpecializedTemplate();
74          TNK = TNK_Type_template;
75        }
76      }
77    } else if (OverloadedFunctionDecl *Ovl
78                 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
79      for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
80                                                  FEnd = Ovl->function_end();
81           F != FEnd; ++F) {
82        if (FunctionTemplateDecl *FuncTmpl
83              = dyn_cast<FunctionTemplateDecl>(*F)) {
84          // We've found a function template. Determine whether there are
85          // any other function templates we need to bundle together in an
86          // OverloadedFunctionDecl
87          for (++F; F != FEnd; ++F) {
88            if (isa<FunctionTemplateDecl>(*F))
89              break;
90          }
91
92          if (F != FEnd) {
93            // Build an overloaded function decl containing only the
94            // function templates in Ovl.
95            OverloadedFunctionDecl *OvlTemplate
96              = OverloadedFunctionDecl::Create(Context,
97                                               Ovl->getDeclContext(),
98                                               Ovl->getDeclName());
99            OvlTemplate->addOverload(FuncTmpl);
100            OvlTemplate->addOverload(*F);
101            for (++F; F != FEnd; ++F) {
102              if (isa<FunctionTemplateDecl>(*F))
103                OvlTemplate->addOverload(*F);
104            }
105
106            // Form the resulting TemplateName
107            if (SS && SS->isSet() && !SS->isInvalid()) {
108              NestedNameSpecifier *Qualifier
109                = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
110              TemplateResult
111                = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
112                                                                    false,
113                                                                  OvlTemplate));
114            } else {
115              TemplateResult = TemplateTy::make(TemplateName(OvlTemplate));
116            }
117            return TNK_Function_template;
118          }
119
120          TNK = TNK_Function_template;
121          Template = FuncTmpl;
122          break;
123        }
124      }
125    }
126
127    if (TNK != TNK_Non_template) {
128      if (SS && SS->isSet() && !SS->isInvalid()) {
129        NestedNameSpecifier *Qualifier
130          = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
131        TemplateResult
132          = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
133                                                              false,
134                                                              Template));
135      } else
136        TemplateResult = TemplateTy::make(TemplateName(Template));
137    }
138  }
139  return TNK;
140}
141
142/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
143/// that the template parameter 'PrevDecl' is being shadowed by a new
144/// declaration at location Loc. Returns true to indicate that this is
145/// an error, and false otherwise.
146bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
147  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
148
149  // Microsoft Visual C++ permits template parameters to be shadowed.
150  if (getLangOptions().Microsoft)
151    return false;
152
153  // C++ [temp.local]p4:
154  //   A template-parameter shall not be redeclared within its
155  //   scope (including nested scopes).
156  Diag(Loc, diag::err_template_param_shadow)
157    << cast<NamedDecl>(PrevDecl)->getDeclName();
158  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
159  return true;
160}
161
162/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
163/// the parameter D to reference the templated declaration and return a pointer
164/// to the template declaration. Otherwise, do nothing to D and return null.
165TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
166  if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
167    D = DeclPtrTy::make(Temp->getTemplatedDecl());
168    return Temp;
169  }
170  return 0;
171}
172
173/// ActOnTypeParameter - Called when a C++ template type parameter
174/// (e.g., "typename T") has been parsed. Typename specifies whether
175/// the keyword "typename" was used to declare the type parameter
176/// (otherwise, "class" was used), and KeyLoc is the location of the
177/// "class" or "typename" keyword. ParamName is the name of the
178/// parameter (NULL indicates an unnamed template parameter) and
179/// ParamName is the location of the parameter name (if any).
180/// If the type parameter has a default argument, it will be added
181/// later via ActOnTypeParameterDefault.
182Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
183                                         SourceLocation EllipsisLoc,
184                                         SourceLocation KeyLoc,
185                                         IdentifierInfo *ParamName,
186                                         SourceLocation ParamNameLoc,
187                                         unsigned Depth, unsigned Position) {
188  assert(S->isTemplateParamScope() &&
189	 "Template type parameter not in template parameter scope!");
190  bool Invalid = false;
191
192  if (ParamName) {
193    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
194    if (PrevDecl && PrevDecl->isTemplateParameter())
195      Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
196							   PrevDecl);
197  }
198
199  SourceLocation Loc = ParamNameLoc;
200  if (!ParamName)
201    Loc = KeyLoc;
202
203  TemplateTypeParmDecl *Param
204    = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
205                                   Depth, Position, ParamName, Typename,
206                                   Ellipsis);
207  if (Invalid)
208    Param->setInvalidDecl();
209
210  if (ParamName) {
211    // Add the template parameter into the current scope.
212    S->AddDecl(DeclPtrTy::make(Param));
213    IdResolver.AddDecl(Param);
214  }
215
216  return DeclPtrTy::make(Param);
217}
218
219/// ActOnTypeParameterDefault - Adds a default argument (the type
220/// Default) to the given template type parameter (TypeParam).
221void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
222                                     SourceLocation EqualLoc,
223                                     SourceLocation DefaultLoc,
224                                     TypeTy *DefaultT) {
225  TemplateTypeParmDecl *Parm
226    = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
227  // FIXME: Preserve type source info.
228  QualType Default = GetTypeFromParser(DefaultT);
229
230  // C++0x [temp.param]p9:
231  // A default template-argument may be specified for any kind of
232  // template-parameter that is not a template parameter pack.
233  if (Parm->isParameterPack()) {
234    Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
235    return;
236  }
237
238  // C++ [temp.param]p14:
239  //   A template-parameter shall not be used in its own default argument.
240  // FIXME: Implement this check! Needs a recursive walk over the types.
241
242  // Check the template argument itself.
243  if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
244    Parm->setInvalidDecl();
245    return;
246  }
247
248  Parm->setDefaultArgument(Default, DefaultLoc, false);
249}
250
251/// \brief Check that the type of a non-type template parameter is
252/// well-formed.
253///
254/// \returns the (possibly-promoted) parameter type if valid;
255/// otherwise, produces a diagnostic and returns a NULL type.
256QualType
257Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
258  // C++ [temp.param]p4:
259  //
260  // A non-type template-parameter shall have one of the following
261  // (optionally cv-qualified) types:
262  //
263  //       -- integral or enumeration type,
264  if (T->isIntegralType() || T->isEnumeralType() ||
265      //   -- pointer to object or pointer to function,
266      (T->isPointerType() &&
267       (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
268        T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
269      //   -- reference to object or reference to function,
270      T->isReferenceType() ||
271      //   -- pointer to member.
272      T->isMemberPointerType() ||
273      // If T is a dependent type, we can't do the check now, so we
274      // assume that it is well-formed.
275      T->isDependentType())
276    return T;
277  // C++ [temp.param]p8:
278  //
279  //   A non-type template-parameter of type "array of T" or
280  //   "function returning T" is adjusted to be of type "pointer to
281  //   T" or "pointer to function returning T", respectively.
282  else if (T->isArrayType())
283    // FIXME: Keep the type prior to promotion?
284    return Context.getArrayDecayedType(T);
285  else if (T->isFunctionType())
286    // FIXME: Keep the type prior to promotion?
287    return Context.getPointerType(T);
288
289  Diag(Loc, diag::err_template_nontype_parm_bad_type)
290    << T;
291
292  return QualType();
293}
294
295/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
296/// template parameter (e.g., "int Size" in "template<int Size>
297/// class Array") has been parsed. S is the current scope and D is
298/// the parsed declarator.
299Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
300                                                    unsigned Depth,
301                                                    unsigned Position) {
302  DeclaratorInfo *DInfo = 0;
303  QualType T = GetTypeForDeclarator(D, S, &DInfo);
304
305  assert(S->isTemplateParamScope() &&
306         "Non-type template parameter not in template parameter scope!");
307  bool Invalid = false;
308
309  IdentifierInfo *ParamName = D.getIdentifier();
310  if (ParamName) {
311    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
312    if (PrevDecl && PrevDecl->isTemplateParameter())
313      Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
314                                                           PrevDecl);
315  }
316
317  T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
318  if (T.isNull()) {
319    T = Context.IntTy; // Recover with an 'int' type.
320    Invalid = true;
321  }
322
323  NonTypeTemplateParmDecl *Param
324    = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
325                                      Depth, Position, ParamName, T, DInfo);
326  if (Invalid)
327    Param->setInvalidDecl();
328
329  if (D.getIdentifier()) {
330    // Add the template parameter into the current scope.
331    S->AddDecl(DeclPtrTy::make(Param));
332    IdResolver.AddDecl(Param);
333  }
334  return DeclPtrTy::make(Param);
335}
336
337/// \brief Adds a default argument to the given non-type template
338/// parameter.
339void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
340                                                SourceLocation EqualLoc,
341                                                ExprArg DefaultE) {
342  NonTypeTemplateParmDecl *TemplateParm
343    = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
344  Expr *Default = static_cast<Expr *>(DefaultE.get());
345
346  // C++ [temp.param]p14:
347  //   A template-parameter shall not be used in its own default argument.
348  // FIXME: Implement this check! Needs a recursive walk over the types.
349
350  // Check the well-formedness of the default template argument.
351  TemplateArgument Converted;
352  if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
353                            Converted)) {
354    TemplateParm->setInvalidDecl();
355    return;
356  }
357
358  TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
359}
360
361
362/// ActOnTemplateTemplateParameter - Called when a C++ template template
363/// parameter (e.g. T in template <template <typename> class T> class array)
364/// has been parsed. S is the current scope.
365Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
366                                                     SourceLocation TmpLoc,
367                                                     TemplateParamsTy *Params,
368                                                     IdentifierInfo *Name,
369                                                     SourceLocation NameLoc,
370                                                     unsigned Depth,
371                                                     unsigned Position)
372{
373  assert(S->isTemplateParamScope() &&
374         "Template template parameter not in template parameter scope!");
375
376  // Construct the parameter object.
377  TemplateTemplateParmDecl *Param =
378    TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
379                                     Position, Name,
380                                     (TemplateParameterList*)Params);
381
382  // Make sure the parameter is valid.
383  // FIXME: Decl object is not currently invalidated anywhere so this doesn't
384  // do anything yet. However, if the template parameter list or (eventual)
385  // default value is ever invalidated, that will propagate here.
386  bool Invalid = false;
387  if (Invalid) {
388    Param->setInvalidDecl();
389  }
390
391  // If the tt-param has a name, then link the identifier into the scope
392  // and lookup mechanisms.
393  if (Name) {
394    S->AddDecl(DeclPtrTy::make(Param));
395    IdResolver.AddDecl(Param);
396  }
397
398  return DeclPtrTy::make(Param);
399}
400
401/// \brief Adds a default argument to the given template template
402/// parameter.
403void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
404                                                 SourceLocation EqualLoc,
405                                                 ExprArg DefaultE) {
406  TemplateTemplateParmDecl *TemplateParm
407    = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
408
409  // Since a template-template parameter's default argument is an
410  // id-expression, it must be a DeclRefExpr.
411  DeclRefExpr *Default
412    = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
413
414  // C++ [temp.param]p14:
415  //   A template-parameter shall not be used in its own default argument.
416  // FIXME: Implement this check! Needs a recursive walk over the types.
417
418  // Check the well-formedness of the template argument.
419  if (!isa<TemplateDecl>(Default->getDecl())) {
420    Diag(Default->getSourceRange().getBegin(),
421         diag::err_template_arg_must_be_template)
422      << Default->getSourceRange();
423    TemplateParm->setInvalidDecl();
424    return;
425  }
426  if (CheckTemplateArgument(TemplateParm, Default)) {
427    TemplateParm->setInvalidDecl();
428    return;
429  }
430
431  DefaultE.release();
432  TemplateParm->setDefaultArgument(Default);
433}
434
435/// ActOnTemplateParameterList - Builds a TemplateParameterList that
436/// contains the template parameters in Params/NumParams.
437Sema::TemplateParamsTy *
438Sema::ActOnTemplateParameterList(unsigned Depth,
439                                 SourceLocation ExportLoc,
440                                 SourceLocation TemplateLoc,
441                                 SourceLocation LAngleLoc,
442                                 DeclPtrTy *Params, unsigned NumParams,
443                                 SourceLocation RAngleLoc) {
444  if (ExportLoc.isValid())
445    Diag(ExportLoc, diag::note_template_export_unsupported);
446
447  return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
448                                       (Decl**)Params, NumParams, RAngleLoc);
449}
450
451Sema::DeclResult
452Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
453                         SourceLocation KWLoc, const CXXScopeSpec &SS,
454                         IdentifierInfo *Name, SourceLocation NameLoc,
455                         AttributeList *Attr,
456                         TemplateParameterList *TemplateParams,
457                         AccessSpecifier AS) {
458  assert(TemplateParams && TemplateParams->size() > 0 &&
459         "No template parameters");
460  assert(TUK != TUK_Reference && "Can only declare or define class templates");
461  bool Invalid = false;
462
463  // Check that we can declare a template here.
464  if (CheckTemplateDeclScope(S, TemplateParams))
465    return true;
466
467  TagDecl::TagKind Kind;
468  switch (TagSpec) {
469  default: assert(0 && "Unknown tag type!");
470  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
471  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
472  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
473  }
474
475  // There is no such thing as an unnamed class template.
476  if (!Name) {
477    Diag(KWLoc, diag::err_template_unnamed_class);
478    return true;
479  }
480
481  // Find any previous declaration with this name.
482  DeclContext *SemanticContext;
483  LookupResult Previous;
484  if (SS.isNotEmpty() && !SS.isInvalid()) {
485    SemanticContext = computeDeclContext(SS, true);
486    if (!SemanticContext) {
487      // FIXME: Produce a reasonable diagnostic here
488      return true;
489    }
490
491    Previous = LookupQualifiedName(SemanticContext, Name, LookupOrdinaryName,
492                                   true);
493  } else {
494    SemanticContext = CurContext;
495    Previous = LookupName(S, Name, LookupOrdinaryName, true);
496  }
497
498  assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
499  NamedDecl *PrevDecl = 0;
500  if (Previous.begin() != Previous.end())
501    PrevDecl = *Previous.begin();
502
503  if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
504    PrevDecl = 0;
505
506  // If there is a previous declaration with the same name, check
507  // whether this is a valid redeclaration.
508  ClassTemplateDecl *PrevClassTemplate
509    = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
510  if (PrevClassTemplate) {
511    // Ensure that the template parameter lists are compatible.
512    if (!TemplateParameterListsAreEqual(TemplateParams,
513                                   PrevClassTemplate->getTemplateParameters(),
514                                        /*Complain=*/true))
515      return true;
516
517    // C++ [temp.class]p4:
518    //   In a redeclaration, partial specialization, explicit
519    //   specialization or explicit instantiation of a class template,
520    //   the class-key shall agree in kind with the original class
521    //   template declaration (7.1.5.3).
522    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
523    if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
524      Diag(KWLoc, diag::err_use_with_wrong_tag)
525        << Name
526        << CodeModificationHint::CreateReplacement(KWLoc,
527                            PrevRecordDecl->getKindName());
528      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
529      Kind = PrevRecordDecl->getTagKind();
530    }
531
532    // Check for redefinition of this class template.
533    if (TUK == TUK_Definition) {
534      if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
535        Diag(NameLoc, diag::err_redefinition) << Name;
536        Diag(Def->getLocation(), diag::note_previous_definition);
537        // FIXME: Would it make sense to try to "forget" the previous
538        // definition, as part of error recovery?
539        return true;
540      }
541    }
542  } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
543    // Maybe we will complain about the shadowed template parameter.
544    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
545    // Just pretend that we didn't see the previous declaration.
546    PrevDecl = 0;
547  } else if (PrevDecl) {
548    // C++ [temp]p5:
549    //   A class template shall not have the same name as any other
550    //   template, class, function, object, enumeration, enumerator,
551    //   namespace, or type in the same scope (3.3), except as specified
552    //   in (14.5.4).
553    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
554    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
555    return true;
556  }
557
558  // Check the template parameter list of this declaration, possibly
559  // merging in the template parameter list from the previous class
560  // template declaration.
561  if (CheckTemplateParameterList(TemplateParams,
562            PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
563    Invalid = true;
564
565  // FIXME: If we had a scope specifier, we better have a previous template
566  // declaration!
567
568  CXXRecordDecl *NewClass =
569    CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
570                          PrevClassTemplate?
571                            PrevClassTemplate->getTemplatedDecl() : 0,
572                          /*DelayTypeCreation=*/true);
573
574  ClassTemplateDecl *NewTemplate
575    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
576                                DeclarationName(Name), TemplateParams,
577                                NewClass, PrevClassTemplate);
578  NewClass->setDescribedClassTemplate(NewTemplate);
579
580  // Build the type for the class template declaration now.
581  QualType T =
582    Context.getTypeDeclType(NewClass,
583                            PrevClassTemplate?
584                              PrevClassTemplate->getTemplatedDecl() : 0);
585  assert(T->isDependentType() && "Class template type is not dependent?");
586  (void)T;
587
588  // Set the access specifier.
589  SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
590
591  // Set the lexical context of these templates
592  NewClass->setLexicalDeclContext(CurContext);
593  NewTemplate->setLexicalDeclContext(CurContext);
594
595  if (TUK == TUK_Definition)
596    NewClass->startDefinition();
597
598  if (Attr)
599    ProcessDeclAttributeList(S, NewClass, Attr);
600
601  PushOnScopeChains(NewTemplate, S);
602
603  if (Invalid) {
604    NewTemplate->setInvalidDecl();
605    NewClass->setInvalidDecl();
606  }
607  return DeclPtrTy::make(NewTemplate);
608}
609
610/// \brief Checks the validity of a template parameter list, possibly
611/// considering the template parameter list from a previous
612/// declaration.
613///
614/// If an "old" template parameter list is provided, it must be
615/// equivalent (per TemplateParameterListsAreEqual) to the "new"
616/// template parameter list.
617///
618/// \param NewParams Template parameter list for a new template
619/// declaration. This template parameter list will be updated with any
620/// default arguments that are carried through from the previous
621/// template parameter list.
622///
623/// \param OldParams If provided, template parameter list from a
624/// previous declaration of the same template. Default template
625/// arguments will be merged from the old template parameter list to
626/// the new template parameter list.
627///
628/// \returns true if an error occurred, false otherwise.
629bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
630                                      TemplateParameterList *OldParams) {
631  bool Invalid = false;
632
633  // C++ [temp.param]p10:
634  //   The set of default template-arguments available for use with a
635  //   template declaration or definition is obtained by merging the
636  //   default arguments from the definition (if in scope) and all
637  //   declarations in scope in the same way default function
638  //   arguments are (8.3.6).
639  bool SawDefaultArgument = false;
640  SourceLocation PreviousDefaultArgLoc;
641
642  bool SawParameterPack = false;
643  SourceLocation ParameterPackLoc;
644
645  // Dummy initialization to avoid warnings.
646  TemplateParameterList::iterator OldParam = NewParams->end();
647  if (OldParams)
648    OldParam = OldParams->begin();
649
650  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
651                                    NewParamEnd = NewParams->end();
652       NewParam != NewParamEnd; ++NewParam) {
653    // Variables used to diagnose redundant default arguments
654    bool RedundantDefaultArg = false;
655    SourceLocation OldDefaultLoc;
656    SourceLocation NewDefaultLoc;
657
658    // Variables used to diagnose missing default arguments
659    bool MissingDefaultArg = false;
660
661    // C++0x [temp.param]p11:
662    // If a template parameter of a class template is a template parameter pack,
663    // it must be the last template parameter.
664    if (SawParameterPack) {
665      Diag(ParameterPackLoc,
666           diag::err_template_param_pack_must_be_last_template_parameter);
667      Invalid = true;
668    }
669
670    // Merge default arguments for template type parameters.
671    if (TemplateTypeParmDecl *NewTypeParm
672          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
673      TemplateTypeParmDecl *OldTypeParm
674          = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
675
676      if (NewTypeParm->isParameterPack()) {
677        assert(!NewTypeParm->hasDefaultArgument() &&
678               "Parameter packs can't have a default argument!");
679        SawParameterPack = true;
680        ParameterPackLoc = NewTypeParm->getLocation();
681      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
682          NewTypeParm->hasDefaultArgument()) {
683        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
684        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
685        SawDefaultArgument = true;
686        RedundantDefaultArg = true;
687        PreviousDefaultArgLoc = NewDefaultLoc;
688      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
689        // Merge the default argument from the old declaration to the
690        // new declaration.
691        SawDefaultArgument = true;
692        NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
693                                        OldTypeParm->getDefaultArgumentLoc(),
694                                        true);
695        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
696      } else if (NewTypeParm->hasDefaultArgument()) {
697        SawDefaultArgument = true;
698        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
699      } else if (SawDefaultArgument)
700        MissingDefaultArg = true;
701    } else if (NonTypeTemplateParmDecl *NewNonTypeParm
702               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
703      // Merge default arguments for non-type template parameters
704      NonTypeTemplateParmDecl *OldNonTypeParm
705        = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
706      if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
707          NewNonTypeParm->hasDefaultArgument()) {
708        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
709        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
710        SawDefaultArgument = true;
711        RedundantDefaultArg = true;
712        PreviousDefaultArgLoc = NewDefaultLoc;
713      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
714        // Merge the default argument from the old declaration to the
715        // new declaration.
716        SawDefaultArgument = true;
717        // FIXME: We need to create a new kind of "default argument"
718        // expression that points to a previous template template
719        // parameter.
720        NewNonTypeParm->setDefaultArgument(
721                                        OldNonTypeParm->getDefaultArgument());
722        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
723      } else if (NewNonTypeParm->hasDefaultArgument()) {
724        SawDefaultArgument = true;
725        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
726      } else if (SawDefaultArgument)
727        MissingDefaultArg = true;
728    } else {
729    // Merge default arguments for template template parameters
730      TemplateTemplateParmDecl *NewTemplateParm
731        = cast<TemplateTemplateParmDecl>(*NewParam);
732      TemplateTemplateParmDecl *OldTemplateParm
733        = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
734      if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
735          NewTemplateParm->hasDefaultArgument()) {
736        OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
737        NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
738        SawDefaultArgument = true;
739        RedundantDefaultArg = true;
740        PreviousDefaultArgLoc = NewDefaultLoc;
741      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
742        // Merge the default argument from the old declaration to the
743        // new declaration.
744        SawDefaultArgument = true;
745        // FIXME: We need to create a new kind of "default argument" expression
746        // that points to a previous template template parameter.
747        NewTemplateParm->setDefaultArgument(
748                                        OldTemplateParm->getDefaultArgument());
749        PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
750      } else if (NewTemplateParm->hasDefaultArgument()) {
751        SawDefaultArgument = true;
752        PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
753      } else if (SawDefaultArgument)
754        MissingDefaultArg = true;
755    }
756
757    if (RedundantDefaultArg) {
758      // C++ [temp.param]p12:
759      //   A template-parameter shall not be given default arguments
760      //   by two different declarations in the same scope.
761      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
762      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
763      Invalid = true;
764    } else if (MissingDefaultArg) {
765      // C++ [temp.param]p11:
766      //   If a template-parameter has a default template-argument,
767      //   all subsequent template-parameters shall have a default
768      //   template-argument supplied.
769      Diag((*NewParam)->getLocation(),
770           diag::err_template_param_default_arg_missing);
771      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
772      Invalid = true;
773    }
774
775    // If we have an old template parameter list that we're merging
776    // in, move on to the next parameter.
777    if (OldParams)
778      ++OldParam;
779  }
780
781  return Invalid;
782}
783
784/// \brief Match the given template parameter lists to the given scope
785/// specifier, returning the template parameter list that applies to the
786/// name.
787///
788/// \param DeclStartLoc the start of the declaration that has a scope
789/// specifier or a template parameter list.
790///
791/// \param SS the scope specifier that will be matched to the given template
792/// parameter lists. This scope specifier precedes a qualified name that is
793/// being declared.
794///
795/// \param ParamLists the template parameter lists, from the outermost to the
796/// innermost template parameter lists.
797///
798/// \param NumParamLists the number of template parameter lists in ParamLists.
799///
800/// \returns the template parameter list, if any, that corresponds to the
801/// name that is preceded by the scope specifier @p SS. This template
802/// parameter list may be have template parameters (if we're declaring a
803/// template) or may have no template parameters (if we're declaring a
804/// template specialization), or may be NULL (if we were's declaring isn't
805/// itself a template).
806TemplateParameterList *
807Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
808                                              const CXXScopeSpec &SS,
809                                          TemplateParameterList **ParamLists,
810                                              unsigned NumParamLists) {
811  // Find the template-ids that occur within the nested-name-specifier. These
812  // template-ids will match up with the template parameter lists.
813  llvm::SmallVector<const TemplateSpecializationType *, 4>
814    TemplateIdsInSpecifier;
815  for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
816       NNS; NNS = NNS->getPrefix()) {
817    if (const TemplateSpecializationType *SpecType
818          = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
819      TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
820      if (!Template)
821        continue; // FIXME: should this be an error? probably...
822
823      if (const RecordType *Record = SpecType->getAs<RecordType>()) {
824        ClassTemplateSpecializationDecl *SpecDecl
825          = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
826        // If the nested name specifier refers to an explicit specialization,
827        // we don't need a template<> header.
828        // FIXME: revisit this approach once we cope with specialization
829        // properly.
830        if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
831          continue;
832      }
833
834      TemplateIdsInSpecifier.push_back(SpecType);
835    }
836  }
837
838  // Reverse the list of template-ids in the scope specifier, so that we can
839  // more easily match up the template-ids and the template parameter lists.
840  std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
841
842  SourceLocation FirstTemplateLoc = DeclStartLoc;
843  if (NumParamLists)
844    FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
845
846  // Match the template-ids found in the specifier to the template parameter
847  // lists.
848  unsigned Idx = 0;
849  for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
850       Idx != NumTemplateIds; ++Idx) {
851    QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
852    bool DependentTemplateId = TemplateId->isDependentType();
853    if (Idx >= NumParamLists) {
854      // We have a template-id without a corresponding template parameter
855      // list.
856      if (DependentTemplateId) {
857        // FIXME: the location information here isn't great.
858        Diag(SS.getRange().getBegin(),
859             diag::err_template_spec_needs_template_parameters)
860          << TemplateId
861          << SS.getRange();
862      } else {
863        Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
864          << SS.getRange()
865          << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
866                                                   "template<> ");
867      }
868      return 0;
869    }
870
871    // Check the template parameter list against its corresponding template-id.
872    if (DependentTemplateId) {
873      TemplateDecl *Template
874        = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
875
876      if (ClassTemplateDecl *ClassTemplate
877            = dyn_cast<ClassTemplateDecl>(Template)) {
878        TemplateParameterList *ExpectedTemplateParams = 0;
879        // Is this template-id naming the primary template?
880        if (Context.hasSameType(TemplateId,
881                             ClassTemplate->getInjectedClassNameType(Context)))
882          ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
883        // ... or a partial specialization?
884        else if (ClassTemplatePartialSpecializationDecl *PartialSpec
885                   = ClassTemplate->findPartialSpecialization(TemplateId))
886          ExpectedTemplateParams = PartialSpec->getTemplateParameters();
887
888        if (ExpectedTemplateParams)
889          TemplateParameterListsAreEqual(ParamLists[Idx],
890                                         ExpectedTemplateParams,
891                                         true);
892      }
893    } else if (ParamLists[Idx]->size() > 0)
894      Diag(ParamLists[Idx]->getTemplateLoc(),
895           diag::err_template_param_list_matches_nontemplate)
896        << TemplateId
897        << ParamLists[Idx]->getSourceRange();
898  }
899
900  // If there were at least as many template-ids as there were template
901  // parameter lists, then there are no template parameter lists remaining for
902  // the declaration itself.
903  if (Idx >= NumParamLists)
904    return 0;
905
906  // If there were too many template parameter lists, complain about that now.
907  if (Idx != NumParamLists - 1) {
908    while (Idx < NumParamLists - 1) {
909      Diag(ParamLists[Idx]->getTemplateLoc(),
910           diag::err_template_spec_extra_headers)
911        << SourceRange(ParamLists[Idx]->getTemplateLoc(),
912                       ParamLists[Idx]->getRAngleLoc());
913      ++Idx;
914    }
915  }
916
917  // Return the last template parameter list, which corresponds to the
918  // entity being declared.
919  return ParamLists[NumParamLists - 1];
920}
921
922/// \brief Translates template arguments as provided by the parser
923/// into template arguments used by semantic analysis.
924static void
925translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
926                           SourceLocation *TemplateArgLocs,
927                     llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
928  TemplateArgs.reserve(TemplateArgsIn.size());
929
930  void **Args = TemplateArgsIn.getArgs();
931  bool *ArgIsType = TemplateArgsIn.getArgIsType();
932  for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
933    TemplateArgs.push_back(
934      ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
935                                       //FIXME: Preserve type source info.
936                                       Sema::GetTypeFromParser(Args[Arg]))
937                    : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
938  }
939}
940
941QualType Sema::CheckTemplateIdType(TemplateName Name,
942                                   SourceLocation TemplateLoc,
943                                   SourceLocation LAngleLoc,
944                                   const TemplateArgument *TemplateArgs,
945                                   unsigned NumTemplateArgs,
946                                   SourceLocation RAngleLoc) {
947  TemplateDecl *Template = Name.getAsTemplateDecl();
948  if (!Template) {
949    // The template name does not resolve to a template, so we just
950    // build a dependent template-id type.
951    return Context.getTemplateSpecializationType(Name, TemplateArgs,
952                                                 NumTemplateArgs);
953  }
954
955  // Check that the template argument list is well-formed for this
956  // template.
957  TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
958                                        NumTemplateArgs);
959  if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
960                                TemplateArgs, NumTemplateArgs, RAngleLoc,
961                                false, Converted))
962    return QualType();
963
964  assert((Converted.structuredSize() ==
965            Template->getTemplateParameters()->size()) &&
966         "Converted template argument list is too short!");
967
968  QualType CanonType;
969
970  if (TemplateSpecializationType::anyDependentTemplateArguments(
971                                                      TemplateArgs,
972                                                      NumTemplateArgs)) {
973    // This class template specialization is a dependent
974    // type. Therefore, its canonical type is another class template
975    // specialization type that contains all of the converted
976    // arguments in canonical form. This ensures that, e.g., A<T> and
977    // A<T, T> have identical types when A is declared as:
978    //
979    //   template<typename T, typename U = T> struct A;
980    TemplateName CanonName = Context.getCanonicalTemplateName(Name);
981    CanonType = Context.getTemplateSpecializationType(CanonName,
982                                                   Converted.getFlatArguments(),
983                                                   Converted.flatSize());
984
985    // FIXME: CanonType is not actually the canonical type, and unfortunately
986    // it is a TemplateTypeSpecializationType that we will never use again.
987    // In the future, we need to teach getTemplateSpecializationType to only
988    // build the canonical type and return that to us.
989    CanonType = Context.getCanonicalType(CanonType);
990  } else if (ClassTemplateDecl *ClassTemplate
991               = dyn_cast<ClassTemplateDecl>(Template)) {
992    // Find the class template specialization declaration that
993    // corresponds to these arguments.
994    llvm::FoldingSetNodeID ID;
995    ClassTemplateSpecializationDecl::Profile(ID,
996                                             Converted.getFlatArguments(),
997                                             Converted.flatSize(),
998                                             Context);
999    void *InsertPos = 0;
1000    ClassTemplateSpecializationDecl *Decl
1001      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1002    if (!Decl) {
1003      // This is the first time we have referenced this class template
1004      // specialization. Create the canonical declaration and add it to
1005      // the set of specializations.
1006      Decl = ClassTemplateSpecializationDecl::Create(Context,
1007                                    ClassTemplate->getDeclContext(),
1008                                    TemplateLoc,
1009                                    ClassTemplate,
1010                                    Converted, 0);
1011      ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1012      Decl->setLexicalDeclContext(CurContext);
1013    }
1014
1015    CanonType = Context.getTypeDeclType(Decl);
1016  }
1017
1018  // Build the fully-sugared type for this class template
1019  // specialization, which refers back to the class template
1020  // specialization we created or found.
1021  //FIXME: Preserve type source info.
1022  return Context.getTemplateSpecializationType(Name, TemplateArgs,
1023                                               NumTemplateArgs, CanonType);
1024}
1025
1026Action::TypeResult
1027Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1028                          SourceLocation LAngleLoc,
1029                          ASTTemplateArgsPtr TemplateArgsIn,
1030                          SourceLocation *TemplateArgLocs,
1031                          SourceLocation RAngleLoc) {
1032  TemplateName Template = TemplateD.getAsVal<TemplateName>();
1033
1034  // Translate the parser's template argument list in our AST format.
1035  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1036  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1037
1038  QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
1039                                        TemplateArgs.data(),
1040                                        TemplateArgs.size(),
1041                                        RAngleLoc);
1042  TemplateArgsIn.release();
1043
1044  if (Result.isNull())
1045    return true;
1046
1047  return Result.getAsOpaquePtr();
1048}
1049
1050Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1051                                                 SourceLocation TemplateNameLoc,
1052                                                 SourceLocation LAngleLoc,
1053                                           const TemplateArgument *TemplateArgs,
1054                                                 unsigned NumTemplateArgs,
1055                                                 SourceLocation RAngleLoc) {
1056  // FIXME: Can we do any checking at this point? I guess we could check the
1057  // template arguments that we have against the template name, if the template
1058  // name refers to a single template. That's not a terribly common case,
1059  // though.
1060  return Owned(TemplateIdRefExpr::Create(Context,
1061                                         /*FIXME: New type?*/Context.OverloadTy,
1062                                         /*FIXME: Necessary?*/0,
1063                                         /*FIXME: Necessary?*/SourceRange(),
1064                                         Template, TemplateNameLoc, LAngleLoc,
1065                                         TemplateArgs,
1066                                         NumTemplateArgs, RAngleLoc));
1067}
1068
1069Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1070                                                 SourceLocation TemplateNameLoc,
1071                                                 SourceLocation LAngleLoc,
1072                                              ASTTemplateArgsPtr TemplateArgsIn,
1073                                                SourceLocation *TemplateArgLocs,
1074                                                 SourceLocation RAngleLoc) {
1075  TemplateName Template = TemplateD.getAsVal<TemplateName>();
1076
1077  // Translate the parser's template argument list in our AST format.
1078  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1079  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1080  TemplateArgsIn.release();
1081
1082  return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1083                             TemplateArgs.data(), TemplateArgs.size(),
1084                             RAngleLoc);
1085}
1086
1087Sema::OwningExprResult
1088Sema::ActOnMemberTemplateIdReferenceExpr(Scope *S, ExprArg Base,
1089                                         SourceLocation OpLoc,
1090                                         tok::TokenKind OpKind,
1091                                         const CXXScopeSpec &SS,
1092                                         TemplateTy TemplateD,
1093                                         SourceLocation TemplateNameLoc,
1094                                         SourceLocation LAngleLoc,
1095                                         ASTTemplateArgsPtr TemplateArgsIn,
1096                                         SourceLocation *TemplateArgLocs,
1097                                         SourceLocation RAngleLoc) {
1098  TemplateName Template = TemplateD.getAsVal<TemplateName>();
1099
1100  // FIXME: We're going to end up looking up the template based on its name,
1101  // twice!
1102  DeclarationName Name;
1103  if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
1104    Name = ActualTemplate->getDeclName();
1105  else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
1106    Name = Ovl->getDeclName();
1107  else
1108    assert(false && "Cannot support dependent template names yet");
1109
1110  // Translate the parser's template argument list in our AST format.
1111  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1112  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1113  TemplateArgsIn.release();
1114
1115  // Do we have the save the actual template name? We might need it...
1116  return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, TemplateNameLoc,
1117                                  Name, true, LAngleLoc,
1118                                  TemplateArgs.data(), TemplateArgs.size(),
1119                                  RAngleLoc, DeclPtrTy(), &SS);
1120}
1121
1122/// \brief Form a dependent template name.
1123///
1124/// This action forms a dependent template name given the template
1125/// name and its (presumably dependent) scope specifier. For
1126/// example, given "MetaFun::template apply", the scope specifier \p
1127/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1128/// of the "template" keyword, and "apply" is the \p Name.
1129Sema::TemplateTy
1130Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1131                                 const IdentifierInfo &Name,
1132                                 SourceLocation NameLoc,
1133                                 const CXXScopeSpec &SS) {
1134  if (!SS.isSet() || SS.isInvalid())
1135    return TemplateTy();
1136
1137  NestedNameSpecifier *Qualifier
1138    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1139
1140  if (computeDeclContext(SS, false)) {
1141    // C++0x [temp.names]p5:
1142    //   If a name prefixed by the keyword template is not the name of
1143    //   a template, the program is ill-formed. [Note: the keyword
1144    //   template may not be applied to non-template members of class
1145    //   templates. -end note ] [ Note: as is the case with the
1146    //   typename prefix, the template prefix is allowed in cases
1147    //   where it is not strictly necessary; i.e., when the
1148    //   nested-name-specifier or the expression on the left of the ->
1149    //   or . is not dependent on a template-parameter, or the use
1150    //   does not appear in the scope of a template. -end note]
1151    //
1152    // Note: C++03 was more strict here, because it banned the use of
1153    // the "template" keyword prior to a template-name that was not a
1154    // dependent name. C++ DR468 relaxed this requirement (the
1155    // "template" keyword is now permitted). We follow the C++0x
1156    // rules, even in C++03 mode, retroactively applying the DR.
1157    TemplateTy Template;
1158    TemplateNameKind TNK = isTemplateName(Name, 0, &SS, false, Template);
1159    if (TNK == TNK_Non_template) {
1160      Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1161        << &Name;
1162      return TemplateTy();
1163    }
1164
1165    return Template;
1166  }
1167
1168  return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1169}
1170
1171bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1172                                     const TemplateArgument &Arg,
1173                                     TemplateArgumentListBuilder &Converted) {
1174  // Check template type parameter.
1175  if (Arg.getKind() != TemplateArgument::Type) {
1176    // C++ [temp.arg.type]p1:
1177    //   A template-argument for a template-parameter which is a
1178    //   type shall be a type-id.
1179
1180    // We have a template type parameter but the template argument
1181    // is not a type.
1182    Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1183    Diag(Param->getLocation(), diag::note_template_param_here);
1184
1185    return true;
1186  }
1187
1188  if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1189    return true;
1190
1191  // Add the converted template type argument.
1192  Converted.Append(
1193                 TemplateArgument(Arg.getLocation(),
1194                                  Context.getCanonicalType(Arg.getAsType())));
1195  return false;
1196}
1197
1198/// \brief Check that the given template argument list is well-formed
1199/// for specializing the given template.
1200bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1201                                     SourceLocation TemplateLoc,
1202                                     SourceLocation LAngleLoc,
1203                                     const TemplateArgument *TemplateArgs,
1204                                     unsigned NumTemplateArgs,
1205                                     SourceLocation RAngleLoc,
1206                                     bool PartialTemplateArgs,
1207                                     TemplateArgumentListBuilder &Converted) {
1208  TemplateParameterList *Params = Template->getTemplateParameters();
1209  unsigned NumParams = Params->size();
1210  unsigned NumArgs = NumTemplateArgs;
1211  bool Invalid = false;
1212
1213  bool HasParameterPack =
1214    NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1215
1216  if ((NumArgs > NumParams && !HasParameterPack) ||
1217      (NumArgs < Params->getMinRequiredArguments() &&
1218       !PartialTemplateArgs)) {
1219    // FIXME: point at either the first arg beyond what we can handle,
1220    // or the '>', depending on whether we have too many or too few
1221    // arguments.
1222    SourceRange Range;
1223    if (NumArgs > NumParams)
1224      Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
1225    Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1226      << (NumArgs > NumParams)
1227      << (isa<ClassTemplateDecl>(Template)? 0 :
1228          isa<FunctionTemplateDecl>(Template)? 1 :
1229          isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1230      << Template << Range;
1231    Diag(Template->getLocation(), diag::note_template_decl_here)
1232      << Params->getSourceRange();
1233    Invalid = true;
1234  }
1235
1236  // C++ [temp.arg]p1:
1237  //   [...] The type and form of each template-argument specified in
1238  //   a template-id shall match the type and form specified for the
1239  //   corresponding parameter declared by the template in its
1240  //   template-parameter-list.
1241  unsigned ArgIdx = 0;
1242  for (TemplateParameterList::iterator Param = Params->begin(),
1243                                       ParamEnd = Params->end();
1244       Param != ParamEnd; ++Param, ++ArgIdx) {
1245    if (ArgIdx > NumArgs && PartialTemplateArgs)
1246      break;
1247
1248    // Decode the template argument
1249    TemplateArgument Arg;
1250    if (ArgIdx >= NumArgs) {
1251      // Retrieve the default template argument from the template
1252      // parameter.
1253      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1254        if (TTP->isParameterPack()) {
1255          // We have an empty argument pack.
1256          Converted.BeginPack();
1257          Converted.EndPack();
1258          break;
1259        }
1260
1261        if (!TTP->hasDefaultArgument())
1262          break;
1263
1264        QualType ArgType = TTP->getDefaultArgument();
1265
1266        // If the argument type is dependent, instantiate it now based
1267        // on the previously-computed template arguments.
1268        if (ArgType->isDependentType()) {
1269          InstantiatingTemplate Inst(*this, TemplateLoc,
1270                                     Template, Converted.getFlatArguments(),
1271                                     Converted.flatSize(),
1272                                     SourceRange(TemplateLoc, RAngleLoc));
1273
1274          TemplateArgumentList TemplateArgs(Context, Converted,
1275                                            /*TakeArgs=*/false);
1276          ArgType = SubstType(ArgType,
1277                              MultiLevelTemplateArgumentList(TemplateArgs),
1278                              TTP->getDefaultArgumentLoc(),
1279                              TTP->getDeclName());
1280        }
1281
1282        if (ArgType.isNull())
1283          return true;
1284
1285        Arg = TemplateArgument(TTP->getLocation(), ArgType);
1286      } else if (NonTypeTemplateParmDecl *NTTP
1287                   = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1288        if (!NTTP->hasDefaultArgument())
1289          break;
1290
1291        InstantiatingTemplate Inst(*this, TemplateLoc,
1292                                   Template, Converted.getFlatArguments(),
1293                                   Converted.flatSize(),
1294                                   SourceRange(TemplateLoc, RAngleLoc));
1295
1296        TemplateArgumentList TemplateArgs(Context, Converted,
1297                                          /*TakeArgs=*/false);
1298
1299        Sema::OwningExprResult E
1300          = SubstExpr(NTTP->getDefaultArgument(),
1301                      MultiLevelTemplateArgumentList(TemplateArgs));
1302        if (E.isInvalid())
1303          return true;
1304
1305        Arg = TemplateArgument(E.takeAs<Expr>());
1306      } else {
1307        TemplateTemplateParmDecl *TempParm
1308          = cast<TemplateTemplateParmDecl>(*Param);
1309
1310        if (!TempParm->hasDefaultArgument())
1311          break;
1312
1313        // FIXME: Subst default argument
1314        Arg = TemplateArgument(TempParm->getDefaultArgument());
1315      }
1316    } else {
1317      // Retrieve the template argument produced by the user.
1318      Arg = TemplateArgs[ArgIdx];
1319    }
1320
1321
1322    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1323      if (TTP->isParameterPack()) {
1324        Converted.BeginPack();
1325        // Check all the remaining arguments (if any).
1326        for (; ArgIdx < NumArgs; ++ArgIdx) {
1327          if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1328            Invalid = true;
1329        }
1330
1331        Converted.EndPack();
1332      } else {
1333        if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1334          Invalid = true;
1335      }
1336    } else if (NonTypeTemplateParmDecl *NTTP
1337                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1338      // Check non-type template parameters.
1339
1340      // Do substitution on the type of the non-type template parameter
1341      // with the template arguments we've seen thus far.
1342      QualType NTTPType = NTTP->getType();
1343      if (NTTPType->isDependentType()) {
1344        // Do substitution on the type of the non-type template parameter.
1345        InstantiatingTemplate Inst(*this, TemplateLoc,
1346                                   Template, Converted.getFlatArguments(),
1347                                   Converted.flatSize(),
1348                                   SourceRange(TemplateLoc, RAngleLoc));
1349
1350        TemplateArgumentList TemplateArgs(Context, Converted,
1351                                          /*TakeArgs=*/false);
1352        NTTPType = SubstType(NTTPType,
1353                             MultiLevelTemplateArgumentList(TemplateArgs),
1354                             NTTP->getLocation(),
1355                             NTTP->getDeclName());
1356        // If that worked, check the non-type template parameter type
1357        // for validity.
1358        if (!NTTPType.isNull())
1359          NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1360                                                       NTTP->getLocation());
1361        if (NTTPType.isNull()) {
1362          Invalid = true;
1363          break;
1364        }
1365      }
1366
1367      switch (Arg.getKind()) {
1368      case TemplateArgument::Null:
1369        assert(false && "Should never see a NULL template argument here");
1370        break;
1371
1372      case TemplateArgument::Expression: {
1373        Expr *E = Arg.getAsExpr();
1374        TemplateArgument Result;
1375        if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1376          Invalid = true;
1377        else
1378          Converted.Append(Result);
1379        break;
1380      }
1381
1382      case TemplateArgument::Declaration:
1383      case TemplateArgument::Integral:
1384        // We've already checked this template argument, so just copy
1385        // it to the list of converted arguments.
1386        Converted.Append(Arg);
1387        break;
1388
1389      case TemplateArgument::Type:
1390        // We have a non-type template parameter but the template
1391        // argument is a type.
1392
1393        // C++ [temp.arg]p2:
1394        //   In a template-argument, an ambiguity between a type-id and
1395        //   an expression is resolved to a type-id, regardless of the
1396        //   form of the corresponding template-parameter.
1397        //
1398        // We warn specifically about this case, since it can be rather
1399        // confusing for users.
1400        if (Arg.getAsType()->isFunctionType())
1401          Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1402            << Arg.getAsType();
1403        else
1404          Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1405        Diag((*Param)->getLocation(), diag::note_template_param_here);
1406        Invalid = true;
1407        break;
1408
1409      case TemplateArgument::Pack:
1410        assert(0 && "FIXME: Implement!");
1411        break;
1412      }
1413    } else {
1414      // Check template template parameters.
1415      TemplateTemplateParmDecl *TempParm
1416        = cast<TemplateTemplateParmDecl>(*Param);
1417
1418      switch (Arg.getKind()) {
1419      case TemplateArgument::Null:
1420        assert(false && "Should never see a NULL template argument here");
1421        break;
1422
1423      case TemplateArgument::Expression: {
1424        Expr *ArgExpr = Arg.getAsExpr();
1425        if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1426            isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1427          if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1428            Invalid = true;
1429
1430          // Add the converted template argument.
1431          Decl *D
1432            = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
1433          Converted.Append(TemplateArgument(Arg.getLocation(), D));
1434          continue;
1435        }
1436      }
1437        // fall through
1438
1439      case TemplateArgument::Type: {
1440        // We have a template template parameter but the template
1441        // argument does not refer to a template.
1442        Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1443        Invalid = true;
1444        break;
1445      }
1446
1447      case TemplateArgument::Declaration:
1448        // We've already checked this template argument, so just copy
1449        // it to the list of converted arguments.
1450        Converted.Append(Arg);
1451        break;
1452
1453      case TemplateArgument::Integral:
1454        assert(false && "Integral argument with template template parameter");
1455        break;
1456
1457      case TemplateArgument::Pack:
1458        assert(0 && "FIXME: Implement!");
1459        break;
1460      }
1461    }
1462  }
1463
1464  return Invalid;
1465}
1466
1467/// \brief Check a template argument against its corresponding
1468/// template type parameter.
1469///
1470/// This routine implements the semantics of C++ [temp.arg.type]. It
1471/// returns true if an error occurred, and false otherwise.
1472bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1473                                 QualType Arg, SourceLocation ArgLoc) {
1474  // C++ [temp.arg.type]p2:
1475  //   A local type, a type with no linkage, an unnamed type or a type
1476  //   compounded from any of these types shall not be used as a
1477  //   template-argument for a template type-parameter.
1478  //
1479  // FIXME: Perform the recursive and no-linkage type checks.
1480  const TagType *Tag = 0;
1481  if (const EnumType *EnumT = Arg->getAsEnumType())
1482    Tag = EnumT;
1483  else if (const RecordType *RecordT = Arg->getAs<RecordType>())
1484    Tag = RecordT;
1485  if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1486    return Diag(ArgLoc, diag::err_template_arg_local_type)
1487      << QualType(Tag, 0);
1488  else if (Tag && !Tag->getDecl()->getDeclName() &&
1489           !Tag->getDecl()->getTypedefForAnonDecl()) {
1490    Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1491    Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1492    return true;
1493  }
1494
1495  return false;
1496}
1497
1498/// \brief Checks whether the given template argument is the address
1499/// of an object or function according to C++ [temp.arg.nontype]p1.
1500bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1501                                                          NamedDecl *&Entity) {
1502  bool Invalid = false;
1503
1504  // See through any implicit casts we added to fix the type.
1505  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1506    Arg = Cast->getSubExpr();
1507
1508  // C++0x allows nullptr, and there's no further checking to be done for that.
1509  if (Arg->getType()->isNullPtrType())
1510    return false;
1511
1512  // C++ [temp.arg.nontype]p1:
1513  //
1514  //   A template-argument for a non-type, non-template
1515  //   template-parameter shall be one of: [...]
1516  //
1517  //     -- the address of an object or function with external
1518  //        linkage, including function templates and function
1519  //        template-ids but excluding non-static class members,
1520  //        expressed as & id-expression where the & is optional if
1521  //        the name refers to a function or array, or if the
1522  //        corresponding template-parameter is a reference; or
1523  DeclRefExpr *DRE = 0;
1524
1525  // Ignore (and complain about) any excess parentheses.
1526  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1527    if (!Invalid) {
1528      Diag(Arg->getSourceRange().getBegin(),
1529           diag::err_template_arg_extra_parens)
1530        << Arg->getSourceRange();
1531      Invalid = true;
1532    }
1533
1534    Arg = Parens->getSubExpr();
1535  }
1536
1537  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1538    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1539      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1540  } else
1541    DRE = dyn_cast<DeclRefExpr>(Arg);
1542
1543  if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1544    return Diag(Arg->getSourceRange().getBegin(),
1545                diag::err_template_arg_not_object_or_func_form)
1546      << Arg->getSourceRange();
1547
1548  // Cannot refer to non-static data members
1549  if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1550    return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1551      << Field << Arg->getSourceRange();
1552
1553  // Cannot refer to non-static member functions
1554  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1555    if (!Method->isStatic())
1556      return Diag(Arg->getSourceRange().getBegin(),
1557                  diag::err_template_arg_method)
1558        << Method << Arg->getSourceRange();
1559
1560  // Functions must have external linkage.
1561  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1562    if (Func->getStorageClass() == FunctionDecl::Static) {
1563      Diag(Arg->getSourceRange().getBegin(),
1564           diag::err_template_arg_function_not_extern)
1565        << Func << Arg->getSourceRange();
1566      Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1567        << true;
1568      return true;
1569    }
1570
1571    // Okay: we've named a function with external linkage.
1572    Entity = Func;
1573    return Invalid;
1574  }
1575
1576  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1577    if (!Var->hasGlobalStorage()) {
1578      Diag(Arg->getSourceRange().getBegin(),
1579           diag::err_template_arg_object_not_extern)
1580        << Var << Arg->getSourceRange();
1581      Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1582        << true;
1583      return true;
1584    }
1585
1586    // Okay: we've named an object with external linkage
1587    Entity = Var;
1588    return Invalid;
1589  }
1590
1591  // We found something else, but we don't know specifically what it is.
1592  Diag(Arg->getSourceRange().getBegin(),
1593       diag::err_template_arg_not_object_or_func)
1594      << Arg->getSourceRange();
1595  Diag(DRE->getDecl()->getLocation(),
1596       diag::note_template_arg_refers_here);
1597  return true;
1598}
1599
1600/// \brief Checks whether the given template argument is a pointer to
1601/// member constant according to C++ [temp.arg.nontype]p1.
1602bool
1603Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
1604  bool Invalid = false;
1605
1606  // See through any implicit casts we added to fix the type.
1607  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1608    Arg = Cast->getSubExpr();
1609
1610  // C++0x allows nullptr, and there's no further checking to be done for that.
1611  if (Arg->getType()->isNullPtrType())
1612    return false;
1613
1614  // C++ [temp.arg.nontype]p1:
1615  //
1616  //   A template-argument for a non-type, non-template
1617  //   template-parameter shall be one of: [...]
1618  //
1619  //     -- a pointer to member expressed as described in 5.3.1.
1620  QualifiedDeclRefExpr *DRE = 0;
1621
1622  // Ignore (and complain about) any excess parentheses.
1623  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1624    if (!Invalid) {
1625      Diag(Arg->getSourceRange().getBegin(),
1626           diag::err_template_arg_extra_parens)
1627        << Arg->getSourceRange();
1628      Invalid = true;
1629    }
1630
1631    Arg = Parens->getSubExpr();
1632  }
1633
1634  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1635    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1636      DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1637
1638  if (!DRE)
1639    return Diag(Arg->getSourceRange().getBegin(),
1640                diag::err_template_arg_not_pointer_to_member_form)
1641      << Arg->getSourceRange();
1642
1643  if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1644    assert((isa<FieldDecl>(DRE->getDecl()) ||
1645            !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1646           "Only non-static member pointers can make it here");
1647
1648    // Okay: this is the address of a non-static member, and therefore
1649    // a member pointer constant.
1650    Member = DRE->getDecl();
1651    return Invalid;
1652  }
1653
1654  // We found something else, but we don't know specifically what it is.
1655  Diag(Arg->getSourceRange().getBegin(),
1656       diag::err_template_arg_not_pointer_to_member_form)
1657      << Arg->getSourceRange();
1658  Diag(DRE->getDecl()->getLocation(),
1659       diag::note_template_arg_refers_here);
1660  return true;
1661}
1662
1663/// \brief Check a template argument against its corresponding
1664/// non-type template parameter.
1665///
1666/// This routine implements the semantics of C++ [temp.arg.nontype].
1667/// It returns true if an error occurred, and false otherwise. \p
1668/// InstantiatedParamType is the type of the non-type template
1669/// parameter after it has been instantiated.
1670///
1671/// If no error was detected, Converted receives the converted template argument.
1672bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
1673                                 QualType InstantiatedParamType, Expr *&Arg,
1674                                 TemplateArgument &Converted) {
1675  SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1676
1677  // If either the parameter has a dependent type or the argument is
1678  // type-dependent, there's nothing we can check now.
1679  // FIXME: Add template argument to Converted!
1680  if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1681    // FIXME: Produce a cloned, canonical expression?
1682    Converted = TemplateArgument(Arg);
1683    return false;
1684  }
1685
1686  // C++ [temp.arg.nontype]p5:
1687  //   The following conversions are performed on each expression used
1688  //   as a non-type template-argument. If a non-type
1689  //   template-argument cannot be converted to the type of the
1690  //   corresponding template-parameter then the program is
1691  //   ill-formed.
1692  //
1693  //     -- for a non-type template-parameter of integral or
1694  //        enumeration type, integral promotions (4.5) and integral
1695  //        conversions (4.7) are applied.
1696  QualType ParamType = InstantiatedParamType;
1697  QualType ArgType = Arg->getType();
1698  if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
1699    // C++ [temp.arg.nontype]p1:
1700    //   A template-argument for a non-type, non-template
1701    //   template-parameter shall be one of:
1702    //
1703    //     -- an integral constant-expression of integral or enumeration
1704    //        type; or
1705    //     -- the name of a non-type template-parameter; or
1706    SourceLocation NonConstantLoc;
1707    llvm::APSInt Value;
1708    if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1709      Diag(Arg->getSourceRange().getBegin(),
1710           diag::err_template_arg_not_integral_or_enumeral)
1711        << ArgType << Arg->getSourceRange();
1712      Diag(Param->getLocation(), diag::note_template_param_here);
1713      return true;
1714    } else if (!Arg->isValueDependent() &&
1715               !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
1716      Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1717        << ArgType << Arg->getSourceRange();
1718      return true;
1719    }
1720
1721    // FIXME: We need some way to more easily get the unqualified form
1722    // of the types without going all the way to the
1723    // canonical type.
1724    if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1725      ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1726    if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1727      ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1728
1729    // Try to convert the argument to the parameter's type.
1730    if (ParamType == ArgType) {
1731      // Okay: no conversion necessary
1732    } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1733               !ParamType->isEnumeralType()) {
1734      // This is an integral promotion or conversion.
1735      ImpCastExprToType(Arg, ParamType);
1736    } else {
1737      // We can't perform this conversion.
1738      Diag(Arg->getSourceRange().getBegin(),
1739           diag::err_template_arg_not_convertible)
1740        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1741      Diag(Param->getLocation(), diag::note_template_param_here);
1742      return true;
1743    }
1744
1745    QualType IntegerType = Context.getCanonicalType(ParamType);
1746    if (const EnumType *Enum = IntegerType->getAsEnumType())
1747      IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
1748
1749    if (!Arg->isValueDependent()) {
1750      // Check that an unsigned parameter does not receive a negative
1751      // value.
1752      if (IntegerType->isUnsignedIntegerType()
1753          && (Value.isSigned() && Value.isNegative())) {
1754        Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1755          << Value.toString(10) << Param->getType()
1756          << Arg->getSourceRange();
1757        Diag(Param->getLocation(), diag::note_template_param_here);
1758        return true;
1759      }
1760
1761      // Check that we don't overflow the template parameter type.
1762      unsigned AllowedBits = Context.getTypeSize(IntegerType);
1763      if (Value.getActiveBits() > AllowedBits) {
1764        Diag(Arg->getSourceRange().getBegin(),
1765             diag::err_template_arg_too_large)
1766          << Value.toString(10) << Param->getType()
1767          << Arg->getSourceRange();
1768        Diag(Param->getLocation(), diag::note_template_param_here);
1769        return true;
1770      }
1771
1772      if (Value.getBitWidth() != AllowedBits)
1773        Value.extOrTrunc(AllowedBits);
1774      Value.setIsSigned(IntegerType->isSignedIntegerType());
1775    }
1776
1777    // Add the value of this argument to the list of converted
1778    // arguments. We use the bitwidth and signedness of the template
1779    // parameter.
1780    if (Arg->isValueDependent()) {
1781      // The argument is value-dependent. Create a new
1782      // TemplateArgument with the converted expression.
1783      Converted = TemplateArgument(Arg);
1784      return false;
1785    }
1786
1787    Converted = TemplateArgument(StartLoc, Value,
1788                                 ParamType->isEnumeralType() ? ParamType
1789                                                             : IntegerType);
1790    return false;
1791  }
1792
1793  // Handle pointer-to-function, reference-to-function, and
1794  // pointer-to-member-function all in (roughly) the same way.
1795  if (// -- For a non-type template-parameter of type pointer to
1796      //    function, only the function-to-pointer conversion (4.3) is
1797      //    applied. If the template-argument represents a set of
1798      //    overloaded functions (or a pointer to such), the matching
1799      //    function is selected from the set (13.4).
1800      // In C++0x, any std::nullptr_t value can be converted.
1801      (ParamType->isPointerType() &&
1802       ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
1803      // -- For a non-type template-parameter of type reference to
1804      //    function, no conversions apply. If the template-argument
1805      //    represents a set of overloaded functions, the matching
1806      //    function is selected from the set (13.4).
1807      (ParamType->isReferenceType() &&
1808       ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
1809      // -- For a non-type template-parameter of type pointer to
1810      //    member function, no conversions apply. If the
1811      //    template-argument represents a set of overloaded member
1812      //    functions, the matching member function is selected from
1813      //    the set (13.4).
1814      // Again, C++0x allows a std::nullptr_t value.
1815      (ParamType->isMemberPointerType() &&
1816       ParamType->getAs<MemberPointerType>()->getPointeeType()
1817         ->isFunctionType())) {
1818    if (Context.hasSameUnqualifiedType(ArgType,
1819                                       ParamType.getNonReferenceType())) {
1820      // We don't have to do anything: the types already match.
1821    } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1822                 ParamType->isMemberPointerType())) {
1823      ArgType = ParamType;
1824      ImpCastExprToType(Arg, ParamType);
1825    } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
1826      ArgType = Context.getPointerType(ArgType);
1827      ImpCastExprToType(Arg, ArgType);
1828    } else if (FunctionDecl *Fn
1829                 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
1830      if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1831        return true;
1832
1833      FixOverloadedFunctionReference(Arg, Fn);
1834      ArgType = Arg->getType();
1835      if (ArgType->isFunctionType() && ParamType->isPointerType()) {
1836        ArgType = Context.getPointerType(Arg->getType());
1837        ImpCastExprToType(Arg, ArgType);
1838      }
1839    }
1840
1841    if (!Context.hasSameUnqualifiedType(ArgType,
1842                                        ParamType.getNonReferenceType())) {
1843      // We can't perform this conversion.
1844      Diag(Arg->getSourceRange().getBegin(),
1845           diag::err_template_arg_not_convertible)
1846        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1847      Diag(Param->getLocation(), diag::note_template_param_here);
1848      return true;
1849    }
1850
1851    if (ParamType->isMemberPointerType()) {
1852      NamedDecl *Member = 0;
1853      if (CheckTemplateArgumentPointerToMember(Arg, Member))
1854        return true;
1855
1856      if (Member)
1857        Member = cast<NamedDecl>(Member->getCanonicalDecl());
1858      Converted = TemplateArgument(StartLoc, Member);
1859      return false;
1860    }
1861
1862    NamedDecl *Entity = 0;
1863    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1864      return true;
1865
1866    if (Entity)
1867      Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
1868    Converted = TemplateArgument(StartLoc, Entity);
1869    return false;
1870  }
1871
1872  if (ParamType->isPointerType()) {
1873    //   -- for a non-type template-parameter of type pointer to
1874    //      object, qualification conversions (4.4) and the
1875    //      array-to-pointer conversion (4.2) are applied.
1876    // C++0x also allows a value of std::nullptr_t.
1877    assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
1878           "Only object pointers allowed here");
1879
1880    if (ArgType->isNullPtrType()) {
1881      ArgType = ParamType;
1882      ImpCastExprToType(Arg, ParamType);
1883    } else if (ArgType->isArrayType()) {
1884      ArgType = Context.getArrayDecayedType(ArgType);
1885      ImpCastExprToType(Arg, ArgType);
1886    }
1887
1888    if (IsQualificationConversion(ArgType, ParamType)) {
1889      ArgType = ParamType;
1890      ImpCastExprToType(Arg, ParamType);
1891    }
1892
1893    if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
1894      // We can't perform this conversion.
1895      Diag(Arg->getSourceRange().getBegin(),
1896           diag::err_template_arg_not_convertible)
1897        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1898      Diag(Param->getLocation(), diag::note_template_param_here);
1899      return true;
1900    }
1901
1902    NamedDecl *Entity = 0;
1903    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1904      return true;
1905
1906    if (Entity)
1907      Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
1908    Converted = TemplateArgument(StartLoc, Entity);
1909    return false;
1910  }
1911
1912  if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
1913    //   -- For a non-type template-parameter of type reference to
1914    //      object, no conversions apply. The type referred to by the
1915    //      reference may be more cv-qualified than the (otherwise
1916    //      identical) type of the template-argument. The
1917    //      template-parameter is bound directly to the
1918    //      template-argument, which must be an lvalue.
1919    assert(ParamRefType->getPointeeType()->isObjectType() &&
1920           "Only object references allowed here");
1921
1922    if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
1923      Diag(Arg->getSourceRange().getBegin(),
1924           diag::err_template_arg_no_ref_bind)
1925        << InstantiatedParamType << Arg->getType()
1926        << Arg->getSourceRange();
1927      Diag(Param->getLocation(), diag::note_template_param_here);
1928      return true;
1929    }
1930
1931    unsigned ParamQuals
1932      = Context.getCanonicalType(ParamType).getCVRQualifiers();
1933    unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1934
1935    if ((ParamQuals | ArgQuals) != ParamQuals) {
1936      Diag(Arg->getSourceRange().getBegin(),
1937           diag::err_template_arg_ref_bind_ignores_quals)
1938        << InstantiatedParamType << Arg->getType()
1939        << Arg->getSourceRange();
1940      Diag(Param->getLocation(), diag::note_template_param_here);
1941      return true;
1942    }
1943
1944    NamedDecl *Entity = 0;
1945    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1946      return true;
1947
1948    Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
1949    Converted = TemplateArgument(StartLoc, Entity);
1950    return false;
1951  }
1952
1953  //     -- For a non-type template-parameter of type pointer to data
1954  //        member, qualification conversions (4.4) are applied.
1955  // C++0x allows std::nullptr_t values.
1956  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1957
1958  if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
1959    // Types match exactly: nothing more to do here.
1960  } else if (ArgType->isNullPtrType()) {
1961    ImpCastExprToType(Arg, ParamType);
1962  } else if (IsQualificationConversion(ArgType, ParamType)) {
1963    ImpCastExprToType(Arg, ParamType);
1964  } else {
1965    // We can't perform this conversion.
1966    Diag(Arg->getSourceRange().getBegin(),
1967         diag::err_template_arg_not_convertible)
1968      << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1969    Diag(Param->getLocation(), diag::note_template_param_here);
1970    return true;
1971  }
1972
1973  NamedDecl *Member = 0;
1974  if (CheckTemplateArgumentPointerToMember(Arg, Member))
1975    return true;
1976
1977  if (Member)
1978    Member = cast<NamedDecl>(Member->getCanonicalDecl());
1979  Converted = TemplateArgument(StartLoc, Member);
1980  return false;
1981}
1982
1983/// \brief Check a template argument against its corresponding
1984/// template template parameter.
1985///
1986/// This routine implements the semantics of C++ [temp.arg.template].
1987/// It returns true if an error occurred, and false otherwise.
1988bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1989                                 DeclRefExpr *Arg) {
1990  assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1991  TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1992
1993  // C++ [temp.arg.template]p1:
1994  //   A template-argument for a template template-parameter shall be
1995  //   the name of a class template, expressed as id-expression. Only
1996  //   primary class templates are considered when matching the
1997  //   template template argument with the corresponding parameter;
1998  //   partial specializations are not considered even if their
1999  //   parameter lists match that of the template template parameter.
2000  //
2001  // Note that we also allow template template parameters here, which
2002  // will happen when we are dealing with, e.g., class template
2003  // partial specializations.
2004  if (!isa<ClassTemplateDecl>(Template) &&
2005      !isa<TemplateTemplateParmDecl>(Template)) {
2006    assert(isa<FunctionTemplateDecl>(Template) &&
2007           "Only function templates are possible here");
2008    Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2009    Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
2010      << Template;
2011  }
2012
2013  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2014                                         Param->getTemplateParameters(),
2015                                         true, true,
2016                                         Arg->getSourceRange().getBegin());
2017}
2018
2019/// \brief Determine whether the given template parameter lists are
2020/// equivalent.
2021///
2022/// \param New  The new template parameter list, typically written in the
2023/// source code as part of a new template declaration.
2024///
2025/// \param Old  The old template parameter list, typically found via
2026/// name lookup of the template declared with this template parameter
2027/// list.
2028///
2029/// \param Complain  If true, this routine will produce a diagnostic if
2030/// the template parameter lists are not equivalent.
2031///
2032/// \param IsTemplateTemplateParm  If true, this routine is being
2033/// called to compare the template parameter lists of a template
2034/// template parameter.
2035///
2036/// \param TemplateArgLoc If this source location is valid, then we
2037/// are actually checking the template parameter list of a template
2038/// argument (New) against the template parameter list of its
2039/// corresponding template template parameter (Old). We produce
2040/// slightly different diagnostics in this scenario.
2041///
2042/// \returns True if the template parameter lists are equal, false
2043/// otherwise.
2044bool
2045Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2046                                     TemplateParameterList *Old,
2047                                     bool Complain,
2048                                     bool IsTemplateTemplateParm,
2049                                     SourceLocation TemplateArgLoc) {
2050  if (Old->size() != New->size()) {
2051    if (Complain) {
2052      unsigned NextDiag = diag::err_template_param_list_different_arity;
2053      if (TemplateArgLoc.isValid()) {
2054        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2055        NextDiag = diag::note_template_param_list_different_arity;
2056      }
2057      Diag(New->getTemplateLoc(), NextDiag)
2058          << (New->size() > Old->size())
2059          << IsTemplateTemplateParm
2060          << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
2061      Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2062        << IsTemplateTemplateParm
2063        << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2064    }
2065
2066    return false;
2067  }
2068
2069  for (TemplateParameterList::iterator OldParm = Old->begin(),
2070         OldParmEnd = Old->end(), NewParm = New->begin();
2071       OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2072    if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
2073      if (Complain) {
2074        unsigned NextDiag = diag::err_template_param_different_kind;
2075        if (TemplateArgLoc.isValid()) {
2076          Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2077          NextDiag = diag::note_template_param_different_kind;
2078        }
2079        Diag((*NewParm)->getLocation(), NextDiag)
2080        << IsTemplateTemplateParm;
2081        Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2082        << IsTemplateTemplateParm;
2083      }
2084      return false;
2085    }
2086
2087    if (isa<TemplateTypeParmDecl>(*OldParm)) {
2088      // Okay; all template type parameters are equivalent (since we
2089      // know we're at the same index).
2090#if 0
2091      // FIXME: Enable this code in debug mode *after* we properly go through
2092      // and "instantiate" the template parameter lists of template template
2093      // parameters. It's only after this instantiation that (1) any dependent
2094      // types within the template parameter list of the template template
2095      // parameter can be checked, and (2) the template type parameter depths
2096      // will match up.
2097      QualType OldParmType
2098        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
2099      QualType NewParmType
2100        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2101      assert(Context.getCanonicalType(OldParmType) ==
2102             Context.getCanonicalType(NewParmType) &&
2103             "type parameter mismatch?");
2104#endif
2105    } else if (NonTypeTemplateParmDecl *OldNTTP
2106                 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2107      // The types of non-type template parameters must agree.
2108      NonTypeTemplateParmDecl *NewNTTP
2109        = cast<NonTypeTemplateParmDecl>(*NewParm);
2110      if (Context.getCanonicalType(OldNTTP->getType()) !=
2111            Context.getCanonicalType(NewNTTP->getType())) {
2112        if (Complain) {
2113          unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2114          if (TemplateArgLoc.isValid()) {
2115            Diag(TemplateArgLoc,
2116                 diag::err_template_arg_template_params_mismatch);
2117            NextDiag = diag::note_template_nontype_parm_different_type;
2118          }
2119          Diag(NewNTTP->getLocation(), NextDiag)
2120            << NewNTTP->getType()
2121            << IsTemplateTemplateParm;
2122          Diag(OldNTTP->getLocation(),
2123               diag::note_template_nontype_parm_prev_declaration)
2124            << OldNTTP->getType();
2125        }
2126        return false;
2127      }
2128    } else {
2129      // The template parameter lists of template template
2130      // parameters must agree.
2131      // FIXME: Could we perform a faster "type" comparison here?
2132      assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2133             "Only template template parameters handled here");
2134      TemplateTemplateParmDecl *OldTTP
2135        = cast<TemplateTemplateParmDecl>(*OldParm);
2136      TemplateTemplateParmDecl *NewTTP
2137        = cast<TemplateTemplateParmDecl>(*NewParm);
2138      if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2139                                          OldTTP->getTemplateParameters(),
2140                                          Complain,
2141                                          /*IsTemplateTemplateParm=*/true,
2142                                          TemplateArgLoc))
2143        return false;
2144    }
2145  }
2146
2147  return true;
2148}
2149
2150/// \brief Check whether a template can be declared within this scope.
2151///
2152/// If the template declaration is valid in this scope, returns
2153/// false. Otherwise, issues a diagnostic and returns true.
2154bool
2155Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
2156  // Find the nearest enclosing declaration scope.
2157  while ((S->getFlags() & Scope::DeclScope) == 0 ||
2158         (S->getFlags() & Scope::TemplateParamScope) != 0)
2159    S = S->getParent();
2160
2161  // C++ [temp]p2:
2162  //   A template-declaration can appear only as a namespace scope or
2163  //   class scope declaration.
2164  DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
2165  if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2166      cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2167    return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
2168             << TemplateParams->getSourceRange();
2169
2170  while (Ctx && isa<LinkageSpecDecl>(Ctx))
2171    Ctx = Ctx->getParent();
2172
2173  if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2174    return false;
2175
2176  return Diag(TemplateParams->getTemplateLoc(),
2177              diag::err_template_outside_namespace_or_class_scope)
2178    << TemplateParams->getSourceRange();
2179}
2180
2181/// \brief Check whether a class template specialization or explicit
2182/// instantiation in the current context is well-formed.
2183///
2184/// This routine determines whether a class template specialization or
2185/// explicit instantiation can be declared in the current context
2186/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2187/// appropriate diagnostics if there was an error. It returns true if
2188// there was an error that we cannot recover from, and false otherwise.
2189bool
2190Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2191                                   ClassTemplateSpecializationDecl *PrevDecl,
2192                                            SourceLocation TemplateNameLoc,
2193                                            SourceRange ScopeSpecifierRange,
2194                                            bool PartialSpecialization,
2195                                            bool ExplicitInstantiation) {
2196  // C++ [temp.expl.spec]p2:
2197  //   An explicit specialization shall be declared in the namespace
2198  //   of which the template is a member, or, for member templates, in
2199  //   the namespace of which the enclosing class or enclosing class
2200  //   template is a member. An explicit specialization of a member
2201  //   function, member class or static data member of a class
2202  //   template shall be declared in the namespace of which the class
2203  //   template is a member. Such a declaration may also be a
2204  //   definition. If the declaration is not a definition, the
2205  //   specialization may be defined later in the name- space in which
2206  //   the explicit specialization was declared, or in a namespace
2207  //   that encloses the one in which the explicit specialization was
2208  //   declared.
2209  if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2210    int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
2211    Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
2212      << Kind << ClassTemplate;
2213    return true;
2214  }
2215
2216  DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2217  DeclContext *TemplateContext
2218    = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
2219  if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2220      !ExplicitInstantiation) {
2221    // There is no prior declaration of this entity, so this
2222    // specialization must be in the same context as the template
2223    // itself.
2224    if (DC != TemplateContext) {
2225      if (isa<TranslationUnitDecl>(TemplateContext))
2226        Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
2227          << PartialSpecialization
2228          << ClassTemplate << ScopeSpecifierRange;
2229      else if (isa<NamespaceDecl>(TemplateContext))
2230        Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
2231          << PartialSpecialization << ClassTemplate
2232          << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2233
2234      Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2235    }
2236
2237    return false;
2238  }
2239
2240  // We have a previous declaration of this entity. Make sure that
2241  // this redeclaration (or definition) occurs in an enclosing namespace.
2242  if (!CurContext->Encloses(TemplateContext)) {
2243    // FIXME:  In C++98,  we  would like  to  turn these  errors into  warnings,
2244    // dependent on a -Wc++0x flag.
2245    bool SuppressedDiag = false;
2246    int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
2247    if (isa<TranslationUnitDecl>(TemplateContext)) {
2248      if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2249        Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
2250          << Kind << ClassTemplate << ScopeSpecifierRange;
2251      else
2252        SuppressedDiag = true;
2253    } else if (isa<NamespaceDecl>(TemplateContext)) {
2254      if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2255        Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
2256          << Kind << ClassTemplate
2257          << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2258      else
2259        SuppressedDiag = true;
2260    }
2261
2262    if (!SuppressedDiag)
2263      Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2264  }
2265
2266  return false;
2267}
2268
2269/// \brief Check the non-type template arguments of a class template
2270/// partial specialization according to C++ [temp.class.spec]p9.
2271///
2272/// \param TemplateParams the template parameters of the primary class
2273/// template.
2274///
2275/// \param TemplateArg the template arguments of the class template
2276/// partial specialization.
2277///
2278/// \param MirrorsPrimaryTemplate will be set true if the class
2279/// template partial specialization arguments are identical to the
2280/// implicit template arguments of the primary template. This is not
2281/// necessarily an error (C++0x), and it is left to the caller to diagnose
2282/// this condition when it is an error.
2283///
2284/// \returns true if there was an error, false otherwise.
2285bool Sema::CheckClassTemplatePartialSpecializationArgs(
2286                                        TemplateParameterList *TemplateParams,
2287                             const TemplateArgumentListBuilder &TemplateArgs,
2288                                        bool &MirrorsPrimaryTemplate) {
2289  // FIXME: the interface to this function will have to change to
2290  // accommodate variadic templates.
2291  MirrorsPrimaryTemplate = true;
2292
2293  const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
2294
2295  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2296    // Determine whether the template argument list of the partial
2297    // specialization is identical to the implicit argument list of
2298    // the primary template. The caller may need to diagnostic this as
2299    // an error per C++ [temp.class.spec]p9b3.
2300    if (MirrorsPrimaryTemplate) {
2301      if (TemplateTypeParmDecl *TTP
2302            = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2303        if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
2304              Context.getCanonicalType(ArgList[I].getAsType()))
2305          MirrorsPrimaryTemplate = false;
2306      } else if (TemplateTemplateParmDecl *TTP
2307                   = dyn_cast<TemplateTemplateParmDecl>(
2308                                                 TemplateParams->getParam(I))) {
2309        // FIXME: We should settle on either Declaration storage or
2310        // Expression storage for template template parameters.
2311        TemplateTemplateParmDecl *ArgDecl
2312          = dyn_cast_or_null<TemplateTemplateParmDecl>(
2313                                                  ArgList[I].getAsDecl());
2314        if (!ArgDecl)
2315          if (DeclRefExpr *DRE
2316                = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
2317            ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2318
2319        if (!ArgDecl ||
2320            ArgDecl->getIndex() != TTP->getIndex() ||
2321            ArgDecl->getDepth() != TTP->getDepth())
2322          MirrorsPrimaryTemplate = false;
2323      }
2324    }
2325
2326    NonTypeTemplateParmDecl *Param
2327      = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
2328    if (!Param) {
2329      continue;
2330    }
2331
2332    Expr *ArgExpr = ArgList[I].getAsExpr();
2333    if (!ArgExpr) {
2334      MirrorsPrimaryTemplate = false;
2335      continue;
2336    }
2337
2338    // C++ [temp.class.spec]p8:
2339    //   A non-type argument is non-specialized if it is the name of a
2340    //   non-type parameter. All other non-type arguments are
2341    //   specialized.
2342    //
2343    // Below, we check the two conditions that only apply to
2344    // specialized non-type arguments, so skip any non-specialized
2345    // arguments.
2346    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
2347      if (NonTypeTemplateParmDecl *NTTP
2348            = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2349        if (MirrorsPrimaryTemplate &&
2350            (Param->getIndex() != NTTP->getIndex() ||
2351             Param->getDepth() != NTTP->getDepth()))
2352          MirrorsPrimaryTemplate = false;
2353
2354        continue;
2355      }
2356
2357    // C++ [temp.class.spec]p9:
2358    //   Within the argument list of a class template partial
2359    //   specialization, the following restrictions apply:
2360    //     -- A partially specialized non-type argument expression
2361    //        shall not involve a template parameter of the partial
2362    //        specialization except when the argument expression is a
2363    //        simple identifier.
2364    if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2365      Diag(ArgExpr->getLocStart(),
2366           diag::err_dependent_non_type_arg_in_partial_spec)
2367        << ArgExpr->getSourceRange();
2368      return true;
2369    }
2370
2371    //     -- The type of a template parameter corresponding to a
2372    //        specialized non-type argument shall not be dependent on a
2373    //        parameter of the specialization.
2374    if (Param->getType()->isDependentType()) {
2375      Diag(ArgExpr->getLocStart(),
2376           diag::err_dependent_typed_non_type_arg_in_partial_spec)
2377        << Param->getType()
2378        << ArgExpr->getSourceRange();
2379      Diag(Param->getLocation(), diag::note_template_param_here);
2380      return true;
2381    }
2382
2383    MirrorsPrimaryTemplate = false;
2384  }
2385
2386  return false;
2387}
2388
2389Sema::DeclResult
2390Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2391                                       TagUseKind TUK,
2392                                       SourceLocation KWLoc,
2393                                       const CXXScopeSpec &SS,
2394                                       TemplateTy TemplateD,
2395                                       SourceLocation TemplateNameLoc,
2396                                       SourceLocation LAngleLoc,
2397                                       ASTTemplateArgsPtr TemplateArgsIn,
2398                                       SourceLocation *TemplateArgLocs,
2399                                       SourceLocation RAngleLoc,
2400                                       AttributeList *Attr,
2401                               MultiTemplateParamsArg TemplateParameterLists) {
2402  // Find the class template we're specializing
2403  TemplateName Name = TemplateD.getAsVal<TemplateName>();
2404  ClassTemplateDecl *ClassTemplate
2405    = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2406
2407  bool isPartialSpecialization = false;
2408
2409  // Check the validity of the template headers that introduce this
2410  // template.
2411  TemplateParameterList *TemplateParams
2412    = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2413                        (TemplateParameterList**)TemplateParameterLists.get(),
2414                                              TemplateParameterLists.size());
2415  if (TemplateParams && TemplateParams->size() > 0) {
2416    isPartialSpecialization = true;
2417
2418    // C++ [temp.class.spec]p10:
2419    //   The template parameter list of a specialization shall not
2420    //   contain default template argument values.
2421    for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2422      Decl *Param = TemplateParams->getParam(I);
2423      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2424        if (TTP->hasDefaultArgument()) {
2425          Diag(TTP->getDefaultArgumentLoc(),
2426               diag::err_default_arg_in_partial_spec);
2427          TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2428        }
2429      } else if (NonTypeTemplateParmDecl *NTTP
2430                   = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2431        if (Expr *DefArg = NTTP->getDefaultArgument()) {
2432          Diag(NTTP->getDefaultArgumentLoc(),
2433               diag::err_default_arg_in_partial_spec)
2434            << DefArg->getSourceRange();
2435          NTTP->setDefaultArgument(0);
2436          DefArg->Destroy(Context);
2437        }
2438      } else {
2439        TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2440        if (Expr *DefArg = TTP->getDefaultArgument()) {
2441          Diag(TTP->getDefaultArgumentLoc(),
2442               diag::err_default_arg_in_partial_spec)
2443            << DefArg->getSourceRange();
2444          TTP->setDefaultArgument(0);
2445          DefArg->Destroy(Context);
2446        }
2447      }
2448    }
2449  } else if (!TemplateParams)
2450    Diag(KWLoc, diag::err_template_spec_needs_header)
2451      << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
2452
2453  // Check that the specialization uses the same tag kind as the
2454  // original template.
2455  TagDecl::TagKind Kind;
2456  switch (TagSpec) {
2457  default: assert(0 && "Unknown tag type!");
2458  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2459  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
2460  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
2461  }
2462  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2463                                    Kind, KWLoc,
2464                                    *ClassTemplate->getIdentifier())) {
2465    Diag(KWLoc, diag::err_use_with_wrong_tag)
2466      << ClassTemplate
2467      << CodeModificationHint::CreateReplacement(KWLoc,
2468                            ClassTemplate->getTemplatedDecl()->getKindName());
2469    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2470         diag::note_previous_use);
2471    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2472  }
2473
2474  // Translate the parser's template argument list in our AST format.
2475  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2476  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2477
2478  // Check that the template argument list is well-formed for this
2479  // template.
2480  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2481                                        TemplateArgs.size());
2482  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
2483                                TemplateArgs.data(), TemplateArgs.size(),
2484                                RAngleLoc, false, Converted))
2485    return true;
2486
2487  assert((Converted.structuredSize() ==
2488            ClassTemplate->getTemplateParameters()->size()) &&
2489         "Converted template argument list is too short!");
2490
2491  // Find the class template (partial) specialization declaration that
2492  // corresponds to these arguments.
2493  llvm::FoldingSetNodeID ID;
2494  if (isPartialSpecialization) {
2495    bool MirrorsPrimaryTemplate;
2496    if (CheckClassTemplatePartialSpecializationArgs(
2497                                         ClassTemplate->getTemplateParameters(),
2498                                         Converted, MirrorsPrimaryTemplate))
2499      return true;
2500
2501    if (MirrorsPrimaryTemplate) {
2502      // C++ [temp.class.spec]p9b3:
2503      //
2504      //   -- The argument list of the specialization shall not be identical
2505      //      to the implicit argument list of the primary template.
2506      Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2507        << (TUK == TUK_Definition)
2508        << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2509                                                           RAngleLoc));
2510      return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
2511                                ClassTemplate->getIdentifier(),
2512                                TemplateNameLoc,
2513                                Attr,
2514                                TemplateParams,
2515                                AS_none);
2516    }
2517
2518    // FIXME: Template parameter list matters, too
2519    ClassTemplatePartialSpecializationDecl::Profile(ID,
2520                                                   Converted.getFlatArguments(),
2521                                                   Converted.flatSize(),
2522                                                    Context);
2523  } else
2524    ClassTemplateSpecializationDecl::Profile(ID,
2525                                             Converted.getFlatArguments(),
2526                                             Converted.flatSize(),
2527                                             Context);
2528  void *InsertPos = 0;
2529  ClassTemplateSpecializationDecl *PrevDecl = 0;
2530
2531  if (isPartialSpecialization)
2532    PrevDecl
2533      = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2534                                                                    InsertPos);
2535  else
2536    PrevDecl
2537      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2538
2539  ClassTemplateSpecializationDecl *Specialization = 0;
2540
2541  // Check whether we can declare a class template specialization in
2542  // the current scope.
2543  if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2544                                            TemplateNameLoc,
2545                                            SS.getRange(),
2546                                            isPartialSpecialization,
2547                                            /*ExplicitInstantiation=*/false))
2548    return true;
2549
2550  // The canonical type
2551  QualType CanonType;
2552  if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2553    // Since the only prior class template specialization with these
2554    // arguments was referenced but not declared, reuse that
2555    // declaration node as our own, updating its source location to
2556    // reflect our new declaration.
2557    Specialization = PrevDecl;
2558    Specialization->setLocation(TemplateNameLoc);
2559    PrevDecl = 0;
2560    CanonType = Context.getTypeDeclType(Specialization);
2561  } else if (isPartialSpecialization) {
2562    // Build the canonical type that describes the converted template
2563    // arguments of the class template partial specialization.
2564    CanonType = Context.getTemplateSpecializationType(
2565                                                  TemplateName(ClassTemplate),
2566                                                  Converted.getFlatArguments(),
2567                                                  Converted.flatSize());
2568
2569    // Create a new class template partial specialization declaration node.
2570    TemplateParameterList *TemplateParams
2571      = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2572    ClassTemplatePartialSpecializationDecl *PrevPartial
2573      = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2574    ClassTemplatePartialSpecializationDecl *Partial
2575      = ClassTemplatePartialSpecializationDecl::Create(Context,
2576                                             ClassTemplate->getDeclContext(),
2577                                                       TemplateNameLoc,
2578                                                       TemplateParams,
2579                                                       ClassTemplate,
2580                                                       Converted,
2581                                                       PrevPartial);
2582
2583    if (PrevPartial) {
2584      ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2585      ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2586    } else {
2587      ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2588    }
2589    Specialization = Partial;
2590
2591    // Check that all of the template parameters of the class template
2592    // partial specialization are deducible from the template
2593    // arguments. If not, this class template partial specialization
2594    // will never be used.
2595    llvm::SmallVector<bool, 8> DeducibleParams;
2596    DeducibleParams.resize(TemplateParams->size());
2597    MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2598    unsigned NumNonDeducible = 0;
2599    for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2600      if (!DeducibleParams[I])
2601        ++NumNonDeducible;
2602
2603    if (NumNonDeducible) {
2604      Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2605        << (NumNonDeducible > 1)
2606        << SourceRange(TemplateNameLoc, RAngleLoc);
2607      for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2608        if (!DeducibleParams[I]) {
2609          NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2610          if (Param->getDeclName())
2611            Diag(Param->getLocation(),
2612                 diag::note_partial_spec_unused_parameter)
2613              << Param->getDeclName();
2614          else
2615            Diag(Param->getLocation(),
2616                 diag::note_partial_spec_unused_parameter)
2617              << std::string("<anonymous>");
2618        }
2619      }
2620    }
2621  } else {
2622    // Create a new class template specialization declaration node for
2623    // this explicit specialization.
2624    Specialization
2625      = ClassTemplateSpecializationDecl::Create(Context,
2626                                             ClassTemplate->getDeclContext(),
2627                                                TemplateNameLoc,
2628                                                ClassTemplate,
2629                                                Converted,
2630                                                PrevDecl);
2631
2632    if (PrevDecl) {
2633      ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2634      ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2635    } else {
2636      ClassTemplate->getSpecializations().InsertNode(Specialization,
2637                                                     InsertPos);
2638    }
2639
2640    CanonType = Context.getTypeDeclType(Specialization);
2641  }
2642
2643  // Note that this is an explicit specialization.
2644  Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2645
2646  // Check that this isn't a redefinition of this specialization.
2647  if (TUK == TUK_Definition) {
2648    if (RecordDecl *Def = Specialization->getDefinition(Context)) {
2649      // FIXME: Should also handle explicit specialization after implicit
2650      // instantiation with a special diagnostic.
2651      SourceRange Range(TemplateNameLoc, RAngleLoc);
2652      Diag(TemplateNameLoc, diag::err_redefinition)
2653        << Context.getTypeDeclType(Specialization) << Range;
2654      Diag(Def->getLocation(), diag::note_previous_definition);
2655      Specialization->setInvalidDecl();
2656      return true;
2657    }
2658  }
2659
2660  // Build the fully-sugared type for this class template
2661  // specialization as the user wrote in the specialization
2662  // itself. This means that we'll pretty-print the type retrieved
2663  // from the specialization's declaration the way that the user
2664  // actually wrote the specialization, rather than formatting the
2665  // name based on the "canonical" representation used to store the
2666  // template arguments in the specialization.
2667  QualType WrittenTy
2668    = Context.getTemplateSpecializationType(Name,
2669                                            TemplateArgs.data(),
2670                                            TemplateArgs.size(),
2671                                            CanonType);
2672  Specialization->setTypeAsWritten(WrittenTy);
2673  TemplateArgsIn.release();
2674
2675  // C++ [temp.expl.spec]p9:
2676  //   A template explicit specialization is in the scope of the
2677  //   namespace in which the template was defined.
2678  //
2679  // We actually implement this paragraph where we set the semantic
2680  // context (in the creation of the ClassTemplateSpecializationDecl),
2681  // but we also maintain the lexical context where the actual
2682  // definition occurs.
2683  Specialization->setLexicalDeclContext(CurContext);
2684
2685  // We may be starting the definition of this specialization.
2686  if (TUK == TUK_Definition)
2687    Specialization->startDefinition();
2688
2689  // Add the specialization into its lexical context, so that it can
2690  // be seen when iterating through the list of declarations in that
2691  // context. However, specializations are not found by name lookup.
2692  CurContext->addDecl(Specialization);
2693  return DeclPtrTy::make(Specialization);
2694}
2695
2696Sema::DeclPtrTy
2697Sema::ActOnTemplateDeclarator(Scope *S,
2698                              MultiTemplateParamsArg TemplateParameterLists,
2699                              Declarator &D) {
2700  return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2701}
2702
2703Sema::DeclPtrTy
2704Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2705                               MultiTemplateParamsArg TemplateParameterLists,
2706                                      Declarator &D) {
2707  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2708  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2709         "Not a function declarator!");
2710  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2711
2712  if (FTI.hasPrototype) {
2713    // FIXME: Diagnose arguments without names in C.
2714  }
2715
2716  Scope *ParentScope = FnBodyScope->getParent();
2717
2718  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2719                                  move(TemplateParameterLists),
2720                                  /*IsFunctionDefinition=*/true);
2721  if (FunctionTemplateDecl *FunctionTemplate
2722        = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
2723    return ActOnStartOfFunctionDef(FnBodyScope,
2724                      DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
2725  if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2726    return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
2727  return DeclPtrTy();
2728}
2729
2730// Explicit instantiation of a class template specialization
2731Sema::DeclResult
2732Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2733                                 unsigned TagSpec,
2734                                 SourceLocation KWLoc,
2735                                 const CXXScopeSpec &SS,
2736                                 TemplateTy TemplateD,
2737                                 SourceLocation TemplateNameLoc,
2738                                 SourceLocation LAngleLoc,
2739                                 ASTTemplateArgsPtr TemplateArgsIn,
2740                                 SourceLocation *TemplateArgLocs,
2741                                 SourceLocation RAngleLoc,
2742                                 AttributeList *Attr) {
2743  // Find the class template we're specializing
2744  TemplateName Name = TemplateD.getAsVal<TemplateName>();
2745  ClassTemplateDecl *ClassTemplate
2746    = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2747
2748  // Check that the specialization uses the same tag kind as the
2749  // original template.
2750  TagDecl::TagKind Kind;
2751  switch (TagSpec) {
2752  default: assert(0 && "Unknown tag type!");
2753  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2754  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
2755  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
2756  }
2757  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2758                                    Kind, KWLoc,
2759                                    *ClassTemplate->getIdentifier())) {
2760    Diag(KWLoc, diag::err_use_with_wrong_tag)
2761      << ClassTemplate
2762      << CodeModificationHint::CreateReplacement(KWLoc,
2763                            ClassTemplate->getTemplatedDecl()->getKindName());
2764    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2765         diag::note_previous_use);
2766    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2767  }
2768
2769  // C++0x [temp.explicit]p2:
2770  //   [...] An explicit instantiation shall appear in an enclosing
2771  //   namespace of its template. [...]
2772  //
2773  // This is C++ DR 275.
2774  if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2775                                            TemplateNameLoc,
2776                                            SS.getRange(),
2777                                            /*PartialSpecialization=*/false,
2778                                            /*ExplicitInstantiation=*/true))
2779    return true;
2780
2781  // Translate the parser's template argument list in our AST format.
2782  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2783  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2784
2785  // Check that the template argument list is well-formed for this
2786  // template.
2787  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2788                                        TemplateArgs.size());
2789  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
2790                                TemplateArgs.data(), TemplateArgs.size(),
2791                                RAngleLoc, false, Converted))
2792    return true;
2793
2794  assert((Converted.structuredSize() ==
2795            ClassTemplate->getTemplateParameters()->size()) &&
2796         "Converted template argument list is too short!");
2797
2798  // Find the class template specialization declaration that
2799  // corresponds to these arguments.
2800  llvm::FoldingSetNodeID ID;
2801  ClassTemplateSpecializationDecl::Profile(ID,
2802                                           Converted.getFlatArguments(),
2803                                           Converted.flatSize(),
2804                                           Context);
2805  void *InsertPos = 0;
2806  ClassTemplateSpecializationDecl *PrevDecl
2807    = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2808
2809  ClassTemplateSpecializationDecl *Specialization = 0;
2810
2811  bool SpecializationRequiresInstantiation = true;
2812  if (PrevDecl) {
2813    if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
2814      // This particular specialization has already been declared or
2815      // instantiated. We cannot explicitly instantiate it.
2816      Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2817        << Context.getTypeDeclType(PrevDecl);
2818      Diag(PrevDecl->getLocation(),
2819           diag::note_previous_explicit_instantiation);
2820      return DeclPtrTy::make(PrevDecl);
2821    }
2822
2823    if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
2824      // C++ DR 259, C++0x [temp.explicit]p4:
2825      //   For a given set of template parameters, if an explicit
2826      //   instantiation of a template appears after a declaration of
2827      //   an explicit specialization for that template, the explicit
2828      //   instantiation has no effect.
2829      if (!getLangOptions().CPlusPlus0x) {
2830        Diag(TemplateNameLoc,
2831             diag::ext_explicit_instantiation_after_specialization)
2832          << Context.getTypeDeclType(PrevDecl);
2833        Diag(PrevDecl->getLocation(),
2834             diag::note_previous_template_specialization);
2835      }
2836
2837      // Create a new class template specialization declaration node
2838      // for this explicit specialization. This node is only used to
2839      // record the existence of this explicit instantiation for
2840      // accurate reproduction of the source code; we don't actually
2841      // use it for anything, since it is semantically irrelevant.
2842      Specialization
2843        = ClassTemplateSpecializationDecl::Create(Context,
2844                                             ClassTemplate->getDeclContext(),
2845                                                  TemplateNameLoc,
2846                                                  ClassTemplate,
2847                                                  Converted, 0);
2848      Specialization->setLexicalDeclContext(CurContext);
2849      CurContext->addDecl(Specialization);
2850      return DeclPtrTy::make(Specialization);
2851    }
2852
2853    // If we have already (implicitly) instantiated this
2854    // specialization, there is less work to do.
2855    if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2856      SpecializationRequiresInstantiation = false;
2857
2858    // Since the only prior class template specialization with these
2859    // arguments was referenced but not declared, reuse that
2860    // declaration node as our own, updating its source location to
2861    // reflect our new declaration.
2862    Specialization = PrevDecl;
2863    Specialization->setLocation(TemplateNameLoc);
2864    PrevDecl = 0;
2865  } else {
2866    // Create a new class template specialization declaration node for
2867    // this explicit specialization.
2868    Specialization
2869      = ClassTemplateSpecializationDecl::Create(Context,
2870                                             ClassTemplate->getDeclContext(),
2871                                                TemplateNameLoc,
2872                                                ClassTemplate,
2873                                                Converted, 0);
2874
2875    ClassTemplate->getSpecializations().InsertNode(Specialization,
2876                                                   InsertPos);
2877  }
2878
2879  // Build the fully-sugared type for this explicit instantiation as
2880  // the user wrote in the explicit instantiation itself. This means
2881  // that we'll pretty-print the type retrieved from the
2882  // specialization's declaration the way that the user actually wrote
2883  // the explicit instantiation, rather than formatting the name based
2884  // on the "canonical" representation used to store the template
2885  // arguments in the specialization.
2886  QualType WrittenTy
2887    = Context.getTemplateSpecializationType(Name,
2888                                            TemplateArgs.data(),
2889                                            TemplateArgs.size(),
2890                                  Context.getTypeDeclType(Specialization));
2891  Specialization->setTypeAsWritten(WrittenTy);
2892  TemplateArgsIn.release();
2893
2894  // Add the explicit instantiation into its lexical context. However,
2895  // since explicit instantiations are never found by name lookup, we
2896  // just put it into the declaration context directly.
2897  Specialization->setLexicalDeclContext(CurContext);
2898  CurContext->addDecl(Specialization);
2899
2900  // C++ [temp.explicit]p3:
2901  //   A definition of a class template or class member template
2902  //   shall be in scope at the point of the explicit instantiation of
2903  //   the class template or class member template.
2904  //
2905  // This check comes when we actually try to perform the
2906  // instantiation.
2907  if (SpecializationRequiresInstantiation)
2908    InstantiateClassTemplateSpecialization(Specialization, true);
2909  else // Instantiate the members of this class template specialization.
2910    InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
2911
2912  return DeclPtrTy::make(Specialization);
2913}
2914
2915// Explicit instantiation of a member class of a class template.
2916Sema::DeclResult
2917Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2918                                 unsigned TagSpec,
2919                                 SourceLocation KWLoc,
2920                                 const CXXScopeSpec &SS,
2921                                 IdentifierInfo *Name,
2922                                 SourceLocation NameLoc,
2923                                 AttributeList *Attr) {
2924
2925  bool Owned = false;
2926  DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
2927                            KWLoc, SS, Name, NameLoc, Attr, AS_none,
2928                            MultiTemplateParamsArg(*this, 0, 0), Owned);
2929  if (!TagD)
2930    return true;
2931
2932  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2933  if (Tag->isEnum()) {
2934    Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2935      << Context.getTypeDeclType(Tag);
2936    return true;
2937  }
2938
2939  if (Tag->isInvalidDecl())
2940    return true;
2941
2942  CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2943  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2944  if (!Pattern) {
2945    Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2946      << Context.getTypeDeclType(Record);
2947    Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2948    return true;
2949  }
2950
2951  // C++0x [temp.explicit]p2:
2952  //   [...] An explicit instantiation shall appear in an enclosing
2953  //   namespace of its template. [...]
2954  //
2955  // This is C++ DR 275.
2956  if (getLangOptions().CPlusPlus0x) {
2957    // FIXME: In C++98, we would like to turn these errors into warnings,
2958    // dependent on a -Wc++0x flag.
2959    DeclContext *PatternContext
2960      = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2961    if (!CurContext->Encloses(PatternContext)) {
2962      Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2963        << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2964      Diag(Pattern->getLocation(), diag::note_previous_declaration);
2965    }
2966  }
2967
2968  if (!Record->getDefinition(Context)) {
2969    // If the class has a definition, instantiate it (and all of its
2970    // members, recursively).
2971    Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2972    if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
2973                                    getTemplateInstantiationArgs(Record),
2974                                    /*ExplicitInstantiation=*/true))
2975      return true;
2976  } else // Instantiate all of the members of the class.
2977    InstantiateClassMembers(TemplateLoc, Record,
2978                            getTemplateInstantiationArgs(Record));
2979
2980  // FIXME: We don't have any representation for explicit instantiations of
2981  // member classes. Such a representation is not needed for compilation, but it
2982  // should be available for clients that want to see all of the declarations in
2983  // the source code.
2984  return TagD;
2985}
2986
2987Sema::TypeResult
2988Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2989                        const IdentifierInfo &II, SourceLocation IdLoc) {
2990  NestedNameSpecifier *NNS
2991    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2992  if (!NNS)
2993    return true;
2994
2995  QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
2996  if (T.isNull())
2997    return true;
2998  return T.getAsOpaquePtr();
2999}
3000
3001Sema::TypeResult
3002Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3003                        SourceLocation TemplateLoc, TypeTy *Ty) {
3004  QualType T = GetTypeFromParser(Ty);
3005  NestedNameSpecifier *NNS
3006    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3007  const TemplateSpecializationType *TemplateId
3008    = T->getAsTemplateSpecializationType();
3009  assert(TemplateId && "Expected a template specialization type");
3010
3011  if (computeDeclContext(SS, false)) {
3012    // If we can compute a declaration context, then the "typename"
3013    // keyword was superfluous. Just build a QualifiedNameType to keep
3014    // track of the nested-name-specifier.
3015
3016    // FIXME: Note that the QualifiedNameType had the "typename" keyword!
3017    return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
3018  }
3019
3020  return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
3021}
3022
3023/// \brief Build the type that describes a C++ typename specifier,
3024/// e.g., "typename T::type".
3025QualType
3026Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
3027                        SourceRange Range) {
3028  CXXRecordDecl *CurrentInstantiation = 0;
3029  if (NNS->isDependent()) {
3030    CurrentInstantiation = getCurrentInstantiationOf(NNS);
3031
3032    // If the nested-name-specifier does not refer to the current
3033    // instantiation, then build a typename type.
3034    if (!CurrentInstantiation)
3035      return Context.getTypenameType(NNS, &II);
3036  }
3037
3038  DeclContext *Ctx = 0;
3039
3040  if (CurrentInstantiation)
3041    Ctx = CurrentInstantiation;
3042  else {
3043    CXXScopeSpec SS;
3044    SS.setScopeRep(NNS);
3045    SS.setRange(Range);
3046    if (RequireCompleteDeclContext(SS))
3047      return QualType();
3048
3049    Ctx = computeDeclContext(SS);
3050  }
3051  assert(Ctx && "No declaration context?");
3052
3053  DeclarationName Name(&II);
3054  LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
3055                                            false);
3056  unsigned DiagID = 0;
3057  Decl *Referenced = 0;
3058  switch (Result.getKind()) {
3059  case LookupResult::NotFound:
3060    if (Ctx->isTranslationUnit())
3061      DiagID = diag::err_typename_nested_not_found_global;
3062    else
3063      DiagID = diag::err_typename_nested_not_found;
3064    break;
3065
3066  case LookupResult::Found:
3067    if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3068      // We found a type. Build a QualifiedNameType, since the
3069      // typename-specifier was just sugar. FIXME: Tell
3070      // QualifiedNameType that it has a "typename" prefix.
3071      return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3072    }
3073
3074    DiagID = diag::err_typename_nested_not_type;
3075    Referenced = Result.getAsDecl();
3076    break;
3077
3078  case LookupResult::FoundOverloaded:
3079    DiagID = diag::err_typename_nested_not_type;
3080    Referenced = *Result.begin();
3081    break;
3082
3083  case LookupResult::AmbiguousBaseSubobjectTypes:
3084  case LookupResult::AmbiguousBaseSubobjects:
3085  case LookupResult::AmbiguousReference:
3086    DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3087    return QualType();
3088  }
3089
3090  // If we get here, it's because name lookup did not find a
3091  // type. Emit an appropriate diagnostic and return an error.
3092  if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3093    Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3094  else
3095    Diag(Range.getEnd(), DiagID) << Range << Name;
3096  if (Referenced)
3097    Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3098      << Name;
3099  return QualType();
3100}
3101
3102namespace {
3103  // See Sema::RebuildTypeInCurrentInstantiation
3104  class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3105    : public TreeTransform<CurrentInstantiationRebuilder>
3106  {
3107    SourceLocation Loc;
3108    DeclarationName Entity;
3109
3110  public:
3111    CurrentInstantiationRebuilder(Sema &SemaRef,
3112                                  SourceLocation Loc,
3113                                  DeclarationName Entity)
3114    : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
3115      Loc(Loc), Entity(Entity) { }
3116
3117    /// \brief Determine whether the given type \p T has already been
3118    /// transformed.
3119    ///
3120    /// For the purposes of type reconstruction, a type has already been
3121    /// transformed if it is NULL or if it is not dependent.
3122    bool AlreadyTransformed(QualType T) {
3123      return T.isNull() || !T->isDependentType();
3124    }
3125
3126    /// \brief Returns the location of the entity whose type is being
3127    /// rebuilt.
3128    SourceLocation getBaseLocation() { return Loc; }
3129
3130    /// \brief Returns the name of the entity whose type is being rebuilt.
3131    DeclarationName getBaseEntity() { return Entity; }
3132
3133    /// \brief Transforms an expression by returning the expression itself
3134    /// (an identity function).
3135    ///
3136    /// FIXME: This is completely unsafe; we will need to actually clone the
3137    /// expressions.
3138    Sema::OwningExprResult TransformExpr(Expr *E) {
3139      return getSema().Owned(E);
3140    }
3141
3142    /// \brief Transforms a typename type by determining whether the type now
3143    /// refers to a member of the current instantiation, and then
3144    /// type-checking and building a QualifiedNameType (when possible).
3145    QualType TransformTypenameType(const TypenameType *T);
3146  };
3147}
3148
3149QualType
3150CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3151  NestedNameSpecifier *NNS
3152    = TransformNestedNameSpecifier(T->getQualifier(),
3153                              /*FIXME:*/SourceRange(getBaseLocation()));
3154  if (!NNS)
3155    return QualType();
3156
3157  // If the nested-name-specifier did not change, and we cannot compute the
3158  // context corresponding to the nested-name-specifier, then this
3159  // typename type will not change; exit early.
3160  CXXScopeSpec SS;
3161  SS.setRange(SourceRange(getBaseLocation()));
3162  SS.setScopeRep(NNS);
3163  if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3164    return QualType(T, 0);
3165
3166  // Rebuild the typename type, which will probably turn into a
3167  // QualifiedNameType.
3168  if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
3169    QualType NewTemplateId
3170      = TransformType(QualType(TemplateId, 0));
3171    if (NewTemplateId.isNull())
3172      return QualType();
3173
3174    if (NNS == T->getQualifier() &&
3175        NewTemplateId == QualType(TemplateId, 0))
3176      return QualType(T, 0);
3177
3178    return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3179  }
3180
3181  return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3182}
3183
3184/// \brief Rebuilds a type within the context of the current instantiation.
3185///
3186/// The type \p T is part of the type of an out-of-line member definition of
3187/// a class template (or class template partial specialization) that was parsed
3188/// and constructed before we entered the scope of the class template (or
3189/// partial specialization thereof). This routine will rebuild that type now
3190/// that we have entered the declarator's scope, which may produce different
3191/// canonical types, e.g.,
3192///
3193/// \code
3194/// template<typename T>
3195/// struct X {
3196///   typedef T* pointer;
3197///   pointer data();
3198/// };
3199///
3200/// template<typename T>
3201/// typename X<T>::pointer X<T>::data() { ... }
3202/// \endcode
3203///
3204/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3205/// since we do not know that we can look into X<T> when we parsed the type.
3206/// This function will rebuild the type, performing the lookup of "pointer"
3207/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3208/// as the canonical type of T*, allowing the return types of the out-of-line
3209/// definition and the declaration to match.
3210QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3211                                                 DeclarationName Name) {
3212  if (T.isNull() || !T->isDependentType())
3213    return T;
3214
3215  CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3216  return Rebuilder.TransformType(T);
3217}
3218