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