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