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