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