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