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