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