SemaTemplate.cpp revision 9c7825b737617339724d43bd04960852271f08e2
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4//                     The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
8//+//===----------------------------------------------------------------------===/
9
10//
11//  This file implements semantic analysis for C++ templates.
12//+//===----------------------------------------------------------------------===/
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.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(IdentifierInfo &II, Scope *S,
30                                      DeclTy *&Template,
31                                      const CXXScopeSpec *SS) {
32  NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
33
34  if (IIDecl) {
35    if (isa<TemplateDecl>(IIDecl)) {
36      Template = IIDecl;
37      if (isa<FunctionTemplateDecl>(IIDecl))
38        return TNK_Function_template;
39      else if (isa<ClassTemplateDecl>(IIDecl))
40        return TNK_Class_template;
41      else if (isa<TemplateTemplateParmDecl>(IIDecl))
42        return TNK_Template_template_parm;
43      else
44        assert(false && "Unknown TemplateDecl");
45    }
46
47    // FIXME: What follows is a gross hack.
48    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
49      if (FD->getType()->isDependentType()) {
50        Template = FD;
51        return TNK_Function_template;
52      }
53    } else if (OverloadedFunctionDecl *Ovl
54                 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
55      for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
56                                                  FEnd = Ovl->function_end();
57           F != FEnd; ++F) {
58        if ((*F)->getType()->isDependentType()) {
59          Template = Ovl;
60          return TNK_Function_template;
61        }
62      }
63    }
64  }
65  return TNK_Non_template;
66}
67
68/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
69/// that the template parameter 'PrevDecl' is being shadowed by a new
70/// declaration at location Loc. Returns true to indicate that this is
71/// an error, and false otherwise.
72bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
73  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
74
75  // Microsoft Visual C++ permits template parameters to be shadowed.
76  if (getLangOptions().Microsoft)
77    return false;
78
79  // C++ [temp.local]p4:
80  //   A template-parameter shall not be redeclared within its
81  //   scope (including nested scopes).
82  Diag(Loc, diag::err_template_param_shadow)
83    << cast<NamedDecl>(PrevDecl)->getDeclName();
84  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
85  return true;
86}
87
88/// AdjustDeclForTemplates - If the given decl happens to be a template, reset
89/// the parameter D to reference the templated declaration and return a pointer
90/// to the template declaration. Otherwise, do nothing to D and return null.
91TemplateDecl *Sema::AdjustDeclIfTemplate(DeclTy *&D)
92{
93  if(TemplateDecl *Temp = dyn_cast<TemplateDecl>(static_cast<Decl*>(D))) {
94    D = Temp->getTemplatedDecl();
95    return Temp;
96  }
97  return 0;
98}
99
100/// ActOnTypeParameter - Called when a C++ template type parameter
101/// (e.g., "typename T") has been parsed. Typename specifies whether
102/// the keyword "typename" was used to declare the type parameter
103/// (otherwise, "class" was used), and KeyLoc is the location of the
104/// "class" or "typename" keyword. ParamName is the name of the
105/// parameter (NULL indicates an unnamed template parameter) and
106/// ParamName is the location of the parameter name (if any).
107/// If the type parameter has a default argument, it will be added
108/// later via ActOnTypeParameterDefault.
109Sema::DeclTy *Sema::ActOnTypeParameter(Scope *S, bool Typename,
110				       SourceLocation KeyLoc,
111				       IdentifierInfo *ParamName,
112				       SourceLocation ParamNameLoc,
113                                       unsigned Depth, unsigned Position) {
114  assert(S->isTemplateParamScope() &&
115	 "Template type parameter not in template parameter scope!");
116  bool Invalid = false;
117
118  if (ParamName) {
119    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
120    if (PrevDecl && PrevDecl->isTemplateParameter())
121      Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
122							   PrevDecl);
123  }
124
125  SourceLocation Loc = ParamNameLoc;
126  if (!ParamName)
127    Loc = KeyLoc;
128
129  TemplateTypeParmDecl *Param
130    = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
131                                   Depth, Position, ParamName, Typename);
132  if (Invalid)
133    Param->setInvalidDecl();
134
135  if (ParamName) {
136    // Add the template parameter into the current scope.
137    S->AddDecl(Param);
138    IdResolver.AddDecl(Param);
139  }
140
141  return Param;
142}
143
144/// ActOnTypeParameterDefault - Adds a default argument (the type
145/// Default) to the given template type parameter (TypeParam).
146void Sema::ActOnTypeParameterDefault(DeclTy *TypeParam,
147                                     SourceLocation EqualLoc,
148                                     SourceLocation DefaultLoc,
149                                     TypeTy *DefaultT) {
150  TemplateTypeParmDecl *Parm
151    = cast<TemplateTypeParmDecl>(static_cast<Decl *>(TypeParam));
152  QualType Default = QualType::getFromOpaquePtr(DefaultT);
153
154  // C++ [temp.param]p14:
155  //   A template-parameter shall not be used in its own default argument.
156  // FIXME: Implement this check! Needs a recursive walk over the types.
157
158  // Check the template argument itself.
159  if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
160    Parm->setInvalidDecl();
161    return;
162  }
163
164  Parm->setDefaultArgument(Default, DefaultLoc, false);
165}
166
167/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
168/// template parameter (e.g., "int Size" in "template<int Size>
169/// class Array") has been parsed. S is the current scope and D is
170/// the parsed declarator.
171Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
172                                                  unsigned Depth,
173                                                  unsigned Position) {
174  QualType T = GetTypeForDeclarator(D, S);
175
176  assert(S->isTemplateParamScope() &&
177         "Non-type template parameter not in template parameter scope!");
178  bool Invalid = false;
179
180  IdentifierInfo *ParamName = D.getIdentifier();
181  if (ParamName) {
182    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
183    if (PrevDecl && PrevDecl->isTemplateParameter())
184      Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
185                                                           PrevDecl);
186  }
187
188  // C++ [temp.param]p4:
189  //
190  // A non-type template-parameter shall have one of the following
191  // (optionally cv-qualified) types:
192  //
193  //       -- integral or enumeration type,
194  if (T->isIntegralType() || T->isEnumeralType() ||
195      //   -- pointer to object or pointer to function,
196      (T->isPointerType() &&
197       (T->getAsPointerType()->getPointeeType()->isObjectType() ||
198        T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
199      //   -- reference to object or reference to function,
200      T->isReferenceType() ||
201      //   -- pointer to member.
202      T->isMemberPointerType() ||
203      // If T is a dependent type, we can't do the check now, so we
204      // assume that it is well-formed.
205      T->isDependentType()) {
206    // Okay: The template parameter is well-formed.
207  }
208  // C++ [temp.param]p8:
209  //
210  //   A non-type template-parameter of type "array of T" or
211  //   "function returning T" is adjusted to be of type "pointer to
212  //   T" or "pointer to function returning T", respectively.
213  else if (T->isArrayType())
214    // FIXME: Keep the type prior to promotion?
215    T = Context.getArrayDecayedType(T);
216  else if (T->isFunctionType())
217    // FIXME: Keep the type prior to promotion?
218    T = Context.getPointerType(T);
219  else {
220    Diag(D.getIdentifierLoc(), diag::err_template_nontype_parm_bad_type)
221      << T;
222    return 0;
223  }
224
225  NonTypeTemplateParmDecl *Param
226    = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
227                                      Depth, Position, ParamName, T);
228  if (Invalid)
229    Param->setInvalidDecl();
230
231  if (D.getIdentifier()) {
232    // Add the template parameter into the current scope.
233    S->AddDecl(Param);
234    IdResolver.AddDecl(Param);
235  }
236  return Param;
237}
238
239/// \brief Adds a default argument to the given non-type template
240/// parameter.
241void Sema::ActOnNonTypeTemplateParameterDefault(DeclTy *TemplateParamD,
242                                                SourceLocation EqualLoc,
243                                                ExprArg DefaultE) {
244  NonTypeTemplateParmDecl *TemplateParm
245    = cast<NonTypeTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
246  Expr *Default = static_cast<Expr *>(DefaultE.get());
247
248  // C++ [temp.param]p14:
249  //   A template-parameter shall not be used in its own default argument.
250  // FIXME: Implement this check! Needs a recursive walk over the types.
251
252  // Check the well-formedness of the default template argument.
253  if (CheckTemplateArgument(TemplateParm, Default)) {
254    TemplateParm->setInvalidDecl();
255    return;
256  }
257
258  TemplateParm->setDefaultArgument(static_cast<Expr *>(DefaultE.release()));
259}
260
261
262/// ActOnTemplateTemplateParameter - Called when a C++ template template
263/// parameter (e.g. T in template <template <typename> class T> class array)
264/// has been parsed. S is the current scope.
265Sema::DeclTy *Sema::ActOnTemplateTemplateParameter(Scope* S,
266                                                   SourceLocation TmpLoc,
267                                                   TemplateParamsTy *Params,
268                                                   IdentifierInfo *Name,
269                                                   SourceLocation NameLoc,
270                                                   unsigned Depth,
271                                                   unsigned Position)
272{
273  assert(S->isTemplateParamScope() &&
274         "Template template parameter not in template parameter scope!");
275
276  // Construct the parameter object.
277  TemplateTemplateParmDecl *Param =
278    TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
279                                     Position, Name,
280                                     (TemplateParameterList*)Params);
281
282  // Make sure the parameter is valid.
283  // FIXME: Decl object is not currently invalidated anywhere so this doesn't
284  // do anything yet. However, if the template parameter list or (eventual)
285  // default value is ever invalidated, that will propagate here.
286  bool Invalid = false;
287  if (Invalid) {
288    Param->setInvalidDecl();
289  }
290
291  // If the tt-param has a name, then link the identifier into the scope
292  // and lookup mechanisms.
293  if (Name) {
294    S->AddDecl(Param);
295    IdResolver.AddDecl(Param);
296  }
297
298  return Param;
299}
300
301/// \brief Adds a default argument to the given template template
302/// parameter.
303void Sema::ActOnTemplateTemplateParameterDefault(DeclTy *TemplateParamD,
304                                                 SourceLocation EqualLoc,
305                                                 ExprArg DefaultE) {
306  TemplateTemplateParmDecl *TemplateParm
307    = cast<TemplateTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
308
309  // Since a template-template parameter's default argument is an
310  // id-expression, it must be a DeclRefExpr.
311  DeclRefExpr *Default
312    = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
313
314  // C++ [temp.param]p14:
315  //   A template-parameter shall not be used in its own default argument.
316  // FIXME: Implement this check! Needs a recursive walk over the types.
317
318  // Check the well-formedness of the template argument.
319  if (!isa<TemplateDecl>(Default->getDecl())) {
320    Diag(Default->getSourceRange().getBegin(),
321         diag::err_template_arg_must_be_template)
322      << Default->getSourceRange();
323    TemplateParm->setInvalidDecl();
324    return;
325  }
326  if (CheckTemplateArgument(TemplateParm, Default)) {
327    TemplateParm->setInvalidDecl();
328    return;
329  }
330
331  DefaultE.release();
332  TemplateParm->setDefaultArgument(Default);
333}
334
335/// ActOnTemplateParameterList - Builds a TemplateParameterList that
336/// contains the template parameters in Params/NumParams.
337Sema::TemplateParamsTy *
338Sema::ActOnTemplateParameterList(unsigned Depth,
339                                 SourceLocation ExportLoc,
340                                 SourceLocation TemplateLoc,
341                                 SourceLocation LAngleLoc,
342                                 DeclTy **Params, unsigned NumParams,
343                                 SourceLocation RAngleLoc) {
344  if (ExportLoc.isValid())
345    Diag(ExportLoc, diag::note_template_export_unsupported);
346
347  return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
348                                       (Decl**)Params, NumParams, RAngleLoc);
349}
350
351Sema::DeclTy *
352Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
353                         SourceLocation KWLoc, const CXXScopeSpec &SS,
354                         IdentifierInfo *Name, SourceLocation NameLoc,
355                         AttributeList *Attr,
356                         MultiTemplateParamsArg TemplateParameterLists) {
357  assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
358  assert(TK != TK_Reference && "Can only declare or define class templates");
359  bool Invalid = false;
360
361  // Check that we can declare a template here.
362  if (CheckTemplateDeclScope(S, TemplateParameterLists))
363    return 0;
364
365  TagDecl::TagKind Kind;
366  switch (TagSpec) {
367  default: assert(0 && "Unknown tag type!");
368  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
369  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
370  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
371  }
372
373  // There is no such thing as an unnamed class template.
374  if (!Name) {
375    Diag(KWLoc, diag::err_template_unnamed_class);
376    return 0;
377  }
378
379  // Find any previous declaration with this name.
380  LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
381                                           true);
382  assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
383  NamedDecl *PrevDecl = 0;
384  if (Previous.begin() != Previous.end())
385    PrevDecl = *Previous.begin();
386
387  DeclContext *SemanticContext = CurContext;
388  if (SS.isNotEmpty() && !SS.isInvalid()) {
389    SemanticContext = static_cast<DeclContext*>(SS.getScopeRep());
390
391    // FIXME: need to match up several levels of template parameter
392    // lists here.
393  }
394
395  // FIXME: member templates!
396  TemplateParameterList *TemplateParams
397    = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
398
399  // If there is a previous declaration with the same name, check
400  // whether this is a valid redeclaration.
401  ClassTemplateDecl *PrevClassTemplate
402    = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
403  if (PrevClassTemplate) {
404    // Ensure that the template parameter lists are compatible.
405    if (!TemplateParameterListsAreEqual(TemplateParams,
406                                   PrevClassTemplate->getTemplateParameters(),
407                                        /*Complain=*/true))
408      return 0;
409
410    // C++ [temp.class]p4:
411    //   In a redeclaration, partial specialization, explicit
412    //   specialization or explicit instantiation of a class template,
413    //   the class-key shall agree in kind with the original class
414    //   template declaration (7.1.5.3).
415    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
416    if (PrevRecordDecl->getTagKind() != Kind) {
417      Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
418      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
419      return 0;
420    }
421
422
423    // Check for redefinition of this class template.
424    if (TK == TK_Definition) {
425      if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
426        Diag(NameLoc, diag::err_redefinition) << Name;
427        Diag(Def->getLocation(), diag::note_previous_definition);
428        // FIXME: Would it make sense to try to "forget" the previous
429        // definition, as part of error recovery?
430        return 0;
431      }
432    }
433  } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
434    // Maybe we will complain about the shadowed template parameter.
435    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
436    // Just pretend that we didn't see the previous declaration.
437    PrevDecl = 0;
438  } else if (PrevDecl) {
439    // C++ [temp]p5:
440    //   A class template shall not have the same name as any other
441    //   template, class, function, object, enumeration, enumerator,
442    //   namespace, or type in the same scope (3.3), except as specified
443    //   in (14.5.4).
444    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
445    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
446    return 0;
447  }
448
449  // Check the template parameter list of this declaration, possibly
450  // merging in the template parameter list from the previous class
451  // template declaration.
452  if (CheckTemplateParameterList(TemplateParams,
453            PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
454    Invalid = true;
455
456  // If we had a scope specifier, we better have a previous template
457  // declaration!
458
459  TagDecl *NewClass =
460    CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
461                          PrevClassTemplate?
462                            PrevClassTemplate->getTemplatedDecl() : 0);
463
464  ClassTemplateDecl *NewTemplate
465    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
466                                DeclarationName(Name), TemplateParams,
467                                NewClass);
468
469  // Set the lexical context of these templates
470  NewClass->setLexicalDeclContext(CurContext);
471  NewTemplate->setLexicalDeclContext(CurContext);
472
473  if (TK == TK_Definition)
474    NewClass->startDefinition();
475
476  if (Attr)
477    ProcessDeclAttributeList(NewClass, Attr);
478
479  PushOnScopeChains(NewTemplate, S);
480
481  if (Invalid) {
482    NewTemplate->setInvalidDecl();
483    NewClass->setInvalidDecl();
484  }
485  return NewTemplate;
486}
487
488/// \brief Checks the validity of a template parameter list, possibly
489/// considering the template parameter list from a previous
490/// declaration.
491///
492/// If an "old" template parameter list is provided, it must be
493/// equivalent (per TemplateParameterListsAreEqual) to the "new"
494/// template parameter list.
495///
496/// \param NewParams Template parameter list for a new template
497/// declaration. This template parameter list will be updated with any
498/// default arguments that are carried through from the previous
499/// template parameter list.
500///
501/// \param OldParams If provided, template parameter list from a
502/// previous declaration of the same template. Default template
503/// arguments will be merged from the old template parameter list to
504/// the new template parameter list.
505///
506/// \returns true if an error occurred, false otherwise.
507bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
508                                      TemplateParameterList *OldParams) {
509  bool Invalid = false;
510
511  // C++ [temp.param]p10:
512  //   The set of default template-arguments available for use with a
513  //   template declaration or definition is obtained by merging the
514  //   default arguments from the definition (if in scope) and all
515  //   declarations in scope in the same way default function
516  //   arguments are (8.3.6).
517  bool SawDefaultArgument = false;
518  SourceLocation PreviousDefaultArgLoc;
519
520  // Dummy initialization to avoid warnings.
521  TemplateParameterList::iterator OldParam = NewParams->end();
522  if (OldParams)
523    OldParam = OldParams->begin();
524
525  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
526                                    NewParamEnd = NewParams->end();
527       NewParam != NewParamEnd; ++NewParam) {
528    // Variables used to diagnose redundant default arguments
529    bool RedundantDefaultArg = false;
530    SourceLocation OldDefaultLoc;
531    SourceLocation NewDefaultLoc;
532
533    // Variables used to diagnose missing default arguments
534    bool MissingDefaultArg = false;
535
536    // Merge default arguments for template type parameters.
537    if (TemplateTypeParmDecl *NewTypeParm
538          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
539      TemplateTypeParmDecl *OldTypeParm
540          = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
541
542      if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
543          NewTypeParm->hasDefaultArgument()) {
544        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
545        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
546        SawDefaultArgument = true;
547        RedundantDefaultArg = true;
548        PreviousDefaultArgLoc = NewDefaultLoc;
549      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
550        // Merge the default argument from the old declaration to the
551        // new declaration.
552        SawDefaultArgument = true;
553        NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
554                                        OldTypeParm->getDefaultArgumentLoc(),
555                                        true);
556        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
557      } else if (NewTypeParm->hasDefaultArgument()) {
558        SawDefaultArgument = true;
559        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
560      } else if (SawDefaultArgument)
561        MissingDefaultArg = true;
562    }
563    // Merge default arguments for non-type template parameters
564    else if (NonTypeTemplateParmDecl *NewNonTypeParm
565               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
566      NonTypeTemplateParmDecl *OldNonTypeParm
567        = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
568      if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
569          NewNonTypeParm->hasDefaultArgument()) {
570        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
571        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
572        SawDefaultArgument = true;
573        RedundantDefaultArg = true;
574        PreviousDefaultArgLoc = NewDefaultLoc;
575      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
576        // Merge the default argument from the old declaration to the
577        // new declaration.
578        SawDefaultArgument = true;
579        // FIXME: We need to create a new kind of "default argument"
580        // expression that points to a previous template template
581        // parameter.
582        NewNonTypeParm->setDefaultArgument(
583                                        OldNonTypeParm->getDefaultArgument());
584        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
585      } else if (NewNonTypeParm->hasDefaultArgument()) {
586        SawDefaultArgument = true;
587        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
588      } else if (SawDefaultArgument)
589        MissingDefaultArg = true;
590    }
591    // Merge default arguments for template template parameters
592    else {
593      TemplateTemplateParmDecl *NewTemplateParm
594        = cast<TemplateTemplateParmDecl>(*NewParam);
595      TemplateTemplateParmDecl *OldTemplateParm
596        = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
597      if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
598          NewTemplateParm->hasDefaultArgument()) {
599        OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
600        NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
601        SawDefaultArgument = true;
602        RedundantDefaultArg = true;
603        PreviousDefaultArgLoc = NewDefaultLoc;
604      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
605        // Merge the default argument from the old declaration to the
606        // new declaration.
607        SawDefaultArgument = true;
608        // FIXME: We need to create a new kind of "default argument"
609        // expression that points to a previous template template
610        // parameter.
611        NewTemplateParm->setDefaultArgument(
612                                        OldTemplateParm->getDefaultArgument());
613        PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
614      } else if (NewTemplateParm->hasDefaultArgument()) {
615        SawDefaultArgument = true;
616        PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
617      } else if (SawDefaultArgument)
618        MissingDefaultArg = true;
619    }
620
621    if (RedundantDefaultArg) {
622      // C++ [temp.param]p12:
623      //   A template-parameter shall not be given default arguments
624      //   by two different declarations in the same scope.
625      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
626      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
627      Invalid = true;
628    } else if (MissingDefaultArg) {
629      // C++ [temp.param]p11:
630      //   If a template-parameter has a default template-argument,
631      //   all subsequent template-parameters shall have a default
632      //   template-argument supplied.
633      Diag((*NewParam)->getLocation(),
634           diag::err_template_param_default_arg_missing);
635      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
636      Invalid = true;
637    }
638
639    // If we have an old template parameter list that we're merging
640    // in, move on to the next parameter.
641    if (OldParams)
642      ++OldParam;
643  }
644
645  return Invalid;
646}
647
648Action::TypeResult
649Sema::ActOnClassTemplateId(DeclTy *TemplateD, SourceLocation TemplateLoc,
650                           SourceLocation LAngleLoc,
651                           ASTTemplateArgsPtr TemplateArgs,
652                           SourceLocation *TemplateArgLocs,
653                           SourceLocation RAngleLoc,
654                           const CXXScopeSpec *SS) {
655  TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
656  ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(Template);
657
658  // Check that the template argument list is well-formed for this
659  // template.
660  llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
661  if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
662                                TemplateArgs, TemplateArgLocs, RAngleLoc,
663                                ConvertedTemplateArgs))
664    return true;
665
666  assert((ConvertedTemplateArgs.size() ==
667            Template->getTemplateParameters()->size()) &&
668         "Converted template argument list is too short!");
669
670  // Find the class template specialization declaration that
671  // corresponds to these arguments.
672  llvm::FoldingSetNodeID ID;
673  ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
674                                           ConvertedTemplateArgs.size());
675  void *InsertPos = 0;
676  ClassTemplateSpecializationDecl *Decl
677    = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
678  if (!Decl) {
679    // This is the first time we have referenced this class template
680    // specialization. Create the canonical declaration and add it to
681    // the set of specializations.
682    Decl = ClassTemplateSpecializationDecl::Create(Context,
683                                           ClassTemplate->getDeclContext(),
684                                                   TemplateLoc,
685                                                   ClassTemplate,
686                                                   &ConvertedTemplateArgs[0],
687                                                ConvertedTemplateArgs.size(),
688                                                   0);
689    ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
690    Decl->setLexicalDeclContext(CurContext);
691  }
692
693  // Build the fully-sugared type for this class template
694  // specialization, which refers back to the class template
695  // specialization we created or found.
696  QualType Result
697    = Context.getClassTemplateSpecializationType(Template,
698                                                 TemplateArgs.size(),
699                    reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
700                                                 TemplateArgs.getArgIsType(),
701                                               Context.getTypeDeclType(Decl));
702  TemplateArgs.release();
703  return Result.getAsOpaquePtr();
704}
705
706/// \brief Check that the given template argument list is well-formed
707/// for specializing the given template.
708bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
709                                     SourceLocation TemplateLoc,
710                                     SourceLocation LAngleLoc,
711                                     ASTTemplateArgsPtr& Args,
712                                     SourceLocation *TemplateArgLocs,
713                                     SourceLocation RAngleLoc,
714                          llvm::SmallVectorImpl<TemplateArgument> &Converted) {
715  TemplateParameterList *Params = Template->getTemplateParameters();
716  unsigned NumParams = Params->size();
717  unsigned NumArgs = Args.size();
718  bool Invalid = false;
719
720  if (NumArgs > NumParams ||
721      NumArgs < Params->getMinRequiredArguments()) {
722    // FIXME: point at either the first arg beyond what we can handle,
723    // or the '>', depending on whether we have too many or too few
724    // arguments.
725    SourceRange Range;
726    if (NumArgs > NumParams)
727      Range = SourceRange(TemplateArgLocs[NumParams], RAngleLoc);
728    Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
729      << (NumArgs > NumParams)
730      << (isa<ClassTemplateDecl>(Template)? 0 :
731          isa<FunctionTemplateDecl>(Template)? 1 :
732          isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
733      << Template << Range;
734    Diag(Template->getLocation(), diag::note_template_decl_here)
735      << Params->getSourceRange();
736    Invalid = true;
737  }
738
739  // C++ [temp.arg]p1:
740  //   [...] The type and form of each template-argument specified in
741  //   a template-id shall match the type and form specified for the
742  //   corresponding parameter declared by the template in its
743  //   template-parameter-list.
744  unsigned ArgIdx = 0;
745  for (TemplateParameterList::iterator Param = Params->begin(),
746                                       ParamEnd = Params->end();
747       Param != ParamEnd; ++Param, ++ArgIdx) {
748    // Decode the template argument
749    QualType ArgType;
750    Expr *ArgExpr = 0;
751    SourceLocation ArgLoc;
752    if (ArgIdx >= NumArgs) {
753      // Retrieve the default template argument from the template
754      // parameter.
755      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
756        if (!TTP->hasDefaultArgument())
757          break;
758
759        ArgType = TTP->getDefaultArgument();
760        ArgLoc = TTP->getDefaultArgumentLoc();
761      } else if (NonTypeTemplateParmDecl *NTTP
762                   = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
763        if (!NTTP->hasDefaultArgument())
764          break;
765
766        ArgExpr = NTTP->getDefaultArgument();
767        ArgLoc = NTTP->getDefaultArgumentLoc();
768      } else {
769        TemplateTemplateParmDecl *TempParm
770          = cast<TemplateTemplateParmDecl>(*Param);
771
772        if (!TempParm->hasDefaultArgument())
773          break;
774
775        ArgExpr = TempParm->getDefaultArgument();
776        ArgLoc = TempParm->getDefaultArgumentLoc();
777      }
778    } else {
779      // Retrieve the template argument produced by the user.
780      ArgLoc = TemplateArgLocs[ArgIdx];
781
782      if (Args.getArgIsType()[ArgIdx])
783        ArgType = QualType::getFromOpaquePtr(Args.getArgs()[ArgIdx]);
784      else
785        ArgExpr = reinterpret_cast<Expr *>(Args.getArgs()[ArgIdx]);
786    }
787
788
789    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
790      // Check template type parameters.
791      if (!ArgType.isNull()) {
792        if (CheckTemplateArgument(TTP, ArgType, ArgLoc))
793          Invalid = true;
794
795        // Add the converted template type argument.
796        Converted.push_back(
797                      TemplateArgument(Context.getCanonicalType(ArgType)));
798        continue;
799      }
800
801      // C++ [temp.arg.type]p1:
802      //   A template-argument for a template-parameter which is a
803      //   type shall be a type-id.
804
805      // We have a template type parameter but the template argument
806      // is an expression.
807      Diag(ArgExpr->getSourceRange().getBegin(),
808           diag::err_template_arg_must_be_type);
809      Diag((*Param)->getLocation(), diag::note_template_param_here);
810      Invalid = true;
811    } else if (NonTypeTemplateParmDecl *NTTP
812                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
813      // Check non-type template parameters.
814      if (ArgExpr) {
815        if (CheckTemplateArgument(NTTP, ArgExpr, &Converted))
816          Invalid = true;
817        continue;
818      }
819
820      // We have a non-type template parameter but the template
821      // argument is a type.
822
823      // C++ [temp.arg]p2:
824      //   In a template-argument, an ambiguity between a type-id and
825      //   an expression is resolved to a type-id, regardless of the
826      //   form of the corresponding template-parameter.
827      //
828      // We warn specifically about this case, since it can be rather
829      // confusing for users.
830      if (ArgType->isFunctionType())
831        Diag(ArgLoc, diag::err_template_arg_nontype_ambig)
832          << ArgType;
833      else
834        Diag(ArgLoc, diag::err_template_arg_must_be_expr);
835      Diag((*Param)->getLocation(), diag::note_template_param_here);
836      Invalid = true;
837    } else {
838      // Check template template parameters.
839      TemplateTemplateParmDecl *TempParm
840        = cast<TemplateTemplateParmDecl>(*Param);
841
842      if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
843          isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
844        if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
845          Invalid = true;
846
847        // Add the converted template argument.
848        // FIXME: Need the "canonical" template declaration!
849        Converted.push_back(
850                   TemplateArgument(cast<DeclRefExpr>(ArgExpr)->getDecl()));
851        continue;
852      }
853
854      // We have a template template parameter but the template
855      // argument does not refer to a template.
856      Diag(ArgLoc, diag::err_template_arg_must_be_template);
857      Invalid = true;
858    }
859  }
860
861  return Invalid;
862}
863
864/// \brief Check a template argument against its corresponding
865/// template type parameter.
866///
867/// This routine implements the semantics of C++ [temp.arg.type]. It
868/// returns true if an error occurred, and false otherwise.
869bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
870                                 QualType Arg, SourceLocation ArgLoc) {
871  // C++ [temp.arg.type]p2:
872  //   A local type, a type with no linkage, an unnamed type or a type
873  //   compounded from any of these types shall not be used as a
874  //   template-argument for a template type-parameter.
875  //
876  // FIXME: Perform the recursive and no-linkage type checks.
877  const TagType *Tag = 0;
878  if (const EnumType *EnumT = Arg->getAsEnumType())
879    Tag = EnumT;
880  else if (const RecordType *RecordT = Arg->getAsRecordType())
881    Tag = RecordT;
882  if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
883    return Diag(ArgLoc, diag::err_template_arg_local_type)
884      << QualType(Tag, 0);
885  else if (Tag && !Tag->getDecl()->getDeclName()) {
886    Diag(ArgLoc, diag::err_template_arg_unnamed_type);
887    Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
888    return true;
889  }
890
891  return false;
892}
893
894/// \brief Checks whether the given template argument is the address
895/// of an object or function according to C++ [temp.arg.nontype]p1.
896bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
897                                                          NamedDecl *&Entity) {
898  bool Invalid = false;
899
900  // See through any implicit casts we added to fix the type.
901  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
902    Arg = Cast->getSubExpr();
903
904  // C++ [temp.arg.nontype]p1:
905  //
906  //   A template-argument for a non-type, non-template
907  //   template-parameter shall be one of: [...]
908  //
909  //     -- the address of an object or function with external
910  //        linkage, including function templates and function
911  //        template-ids but excluding non-static class members,
912  //        expressed as & id-expression where the & is optional if
913  //        the name refers to a function or array, or if the
914  //        corresponding template-parameter is a reference; or
915  DeclRefExpr *DRE = 0;
916
917  // Ignore (and complain about) any excess parentheses.
918  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
919    if (!Invalid) {
920      Diag(Arg->getSourceRange().getBegin(),
921           diag::err_template_arg_extra_parens)
922        << Arg->getSourceRange();
923      Invalid = true;
924    }
925
926    Arg = Parens->getSubExpr();
927  }
928
929  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
930    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
931      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
932  } else
933    DRE = dyn_cast<DeclRefExpr>(Arg);
934
935  if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
936    return Diag(Arg->getSourceRange().getBegin(),
937                diag::err_template_arg_not_object_or_func_form)
938      << Arg->getSourceRange();
939
940  // Cannot refer to non-static data members
941  if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
942    return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
943      << Field << Arg->getSourceRange();
944
945  // Cannot refer to non-static member functions
946  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
947    if (!Method->isStatic())
948      return Diag(Arg->getSourceRange().getBegin(),
949                  diag::err_template_arg_method)
950        << Method << Arg->getSourceRange();
951
952  // Functions must have external linkage.
953  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
954    if (Func->getStorageClass() == FunctionDecl::Static) {
955      Diag(Arg->getSourceRange().getBegin(),
956           diag::err_template_arg_function_not_extern)
957        << Func << Arg->getSourceRange();
958      Diag(Func->getLocation(), diag::note_template_arg_internal_object)
959        << true;
960      return true;
961    }
962
963    // Okay: we've named a function with external linkage.
964    Entity = Func;
965    return Invalid;
966  }
967
968  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
969    if (!Var->hasGlobalStorage()) {
970      Diag(Arg->getSourceRange().getBegin(),
971           diag::err_template_arg_object_not_extern)
972        << Var << Arg->getSourceRange();
973      Diag(Var->getLocation(), diag::note_template_arg_internal_object)
974        << true;
975      return true;
976    }
977
978    // Okay: we've named an object with external linkage
979    Entity = Var;
980    return Invalid;
981  }
982
983  // We found something else, but we don't know specifically what it is.
984  Diag(Arg->getSourceRange().getBegin(),
985       diag::err_template_arg_not_object_or_func)
986      << Arg->getSourceRange();
987  Diag(DRE->getDecl()->getLocation(),
988       diag::note_template_arg_refers_here);
989  return true;
990}
991
992/// \brief Checks whether the given template argument is a pointer to
993/// member constant according to C++ [temp.arg.nontype]p1.
994bool
995Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
996  bool Invalid = false;
997
998  // See through any implicit casts we added to fix the type.
999  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1000    Arg = Cast->getSubExpr();
1001
1002  // C++ [temp.arg.nontype]p1:
1003  //
1004  //   A template-argument for a non-type, non-template
1005  //   template-parameter shall be one of: [...]
1006  //
1007  //     -- a pointer to member expressed as described in 5.3.1.
1008  QualifiedDeclRefExpr *DRE = 0;
1009
1010  // Ignore (and complain about) any excess parentheses.
1011  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1012    if (!Invalid) {
1013      Diag(Arg->getSourceRange().getBegin(),
1014           diag::err_template_arg_extra_parens)
1015        << Arg->getSourceRange();
1016      Invalid = true;
1017    }
1018
1019    Arg = Parens->getSubExpr();
1020  }
1021
1022  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1023    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1024      DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1025
1026  if (!DRE)
1027    return Diag(Arg->getSourceRange().getBegin(),
1028                diag::err_template_arg_not_pointer_to_member_form)
1029      << Arg->getSourceRange();
1030
1031  if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1032    assert((isa<FieldDecl>(DRE->getDecl()) ||
1033            !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1034           "Only non-static member pointers can make it here");
1035
1036    // Okay: this is the address of a non-static member, and therefore
1037    // a member pointer constant.
1038    Member = DRE->getDecl();
1039    return Invalid;
1040  }
1041
1042  // We found something else, but we don't know specifically what it is.
1043  Diag(Arg->getSourceRange().getBegin(),
1044       diag::err_template_arg_not_pointer_to_member_form)
1045      << Arg->getSourceRange();
1046  Diag(DRE->getDecl()->getLocation(),
1047       diag::note_template_arg_refers_here);
1048  return true;
1049}
1050
1051/// \brief Check a template argument against its corresponding
1052/// non-type template parameter.
1053///
1054/// This routine implements the semantics of C++ [temp.arg.nontype].
1055/// It returns true if an error occurred, and false otherwise.
1056///
1057/// If Converted is non-NULL and no errors occur, the value
1058/// of this argument will be added to the end of the Converted vector.
1059bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
1060                                 Expr *&Arg,
1061                         llvm::SmallVectorImpl<TemplateArgument> *Converted) {
1062  // If either the parameter has a dependent type or the argument is
1063  // type-dependent, there's nothing we can check now.
1064  // FIXME: Add template argument to Converted!
1065  if (Param->getType()->isDependentType() || Arg->isTypeDependent())
1066    return false;
1067
1068  // C++ [temp.arg.nontype]p5:
1069  //   The following conversions are performed on each expression used
1070  //   as a non-type template-argument. If a non-type
1071  //   template-argument cannot be converted to the type of the
1072  //   corresponding template-parameter then the program is
1073  //   ill-formed.
1074  //
1075  //     -- for a non-type template-parameter of integral or
1076  //        enumeration type, integral promotions (4.5) and integral
1077  //        conversions (4.7) are applied.
1078  QualType ParamType = Param->getType();
1079  QualType ArgType = Arg->getType();
1080  if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
1081    // C++ [temp.arg.nontype]p1:
1082    //   A template-argument for a non-type, non-template
1083    //   template-parameter shall be one of:
1084    //
1085    //     -- an integral constant-expression of integral or enumeration
1086    //        type; or
1087    //     -- the name of a non-type template-parameter; or
1088    SourceLocation NonConstantLoc;
1089    llvm::APSInt Value;
1090    if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1091      Diag(Arg->getSourceRange().getBegin(),
1092           diag::err_template_arg_not_integral_or_enumeral)
1093        << ArgType << Arg->getSourceRange();
1094      Diag(Param->getLocation(), diag::note_template_param_here);
1095      return true;
1096    } else if (!Arg->isValueDependent() &&
1097               !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
1098      Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1099        << ArgType << Arg->getSourceRange();
1100      return true;
1101    }
1102
1103    // FIXME: We need some way to more easily get the unqualified form
1104    // of the types without going all the way to the
1105    // canonical type.
1106    if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1107      ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1108    if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1109      ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1110
1111    // Try to convert the argument to the parameter's type.
1112    if (ParamType == ArgType) {
1113      // Okay: no conversion necessary
1114    } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1115               !ParamType->isEnumeralType()) {
1116      // This is an integral promotion or conversion.
1117      ImpCastExprToType(Arg, ParamType);
1118    } else {
1119      // We can't perform this conversion.
1120      Diag(Arg->getSourceRange().getBegin(),
1121           diag::err_template_arg_not_convertible)
1122        << Arg->getType() << Param->getType() << Arg->getSourceRange();
1123      Diag(Param->getLocation(), diag::note_template_param_here);
1124      return true;
1125    }
1126
1127    // FIXME: Check overflow of template arguments?
1128
1129    if (Converted) {
1130      // Add the value of this argument to the list of converted
1131      // arguments. We use the bitwidth and signedness of the template
1132      // parameter.
1133      QualType IntegerType = Context.getCanonicalType(ParamType);
1134      if (const EnumType *Enum = IntegerType->getAsEnumType())
1135        IntegerType = Enum->getDecl()->getIntegerType();
1136
1137      llvm::APInt CanonicalArg(Context.getTypeSize(IntegerType), 0,
1138                               IntegerType->isSignedIntegerType());
1139      CanonicalArg = Value;
1140
1141      Converted->push_back(TemplateArgument(CanonicalArg));
1142    }
1143
1144    return false;
1145  }
1146
1147  // Handle pointer-to-function, reference-to-function, and
1148  // pointer-to-member-function all in (roughly) the same way.
1149  if (// -- For a non-type template-parameter of type pointer to
1150      //    function, only the function-to-pointer conversion (4.3) is
1151      //    applied. If the template-argument represents a set of
1152      //    overloaded functions (or a pointer to such), the matching
1153      //    function is selected from the set (13.4).
1154      (ParamType->isPointerType() &&
1155       ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1156      // -- For a non-type template-parameter of type reference to
1157      //    function, no conversions apply. If the template-argument
1158      //    represents a set of overloaded functions, the matching
1159      //    function is selected from the set (13.4).
1160      (ParamType->isReferenceType() &&
1161       ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1162      // -- For a non-type template-parameter of type pointer to
1163      //    member function, no conversions apply. If the
1164      //    template-argument represents a set of overloaded member
1165      //    functions, the matching member function is selected from
1166      //    the set (13.4).
1167      (ParamType->isMemberPointerType() &&
1168       ParamType->getAsMemberPointerType()->getPointeeType()
1169         ->isFunctionType())) {
1170    if (Context.hasSameUnqualifiedType(ArgType,
1171                                       ParamType.getNonReferenceType())) {
1172      // We don't have to do anything: the types already match.
1173    } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
1174      ArgType = Context.getPointerType(ArgType);
1175      ImpCastExprToType(Arg, ArgType);
1176    } else if (FunctionDecl *Fn
1177                 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
1178      if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1179        return true;
1180
1181      FixOverloadedFunctionReference(Arg, Fn);
1182      ArgType = Arg->getType();
1183      if (ArgType->isFunctionType() && ParamType->isPointerType()) {
1184        ArgType = Context.getPointerType(Arg->getType());
1185        ImpCastExprToType(Arg, ArgType);
1186      }
1187    }
1188
1189    if (!Context.hasSameUnqualifiedType(ArgType,
1190                                        ParamType.getNonReferenceType())) {
1191      // We can't perform this conversion.
1192      Diag(Arg->getSourceRange().getBegin(),
1193           diag::err_template_arg_not_convertible)
1194        << Arg->getType() << Param->getType() << Arg->getSourceRange();
1195      Diag(Param->getLocation(), diag::note_template_param_here);
1196      return true;
1197    }
1198
1199    if (ParamType->isMemberPointerType()) {
1200      NamedDecl *Member = 0;
1201      if (CheckTemplateArgumentPointerToMember(Arg, Member))
1202        return true;
1203
1204      if (Converted)
1205        Converted->push_back(TemplateArgument(Member));
1206
1207      return false;
1208    }
1209
1210    NamedDecl *Entity = 0;
1211    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1212      return true;
1213
1214    if (Converted)
1215      Converted->push_back(TemplateArgument(Entity));
1216    return false;
1217  }
1218
1219  if (ParamType->isPointerType()) {
1220    //   -- for a non-type template-parameter of type pointer to
1221    //      object, qualification conversions (4.4) and the
1222    //      array-to-pointer conversion (4.2) are applied.
1223    assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
1224           "Only object pointers allowed here");
1225
1226    if (ArgType->isArrayType()) {
1227      ArgType = Context.getArrayDecayedType(ArgType);
1228      ImpCastExprToType(Arg, ArgType);
1229    }
1230
1231    if (IsQualificationConversion(ArgType, ParamType)) {
1232      ArgType = ParamType;
1233      ImpCastExprToType(Arg, ParamType);
1234    }
1235
1236    if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
1237      // We can't perform this conversion.
1238      Diag(Arg->getSourceRange().getBegin(),
1239           diag::err_template_arg_not_convertible)
1240        << Arg->getType() << Param->getType() << Arg->getSourceRange();
1241      Diag(Param->getLocation(), diag::note_template_param_here);
1242      return true;
1243    }
1244
1245    NamedDecl *Entity = 0;
1246    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1247      return true;
1248
1249    if (Converted)
1250      Converted->push_back(TemplateArgument(Entity));
1251
1252    return false;
1253  }
1254
1255  if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1256    //   -- For a non-type template-parameter of type reference to
1257    //      object, no conversions apply. The type referred to by the
1258    //      reference may be more cv-qualified than the (otherwise
1259    //      identical) type of the template-argument. The
1260    //      template-parameter is bound directly to the
1261    //      template-argument, which must be an lvalue.
1262    assert(ParamRefType->getPointeeType()->isObjectType() &&
1263           "Only object references allowed here");
1264
1265    if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
1266      Diag(Arg->getSourceRange().getBegin(),
1267           diag::err_template_arg_no_ref_bind)
1268        << Param->getType() << Arg->getType()
1269        << Arg->getSourceRange();
1270      Diag(Param->getLocation(), diag::note_template_param_here);
1271      return true;
1272    }
1273
1274    unsigned ParamQuals
1275      = Context.getCanonicalType(ParamType).getCVRQualifiers();
1276    unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1277
1278    if ((ParamQuals | ArgQuals) != ParamQuals) {
1279      Diag(Arg->getSourceRange().getBegin(),
1280           diag::err_template_arg_ref_bind_ignores_quals)
1281        << Param->getType() << Arg->getType()
1282        << Arg->getSourceRange();
1283      Diag(Param->getLocation(), diag::note_template_param_here);
1284      return true;
1285    }
1286
1287    NamedDecl *Entity = 0;
1288    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1289      return true;
1290
1291    if (Converted)
1292      Converted->push_back(TemplateArgument(Entity));
1293
1294    return false;
1295  }
1296
1297  //     -- For a non-type template-parameter of type pointer to data
1298  //        member, qualification conversions (4.4) are applied.
1299  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1300
1301  if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
1302    // Types match exactly: nothing more to do here.
1303  } else if (IsQualificationConversion(ArgType, ParamType)) {
1304    ImpCastExprToType(Arg, ParamType);
1305  } else {
1306    // We can't perform this conversion.
1307    Diag(Arg->getSourceRange().getBegin(),
1308         diag::err_template_arg_not_convertible)
1309      << Arg->getType() << Param->getType() << Arg->getSourceRange();
1310    Diag(Param->getLocation(), diag::note_template_param_here);
1311    return true;
1312  }
1313
1314  NamedDecl *Member = 0;
1315  if (CheckTemplateArgumentPointerToMember(Arg, Member))
1316    return true;
1317
1318  if (Converted)
1319    Converted->push_back(TemplateArgument(Member));
1320
1321  return false;
1322}
1323
1324/// \brief Check a template argument against its corresponding
1325/// template template parameter.
1326///
1327/// This routine implements the semantics of C++ [temp.arg.template].
1328/// It returns true if an error occurred, and false otherwise.
1329bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1330                                 DeclRefExpr *Arg) {
1331  assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1332  TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1333
1334  // C++ [temp.arg.template]p1:
1335  //   A template-argument for a template template-parameter shall be
1336  //   the name of a class template, expressed as id-expression. Only
1337  //   primary class templates are considered when matching the
1338  //   template template argument with the corresponding parameter;
1339  //   partial specializations are not considered even if their
1340  //   parameter lists match that of the template template parameter.
1341  if (!isa<ClassTemplateDecl>(Template)) {
1342    assert(isa<FunctionTemplateDecl>(Template) &&
1343           "Only function templates are possible here");
1344    Diag(Arg->getSourceRange().getBegin(),
1345         diag::note_template_arg_refers_here_func)
1346      << Template;
1347  }
1348
1349  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1350                                         Param->getTemplateParameters(),
1351                                         true, true,
1352                                         Arg->getSourceRange().getBegin());
1353}
1354
1355/// \brief Determine whether the given template parameter lists are
1356/// equivalent.
1357///
1358/// \param New  The new template parameter list, typically written in the
1359/// source code as part of a new template declaration.
1360///
1361/// \param Old  The old template parameter list, typically found via
1362/// name lookup of the template declared with this template parameter
1363/// list.
1364///
1365/// \param Complain  If true, this routine will produce a diagnostic if
1366/// the template parameter lists are not equivalent.
1367///
1368/// \param IsTemplateTemplateParm  If true, this routine is being
1369/// called to compare the template parameter lists of a template
1370/// template parameter.
1371///
1372/// \param TemplateArgLoc If this source location is valid, then we
1373/// are actually checking the template parameter list of a template
1374/// argument (New) against the template parameter list of its
1375/// corresponding template template parameter (Old). We produce
1376/// slightly different diagnostics in this scenario.
1377///
1378/// \returns True if the template parameter lists are equal, false
1379/// otherwise.
1380bool
1381Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1382                                     TemplateParameterList *Old,
1383                                     bool Complain,
1384                                     bool IsTemplateTemplateParm,
1385                                     SourceLocation TemplateArgLoc) {
1386  if (Old->size() != New->size()) {
1387    if (Complain) {
1388      unsigned NextDiag = diag::err_template_param_list_different_arity;
1389      if (TemplateArgLoc.isValid()) {
1390        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1391        NextDiag = diag::note_template_param_list_different_arity;
1392      }
1393      Diag(New->getTemplateLoc(), NextDiag)
1394          << (New->size() > Old->size())
1395          << IsTemplateTemplateParm
1396          << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
1397      Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1398        << IsTemplateTemplateParm
1399        << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1400    }
1401
1402    return false;
1403  }
1404
1405  for (TemplateParameterList::iterator OldParm = Old->begin(),
1406         OldParmEnd = Old->end(), NewParm = New->begin();
1407       OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1408    if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
1409      unsigned NextDiag = diag::err_template_param_different_kind;
1410      if (TemplateArgLoc.isValid()) {
1411        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1412        NextDiag = diag::note_template_param_different_kind;
1413      }
1414      Diag((*NewParm)->getLocation(), NextDiag)
1415        << IsTemplateTemplateParm;
1416      Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1417        << IsTemplateTemplateParm;
1418      return false;
1419    }
1420
1421    if (isa<TemplateTypeParmDecl>(*OldParm)) {
1422      // Okay; all template type parameters are equivalent (since we
1423      // know we're at the same index).
1424#if 0
1425      // FIXME: Enable this code in debug mode *after* we properly go
1426      // through and "instantiate" the template parameter lists of
1427      // template template parameters. It's only after this
1428      // instantiation that (1) any dependent types within the
1429      // template parameter list of the template template parameter
1430      // can be checked, and (2) the template type parameter depths
1431      // will match up.
1432      QualType OldParmType
1433        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1434      QualType NewParmType
1435        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1436      assert(Context.getCanonicalType(OldParmType) ==
1437             Context.getCanonicalType(NewParmType) &&
1438             "type parameter mismatch?");
1439#endif
1440    } else if (NonTypeTemplateParmDecl *OldNTTP
1441                 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1442      // The types of non-type template parameters must agree.
1443      NonTypeTemplateParmDecl *NewNTTP
1444        = cast<NonTypeTemplateParmDecl>(*NewParm);
1445      if (Context.getCanonicalType(OldNTTP->getType()) !=
1446            Context.getCanonicalType(NewNTTP->getType())) {
1447        if (Complain) {
1448          unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1449          if (TemplateArgLoc.isValid()) {
1450            Diag(TemplateArgLoc,
1451                 diag::err_template_arg_template_params_mismatch);
1452            NextDiag = diag::note_template_nontype_parm_different_type;
1453          }
1454          Diag(NewNTTP->getLocation(), NextDiag)
1455            << NewNTTP->getType()
1456            << IsTemplateTemplateParm;
1457          Diag(OldNTTP->getLocation(),
1458               diag::note_template_nontype_parm_prev_declaration)
1459            << OldNTTP->getType();
1460        }
1461        return false;
1462      }
1463    } else {
1464      // The template parameter lists of template template
1465      // parameters must agree.
1466      // FIXME: Could we perform a faster "type" comparison here?
1467      assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1468             "Only template template parameters handled here");
1469      TemplateTemplateParmDecl *OldTTP
1470        = cast<TemplateTemplateParmDecl>(*OldParm);
1471      TemplateTemplateParmDecl *NewTTP
1472        = cast<TemplateTemplateParmDecl>(*NewParm);
1473      if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1474                                          OldTTP->getTemplateParameters(),
1475                                          Complain,
1476                                          /*IsTemplateTemplateParm=*/true,
1477                                          TemplateArgLoc))
1478        return false;
1479    }
1480  }
1481
1482  return true;
1483}
1484
1485/// \brief Check whether a template can be declared within this scope.
1486///
1487/// If the template declaration is valid in this scope, returns
1488/// false. Otherwise, issues a diagnostic and returns true.
1489bool
1490Sema::CheckTemplateDeclScope(Scope *S,
1491                             MultiTemplateParamsArg &TemplateParameterLists) {
1492  assert(TemplateParameterLists.size() > 0 && "Not a template");
1493
1494  // Find the nearest enclosing declaration scope.
1495  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1496         (S->getFlags() & Scope::TemplateParamScope) != 0)
1497    S = S->getParent();
1498
1499  TemplateParameterList *TemplateParams =
1500    static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1501  SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1502  SourceRange TemplateRange
1503    = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1504
1505  // C++ [temp]p2:
1506  //   A template-declaration can appear only as a namespace scope or
1507  //   class scope declaration.
1508  DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1509  while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1510    if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1511      return Diag(TemplateLoc, diag::err_template_linkage)
1512        << TemplateRange;
1513
1514    Ctx = Ctx->getParent();
1515  }
1516
1517  if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1518    return false;
1519
1520  return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1521    << TemplateRange;
1522}
1523
1524/// \brief Check whether a class template specialization in the
1525/// current context is well-formed.
1526///
1527/// This routine determines whether a class template specialization
1528/// can be declared in the current context (C++ [temp.expl.spec]p2)
1529/// and emits appropriate diagnostics if there was an error. It
1530/// returns true if there was an error that we cannot recover from,
1531/// and false otherwise.
1532bool
1533Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1534                                   ClassTemplateSpecializationDecl *PrevDecl,
1535                                            SourceLocation TemplateNameLoc,
1536                                            SourceRange ScopeSpecifierRange) {
1537  // C++ [temp.expl.spec]p2:
1538  //   An explicit specialization shall be declared in the namespace
1539  //   of which the template is a member, or, for member templates, in
1540  //   the namespace of which the enclosing class or enclosing class
1541  //   template is a member. An explicit specialization of a member
1542  //   function, member class or static data member of a class
1543  //   template shall be declared in the namespace of which the class
1544  //   template is a member. Such a declaration may also be a
1545  //   definition. If the declaration is not a definition, the
1546  //   specialization may be defined later in the name- space in which
1547  //   the explicit specialization was declared, or in a namespace
1548  //   that encloses the one in which the explicit specialization was
1549  //   declared.
1550  if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1551    Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
1552      << ClassTemplate;
1553    return true;
1554  }
1555
1556  DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1557  DeclContext *TemplateContext
1558    = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
1559  if (!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1560    // There is no prior declaration of this entity, so this
1561    // specialization must be in the same context as the template
1562    // itself.
1563    if (DC != TemplateContext) {
1564      if (isa<TranslationUnitDecl>(TemplateContext))
1565        Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1566          << ClassTemplate << ScopeSpecifierRange;
1567      else if (isa<NamespaceDecl>(TemplateContext))
1568        Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1569          << ClassTemplate << cast<NamedDecl>(TemplateContext)
1570          << ScopeSpecifierRange;
1571
1572      Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1573    }
1574
1575    return false;
1576  }
1577
1578  // We have a previous declaration of this entity. Make sure that
1579  // this redeclaration (or definition) occurs in an enclosing namespace.
1580  if (!CurContext->Encloses(TemplateContext)) {
1581    if (isa<TranslationUnitDecl>(TemplateContext))
1582      Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1583        << ClassTemplate << ScopeSpecifierRange;
1584    else if (isa<NamespaceDecl>(TemplateContext))
1585      Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1586        << ClassTemplate << cast<NamedDecl>(TemplateContext)
1587        << ScopeSpecifierRange;
1588
1589    Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1590  }
1591
1592  return false;
1593}
1594
1595Sema::DeclTy *
1596Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1597                                       SourceLocation KWLoc,
1598                                       const CXXScopeSpec &SS,
1599                                       DeclTy *TemplateD,
1600                                       SourceLocation TemplateNameLoc,
1601                                       SourceLocation LAngleLoc,
1602                                       ASTTemplateArgsPtr TemplateArgs,
1603                                       SourceLocation *TemplateArgLocs,
1604                                       SourceLocation RAngleLoc,
1605                                       AttributeList *Attr,
1606                               MultiTemplateParamsArg TemplateParameterLists) {
1607  // Find the class template we're specializing
1608  ClassTemplateDecl *ClassTemplate
1609    = dyn_cast_or_null<ClassTemplateDecl>(static_cast<Decl *>(TemplateD));
1610  if (!ClassTemplate)
1611    return 0;
1612
1613  // Check the validity of the template headers that introduce this
1614  // template.
1615  // FIXME: Once we have member templates, we'll need to check
1616  // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
1617  // template<> headers.
1618  if (TemplateParameterLists.size() == 0)
1619    Diag(KWLoc, diag::err_template_spec_needs_header)
1620      << CodeInsertionHint(KWLoc, "template<> ");
1621  else {
1622    TemplateParameterList *TemplateParams
1623      = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1624    if (TemplateParameterLists.size() > 1) {
1625      Diag(TemplateParams->getTemplateLoc(),
1626           diag::err_template_spec_extra_headers);
1627      return 0;
1628    }
1629
1630    if (TemplateParams->size() > 0) {
1631      // FIXME: No support for class template partial specialization.
1632      Diag(TemplateParams->getTemplateLoc(),
1633           diag::unsup_template_partial_spec);
1634      return 0;
1635    }
1636  }
1637
1638  // Check that the specialization uses the same tag kind as the
1639  // original template.
1640  TagDecl::TagKind Kind;
1641  switch (TagSpec) {
1642  default: assert(0 && "Unknown tag type!");
1643  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1644  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
1645  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
1646  }
1647  if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) {
1648    Diag(KWLoc, diag::err_use_with_wrong_tag) << ClassTemplate;
1649    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
1650         diag::note_previous_use);
1651    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
1652  }
1653
1654  // Check that the template argument list is well-formed for this
1655  // template.
1656  llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
1657  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
1658                                TemplateArgs, TemplateArgLocs, RAngleLoc,
1659                                ConvertedTemplateArgs))
1660    return 0;
1661
1662  assert((ConvertedTemplateArgs.size() ==
1663            ClassTemplate->getTemplateParameters()->size()) &&
1664         "Converted template argument list is too short!");
1665
1666  // Find the class template specialization declaration that
1667  // corresponds to these arguments.
1668  llvm::FoldingSetNodeID ID;
1669  ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
1670                                           ConvertedTemplateArgs.size());
1671  void *InsertPos = 0;
1672  ClassTemplateSpecializationDecl *PrevDecl
1673    = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1674
1675  ClassTemplateSpecializationDecl *Specialization = 0;
1676
1677  // Check whether we can declare a class template specialization in
1678  // the current scope.
1679  if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
1680                                            TemplateNameLoc,
1681                                            SS.getRange()))
1682    return 0;
1683
1684  if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1685    // Since the only prior class template specialization with these
1686    // arguments was referenced but not declared, reuse that
1687    // declaration node as our own, updating its source location to
1688    // reflect our new declaration.
1689    Specialization = PrevDecl;
1690    Specialization->setLocation(TemplateNameLoc);
1691    PrevDecl = 0;
1692  } else {
1693    // Create a new class template specialization declaration node for
1694    // this explicit specialization.
1695    Specialization
1696      = ClassTemplateSpecializationDecl::Create(Context,
1697                                             ClassTemplate->getDeclContext(),
1698                                                TemplateNameLoc,
1699                                                ClassTemplate,
1700                                                &ConvertedTemplateArgs[0],
1701                                                ConvertedTemplateArgs.size(),
1702                                                PrevDecl);
1703
1704    if (PrevDecl) {
1705      ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
1706      ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
1707    } else {
1708      ClassTemplate->getSpecializations().InsertNode(Specialization,
1709                                                     InsertPos);
1710    }
1711  }
1712
1713  // Note that this is an explicit specialization.
1714  Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
1715
1716  // Check that this isn't a redefinition of this specialization.
1717  if (TK == TK_Definition) {
1718    if (RecordDecl *Def = Specialization->getDefinition(Context)) {
1719      // FIXME: Should also handle explicit specialization after
1720      // implicit instantiation with a special diagnostic.
1721      SourceRange Range(TemplateNameLoc, RAngleLoc);
1722      Diag(TemplateNameLoc, diag::err_redefinition)
1723        << Specialization << Range;
1724      Diag(Def->getLocation(), diag::note_previous_definition);
1725      Specialization->setInvalidDecl();
1726      return 0;
1727    }
1728  }
1729
1730  // Build the fully-sugared type for this class template
1731  // specialization as the user wrote in the specialization
1732  // itself. This means that we'll pretty-print the type retrieved
1733  // from the specialization's declaration the way that the user
1734  // actually wrote the specialization, rather than formatting the
1735  // name based on the "canonical" representation used to store the
1736  // template arguments in the specialization.
1737  Specialization->setTypeAsWritten(
1738    Context.getClassTemplateSpecializationType(ClassTemplate,
1739                                               TemplateArgs.size(),
1740                  reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
1741                                               TemplateArgs.getArgIsType(),
1742                                  Context.getTypeDeclType(Specialization)));
1743  TemplateArgs.release();
1744
1745  // C++ [temp.expl.spec]p9:
1746  //   A template explicit specialization is in the scope of the
1747  //   namespace in which the template was defined.
1748  //
1749  // We actually implement this paragraph where we set the semantic
1750  // context (in the creation of the ClassTemplateSpecializationDecl),
1751  // but we also maintain the lexical context where the actual
1752  // definition occurs.
1753  Specialization->setLexicalDeclContext(CurContext);
1754
1755  // We may be starting the definition of this specialization.
1756  if (TK == TK_Definition)
1757    Specialization->startDefinition();
1758
1759  // Add the specialization into its lexical context, so that it can
1760  // be seen when iterating through the list of declarations in that
1761  // context. However, specializations are not found by name lookup.
1762  CurContext->addDecl(Specialization);
1763  return Specialization;
1764}
1765