clang API Documentation

SemaTemplate.cpp
Go to the documentation of this file.
00001 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //===----------------------------------------------------------------------===/
00008 //
00009 //  This file implements semantic analysis for C++ templates.
00010 //===----------------------------------------------------------------------===/
00011 
00012 #include "clang/Sema/SemaInternal.h"
00013 #include "clang/Sema/Lookup.h"
00014 #include "clang/Sema/Scope.h"
00015 #include "clang/Sema/Template.h"
00016 #include "clang/Sema/TemplateDeduction.h"
00017 #include "TreeTransform.h"
00018 #include "clang/AST/ASTContext.h"
00019 #include "clang/AST/Expr.h"
00020 #include "clang/AST/ExprCXX.h"
00021 #include "clang/AST/DeclFriend.h"
00022 #include "clang/AST/DeclTemplate.h"
00023 #include "clang/AST/RecursiveASTVisitor.h"
00024 #include "clang/AST/TypeVisitor.h"
00025 #include "clang/Sema/DeclSpec.h"
00026 #include "clang/Sema/ParsedTemplate.h"
00027 #include "clang/Basic/LangOptions.h"
00028 #include "clang/Basic/PartialDiagnostic.h"
00029 #include "llvm/ADT/SmallBitVector.h"
00030 #include "llvm/ADT/SmallString.h"
00031 #include "llvm/ADT/StringExtras.h"
00032 using namespace clang;
00033 using namespace sema;
00034 
00035 // Exported for use by Parser.
00036 SourceRange
00037 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
00038                               unsigned N) {
00039   if (!N) return SourceRange();
00040   return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
00041 }
00042 
00043 /// \brief Determine whether the declaration found is acceptable as the name
00044 /// of a template and, if so, return that template declaration. Otherwise,
00045 /// returns NULL.
00046 static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
00047                                            NamedDecl *Orig,
00048                                            bool AllowFunctionTemplates) {
00049   NamedDecl *D = Orig->getUnderlyingDecl();
00050 
00051   if (isa<TemplateDecl>(D)) {
00052     if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
00053       return 0;
00054     
00055     return Orig;
00056   }
00057 
00058   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
00059     // C++ [temp.local]p1:
00060     //   Like normal (non-template) classes, class templates have an
00061     //   injected-class-name (Clause 9). The injected-class-name
00062     //   can be used with or without a template-argument-list. When
00063     //   it is used without a template-argument-list, it is
00064     //   equivalent to the injected-class-name followed by the
00065     //   template-parameters of the class template enclosed in
00066     //   <>. When it is used with a template-argument-list, it
00067     //   refers to the specified class template specialization,
00068     //   which could be the current specialization or another
00069     //   specialization.
00070     if (Record->isInjectedClassName()) {
00071       Record = cast<CXXRecordDecl>(Record->getDeclContext());
00072       if (Record->getDescribedClassTemplate())
00073         return Record->getDescribedClassTemplate();
00074 
00075       if (ClassTemplateSpecializationDecl *Spec
00076             = dyn_cast<ClassTemplateSpecializationDecl>(Record))
00077         return Spec->getSpecializedTemplate();
00078     }
00079 
00080     return 0;
00081   }
00082 
00083   return 0;
00084 }
00085 
00086 void Sema::FilterAcceptableTemplateNames(LookupResult &R, 
00087                                          bool AllowFunctionTemplates) {
00088   // The set of class templates we've already seen.
00089   llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
00090   LookupResult::Filter filter = R.makeFilter();
00091   while (filter.hasNext()) {
00092     NamedDecl *Orig = filter.next();
00093     NamedDecl *Repl = isAcceptableTemplateName(Context, Orig, 
00094                                                AllowFunctionTemplates);
00095     if (!Repl)
00096       filter.erase();
00097     else if (Repl != Orig) {
00098 
00099       // C++ [temp.local]p3:
00100       //   A lookup that finds an injected-class-name (10.2) can result in an
00101       //   ambiguity in certain cases (for example, if it is found in more than
00102       //   one base class). If all of the injected-class-names that are found
00103       //   refer to specializations of the same class template, and if the name
00104       //   is used as a template-name, the reference refers to the class
00105       //   template itself and not a specialization thereof, and is not
00106       //   ambiguous.
00107       if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
00108         if (!ClassTemplates.insert(ClassTmpl)) {
00109           filter.erase();
00110           continue;
00111         }
00112 
00113       // FIXME: we promote access to public here as a workaround to
00114       // the fact that LookupResult doesn't let us remember that we
00115       // found this template through a particular injected class name,
00116       // which means we end up doing nasty things to the invariants.
00117       // Pretending that access is public is *much* safer.
00118       filter.replace(Repl, AS_public);
00119     }
00120   }
00121   filter.done();
00122 }
00123 
00124 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
00125                                          bool AllowFunctionTemplates) {
00126   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
00127     if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
00128       return true;
00129   
00130   return false;
00131 }
00132 
00133 TemplateNameKind Sema::isTemplateName(Scope *S,
00134                                       CXXScopeSpec &SS,
00135                                       bool hasTemplateKeyword,
00136                                       UnqualifiedId &Name,
00137                                       ParsedType ObjectTypePtr,
00138                                       bool EnteringContext,
00139                                       TemplateTy &TemplateResult,
00140                                       bool &MemberOfUnknownSpecialization) {
00141   assert(getLangOpts().CPlusPlus && "No template names in C!");
00142 
00143   DeclarationName TName;
00144   MemberOfUnknownSpecialization = false;
00145 
00146   switch (Name.getKind()) {
00147   case UnqualifiedId::IK_Identifier:
00148     TName = DeclarationName(Name.Identifier);
00149     break;
00150 
00151   case UnqualifiedId::IK_OperatorFunctionId:
00152     TName = Context.DeclarationNames.getCXXOperatorName(
00153                                               Name.OperatorFunctionId.Operator);
00154     break;
00155 
00156   case UnqualifiedId::IK_LiteralOperatorId:
00157     TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
00158     break;
00159 
00160   default:
00161     return TNK_Non_template;
00162   }
00163 
00164   QualType ObjectType = ObjectTypePtr.get();
00165 
00166   LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
00167   LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
00168                      MemberOfUnknownSpecialization);
00169   if (R.empty()) return TNK_Non_template;
00170   if (R.isAmbiguous()) {
00171     // Suppress diagnostics;  we'll redo this lookup later.
00172     R.suppressDiagnostics();
00173 
00174     // FIXME: we might have ambiguous templates, in which case we
00175     // should at least parse them properly!
00176     return TNK_Non_template;
00177   }
00178 
00179   TemplateName Template;
00180   TemplateNameKind TemplateKind;
00181 
00182   unsigned ResultCount = R.end() - R.begin();
00183   if (ResultCount > 1) {
00184     // We assume that we'll preserve the qualifier from a function
00185     // template name in other ways.
00186     Template = Context.getOverloadedTemplateName(R.begin(), R.end());
00187     TemplateKind = TNK_Function_template;
00188 
00189     // We'll do this lookup again later.
00190     R.suppressDiagnostics();
00191   } else {
00192     TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
00193 
00194     if (SS.isSet() && !SS.isInvalid()) {
00195       NestedNameSpecifier *Qualifier
00196         = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
00197       Template = Context.getQualifiedTemplateName(Qualifier,
00198                                                   hasTemplateKeyword, TD);
00199     } else {
00200       Template = TemplateName(TD);
00201     }
00202 
00203     if (isa<FunctionTemplateDecl>(TD)) {
00204       TemplateKind = TNK_Function_template;
00205 
00206       // We'll do this lookup again later.
00207       R.suppressDiagnostics();
00208     } else {
00209       assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
00210              isa<TypeAliasTemplateDecl>(TD));
00211       TemplateKind = TNK_Type_template;
00212     }
00213   }
00214 
00215   TemplateResult = TemplateTy::make(Template);
00216   return TemplateKind;
00217 }
00218 
00219 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
00220                                        SourceLocation IILoc,
00221                                        Scope *S,
00222                                        const CXXScopeSpec *SS,
00223                                        TemplateTy &SuggestedTemplate,
00224                                        TemplateNameKind &SuggestedKind) {
00225   // We can't recover unless there's a dependent scope specifier preceding the
00226   // template name.
00227   // FIXME: Typo correction?
00228   if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
00229       computeDeclContext(*SS))
00230     return false;
00231 
00232   // The code is missing a 'template' keyword prior to the dependent template
00233   // name.
00234   NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
00235   Diag(IILoc, diag::err_template_kw_missing)
00236     << Qualifier << II.getName()
00237     << FixItHint::CreateInsertion(IILoc, "template ");
00238   SuggestedTemplate
00239     = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
00240   SuggestedKind = TNK_Dependent_template_name;
00241   return true;
00242 }
00243 
00244 void Sema::LookupTemplateName(LookupResult &Found,
00245                               Scope *S, CXXScopeSpec &SS,
00246                               QualType ObjectType,
00247                               bool EnteringContext,
00248                               bool &MemberOfUnknownSpecialization) {
00249   // Determine where to perform name lookup
00250   MemberOfUnknownSpecialization = false;
00251   DeclContext *LookupCtx = 0;
00252   bool isDependent = false;
00253   if (!ObjectType.isNull()) {
00254     // This nested-name-specifier occurs in a member access expression, e.g.,
00255     // x->B::f, and we are looking into the type of the object.
00256     assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
00257     LookupCtx = computeDeclContext(ObjectType);
00258     isDependent = ObjectType->isDependentType();
00259     assert((isDependent || !ObjectType->isIncompleteType()) &&
00260            "Caller should have completed object type");
00261     
00262     // Template names cannot appear inside an Objective-C class or object type.
00263     if (ObjectType->isObjCObjectOrInterfaceType()) {
00264       Found.clear();
00265       return;
00266     }
00267   } else if (SS.isSet()) {
00268     // This nested-name-specifier occurs after another nested-name-specifier,
00269     // so long into the context associated with the prior nested-name-specifier.
00270     LookupCtx = computeDeclContext(SS, EnteringContext);
00271     isDependent = isDependentScopeSpecifier(SS);
00272 
00273     // The declaration context must be complete.
00274     if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
00275       return;
00276   }
00277 
00278   bool ObjectTypeSearchedInScope = false;
00279   bool AllowFunctionTemplatesInLookup = true;
00280   if (LookupCtx) {
00281     // Perform "qualified" name lookup into the declaration context we
00282     // computed, which is either the type of the base of a member access
00283     // expression or the declaration context associated with a prior
00284     // nested-name-specifier.
00285     LookupQualifiedName(Found, LookupCtx);
00286     if (!ObjectType.isNull() && Found.empty()) {
00287       // C++ [basic.lookup.classref]p1:
00288       //   In a class member access expression (5.2.5), if the . or -> token is
00289       //   immediately followed by an identifier followed by a <, the
00290       //   identifier must be looked up to determine whether the < is the
00291       //   beginning of a template argument list (14.2) or a less-than operator.
00292       //   The identifier is first looked up in the class of the object
00293       //   expression. If the identifier is not found, it is then looked up in
00294       //   the context of the entire postfix-expression and shall name a class
00295       //   or function template.
00296       if (S) LookupName(Found, S);
00297       ObjectTypeSearchedInScope = true;
00298       AllowFunctionTemplatesInLookup = false;
00299     }
00300   } else if (isDependent && (!S || ObjectType.isNull())) {
00301     // We cannot look into a dependent object type or nested nme
00302     // specifier.
00303     MemberOfUnknownSpecialization = true;
00304     return;
00305   } else {
00306     // Perform unqualified name lookup in the current scope.
00307     LookupName(Found, S);
00308     
00309     if (!ObjectType.isNull())
00310       AllowFunctionTemplatesInLookup = false;
00311   }
00312 
00313   if (Found.empty() && !isDependent) {
00314     // If we did not find any names, attempt to correct any typos.
00315     DeclarationName Name = Found.getLookupName();
00316     Found.clear();
00317     // Simple filter callback that, for keywords, only accepts the C++ *_cast
00318     CorrectionCandidateCallback FilterCCC;
00319     FilterCCC.WantTypeSpecifiers = false;
00320     FilterCCC.WantExpressionKeywords = false;
00321     FilterCCC.WantRemainingKeywords = false;
00322     FilterCCC.WantCXXNamedCasts = true;
00323     if (TypoCorrection Corrected = CorrectTypo(Found.getLookupNameInfo(),
00324                                                Found.getLookupKind(), S, &SS,
00325                                                FilterCCC, LookupCtx)) {
00326       Found.setLookupName(Corrected.getCorrection());
00327       if (Corrected.getCorrectionDecl())
00328         Found.addDecl(Corrected.getCorrectionDecl());
00329       FilterAcceptableTemplateNames(Found);
00330       if (!Found.empty()) {
00331         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
00332         std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
00333         if (LookupCtx)
00334           Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
00335             << Name << LookupCtx << CorrectedQuotedStr << SS.getRange()
00336             << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
00337         else
00338           Diag(Found.getNameLoc(), diag::err_no_template_suggest)
00339             << Name << CorrectedQuotedStr
00340             << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
00341         if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
00342           Diag(Template->getLocation(), diag::note_previous_decl)
00343             << CorrectedQuotedStr;
00344       }
00345     } else {
00346       Found.setLookupName(Name);
00347     }
00348   }
00349 
00350   FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
00351   if (Found.empty()) {
00352     if (isDependent)
00353       MemberOfUnknownSpecialization = true;
00354     return;
00355   }
00356 
00357   if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
00358       !(getLangOpts().CPlusPlus0x && !Found.empty())) {
00359     // C++03 [basic.lookup.classref]p1:
00360     //   [...] If the lookup in the class of the object expression finds a
00361     //   template, the name is also looked up in the context of the entire
00362     //   postfix-expression and [...]
00363     //
00364     // Note: C++11 does not perform this second lookup.
00365     LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
00366                             LookupOrdinaryName);
00367     LookupName(FoundOuter, S);
00368     FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
00369 
00370     if (FoundOuter.empty()) {
00371       //   - if the name is not found, the name found in the class of the
00372       //     object expression is used, otherwise
00373     } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
00374                FoundOuter.isAmbiguous()) {
00375       //   - if the name is found in the context of the entire
00376       //     postfix-expression and does not name a class template, the name
00377       //     found in the class of the object expression is used, otherwise
00378       FoundOuter.clear();
00379     } else if (!Found.isSuppressingDiagnostics()) {
00380       //   - if the name found is a class template, it must refer to the same
00381       //     entity as the one found in the class of the object expression,
00382       //     otherwise the program is ill-formed.
00383       if (!Found.isSingleResult() ||
00384           Found.getFoundDecl()->getCanonicalDecl()
00385             != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
00386         Diag(Found.getNameLoc(),
00387              diag::ext_nested_name_member_ref_lookup_ambiguous)
00388           << Found.getLookupName()
00389           << ObjectType;
00390         Diag(Found.getRepresentativeDecl()->getLocation(),
00391              diag::note_ambig_member_ref_object_type)
00392           << ObjectType;
00393         Diag(FoundOuter.getFoundDecl()->getLocation(),
00394              diag::note_ambig_member_ref_scope);
00395 
00396         // Recover by taking the template that we found in the object
00397         // expression's type.
00398       }
00399     }
00400   }
00401 }
00402 
00403 /// ActOnDependentIdExpression - Handle a dependent id-expression that
00404 /// was just parsed.  This is only possible with an explicit scope
00405 /// specifier naming a dependent type.
00406 ExprResult
00407 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
00408                                  SourceLocation TemplateKWLoc,
00409                                  const DeclarationNameInfo &NameInfo,
00410                                  bool isAddressOfOperand,
00411                            const TemplateArgumentListInfo *TemplateArgs) {
00412   DeclContext *DC = getFunctionLevelDeclContext();
00413 
00414   if (!isAddressOfOperand &&
00415       isa<CXXMethodDecl>(DC) &&
00416       cast<CXXMethodDecl>(DC)->isInstance()) {
00417     QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
00418 
00419     // Since the 'this' expression is synthesized, we don't need to
00420     // perform the double-lookup check.
00421     NamedDecl *FirstQualifierInScope = 0;
00422 
00423     return Owned(CXXDependentScopeMemberExpr::Create(Context,
00424                                                      /*This*/ 0, ThisType,
00425                                                      /*IsArrow*/ true,
00426                                                      /*Op*/ SourceLocation(),
00427                                                SS.getWithLocInContext(Context),
00428                                                      TemplateKWLoc,
00429                                                      FirstQualifierInScope,
00430                                                      NameInfo,
00431                                                      TemplateArgs));
00432   }
00433 
00434   return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
00435 }
00436 
00437 ExprResult
00438 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
00439                                 SourceLocation TemplateKWLoc,
00440                                 const DeclarationNameInfo &NameInfo,
00441                                 const TemplateArgumentListInfo *TemplateArgs) {
00442   return Owned(DependentScopeDeclRefExpr::Create(Context,
00443                                                SS.getWithLocInContext(Context),
00444                                                  TemplateKWLoc,
00445                                                  NameInfo,
00446                                                  TemplateArgs));
00447 }
00448 
00449 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
00450 /// that the template parameter 'PrevDecl' is being shadowed by a new
00451 /// declaration at location Loc. Returns true to indicate that this is
00452 /// an error, and false otherwise.
00453 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
00454   assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
00455 
00456   // Microsoft Visual C++ permits template parameters to be shadowed.
00457   if (getLangOpts().MicrosoftExt)
00458     return;
00459 
00460   // C++ [temp.local]p4:
00461   //   A template-parameter shall not be redeclared within its
00462   //   scope (including nested scopes).
00463   Diag(Loc, diag::err_template_param_shadow)
00464     << cast<NamedDecl>(PrevDecl)->getDeclName();
00465   Diag(PrevDecl->getLocation(), diag::note_template_param_here);
00466   return;
00467 }
00468 
00469 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
00470 /// the parameter D to reference the templated declaration and return a pointer
00471 /// to the template declaration. Otherwise, do nothing to D and return null.
00472 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
00473   if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
00474     D = Temp->getTemplatedDecl();
00475     return Temp;
00476   }
00477   return 0;
00478 }
00479 
00480 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
00481                                              SourceLocation EllipsisLoc) const {
00482   assert(Kind == Template &&
00483          "Only template template arguments can be pack expansions here");
00484   assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
00485          "Template template argument pack expansion without packs");
00486   ParsedTemplateArgument Result(*this);
00487   Result.EllipsisLoc = EllipsisLoc;
00488   return Result;
00489 }
00490 
00491 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
00492                                             const ParsedTemplateArgument &Arg) {
00493 
00494   switch (Arg.getKind()) {
00495   case ParsedTemplateArgument::Type: {
00496     TypeSourceInfo *DI;
00497     QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
00498     if (!DI)
00499       DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
00500     return TemplateArgumentLoc(TemplateArgument(T), DI);
00501   }
00502 
00503   case ParsedTemplateArgument::NonType: {
00504     Expr *E = static_cast<Expr *>(Arg.getAsExpr());
00505     return TemplateArgumentLoc(TemplateArgument(E), E);
00506   }
00507 
00508   case ParsedTemplateArgument::Template: {
00509     TemplateName Template = Arg.getAsTemplate().get();
00510     TemplateArgument TArg;
00511     if (Arg.getEllipsisLoc().isValid())
00512       TArg = TemplateArgument(Template, llvm::Optional<unsigned int>());
00513     else
00514       TArg = Template;
00515     return TemplateArgumentLoc(TArg,
00516                                Arg.getScopeSpec().getWithLocInContext(
00517                                                               SemaRef.Context),
00518                                Arg.getLocation(),
00519                                Arg.getEllipsisLoc());
00520   }
00521   }
00522 
00523   llvm_unreachable("Unhandled parsed template argument");
00524 }
00525 
00526 /// \brief Translates template arguments as provided by the parser
00527 /// into template arguments used by semantic analysis.
00528 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
00529                                       TemplateArgumentListInfo &TemplateArgs) {
00530  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
00531    TemplateArgs.addArgument(translateTemplateArgument(*this,
00532                                                       TemplateArgsIn[I]));
00533 }
00534 
00535 /// ActOnTypeParameter - Called when a C++ template type parameter
00536 /// (e.g., "typename T") has been parsed. Typename specifies whether
00537 /// the keyword "typename" was used to declare the type parameter
00538 /// (otherwise, "class" was used), and KeyLoc is the location of the
00539 /// "class" or "typename" keyword. ParamName is the name of the
00540 /// parameter (NULL indicates an unnamed template parameter) and
00541 /// ParamNameLoc is the location of the parameter name (if any).
00542 /// If the type parameter has a default argument, it will be added
00543 /// later via ActOnTypeParameterDefault.
00544 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
00545                                SourceLocation EllipsisLoc,
00546                                SourceLocation KeyLoc,
00547                                IdentifierInfo *ParamName,
00548                                SourceLocation ParamNameLoc,
00549                                unsigned Depth, unsigned Position,
00550                                SourceLocation EqualLoc,
00551                                ParsedType DefaultArg) {
00552   assert(S->isTemplateParamScope() &&
00553          "Template type parameter not in template parameter scope!");
00554   bool Invalid = false;
00555 
00556   if (ParamName) {
00557     NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
00558                                            LookupOrdinaryName,
00559                                            ForRedeclaration);
00560     if (PrevDecl && PrevDecl->isTemplateParameter()) {
00561       DiagnoseTemplateParameterShadow(ParamNameLoc, PrevDecl);
00562       PrevDecl = 0;
00563     }
00564   }
00565 
00566   SourceLocation Loc = ParamNameLoc;
00567   if (!ParamName)
00568     Loc = KeyLoc;
00569 
00570   TemplateTypeParmDecl *Param
00571     = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
00572                                    KeyLoc, Loc, Depth, Position, ParamName,
00573                                    Typename, Ellipsis);
00574   Param->setAccess(AS_public);
00575   if (Invalid)
00576     Param->setInvalidDecl();
00577 
00578   if (ParamName) {
00579     // Add the template parameter into the current scope.
00580     S->AddDecl(Param);
00581     IdResolver.AddDecl(Param);
00582   }
00583 
00584   // C++0x [temp.param]p9:
00585   //   A default template-argument may be specified for any kind of
00586   //   template-parameter that is not a template parameter pack.
00587   if (DefaultArg && Ellipsis) {
00588     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
00589     DefaultArg = ParsedType();
00590   }
00591 
00592   // Handle the default argument, if provided.
00593   if (DefaultArg) {
00594     TypeSourceInfo *DefaultTInfo;
00595     GetTypeFromParser(DefaultArg, &DefaultTInfo);
00596 
00597     assert(DefaultTInfo && "expected source information for type");
00598 
00599     // Check for unexpanded parameter packs.
00600     if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
00601                                         UPPC_DefaultArgument))
00602       return Param;
00603 
00604     // Check the template argument itself.
00605     if (CheckTemplateArgument(Param, DefaultTInfo)) {
00606       Param->setInvalidDecl();
00607       return Param;
00608     }
00609 
00610     Param->setDefaultArgument(DefaultTInfo, false);
00611   }
00612 
00613   return Param;
00614 }
00615 
00616 /// \brief Check that the type of a non-type template parameter is
00617 /// well-formed.
00618 ///
00619 /// \returns the (possibly-promoted) parameter type if valid;
00620 /// otherwise, produces a diagnostic and returns a NULL type.
00621 QualType
00622 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
00623   // We don't allow variably-modified types as the type of non-type template
00624   // parameters.
00625   if (T->isVariablyModifiedType()) {
00626     Diag(Loc, diag::err_variably_modified_nontype_template_param)
00627       << T;
00628     return QualType();
00629   }
00630 
00631   // C++ [temp.param]p4:
00632   //
00633   // A non-type template-parameter shall have one of the following
00634   // (optionally cv-qualified) types:
00635   //
00636   //       -- integral or enumeration type,
00637   if (T->isIntegralOrEnumerationType() ||
00638       //   -- pointer to object or pointer to function,
00639       T->isPointerType() ||
00640       //   -- reference to object or reference to function,
00641       T->isReferenceType() ||
00642       //   -- pointer to member,
00643       T->isMemberPointerType() ||
00644       //   -- std::nullptr_t.
00645       T->isNullPtrType() ||
00646       // If T is a dependent type, we can't do the check now, so we
00647       // assume that it is well-formed.
00648       T->isDependentType()) {
00649     // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
00650     // are ignored when determining its type.
00651     return T.getUnqualifiedType();
00652   }
00653 
00654   // C++ [temp.param]p8:
00655   //
00656   //   A non-type template-parameter of type "array of T" or
00657   //   "function returning T" is adjusted to be of type "pointer to
00658   //   T" or "pointer to function returning T", respectively.
00659   else if (T->isArrayType())
00660     // FIXME: Keep the type prior to promotion?
00661     return Context.getArrayDecayedType(T);
00662   else if (T->isFunctionType())
00663     // FIXME: Keep the type prior to promotion?
00664     return Context.getPointerType(T);
00665 
00666   Diag(Loc, diag::err_template_nontype_parm_bad_type)
00667     << T;
00668 
00669   return QualType();
00670 }
00671 
00672 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
00673                                           unsigned Depth,
00674                                           unsigned Position,
00675                                           SourceLocation EqualLoc,
00676                                           Expr *Default) {
00677   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
00678   QualType T = TInfo->getType();
00679 
00680   assert(S->isTemplateParamScope() &&
00681          "Non-type template parameter not in template parameter scope!");
00682   bool Invalid = false;
00683 
00684   IdentifierInfo *ParamName = D.getIdentifier();
00685   if (ParamName) {
00686     NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
00687                                            LookupOrdinaryName,
00688                                            ForRedeclaration);
00689     if (PrevDecl && PrevDecl->isTemplateParameter()) {
00690       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
00691       PrevDecl = 0;
00692     }
00693   }
00694 
00695   T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
00696   if (T.isNull()) {
00697     T = Context.IntTy; // Recover with an 'int' type.
00698     Invalid = true;
00699   }
00700 
00701   bool IsParameterPack = D.hasEllipsis();
00702   NonTypeTemplateParmDecl *Param
00703     = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
00704                                       D.getLocStart(),
00705                                       D.getIdentifierLoc(),
00706                                       Depth, Position, ParamName, T,
00707                                       IsParameterPack, TInfo);
00708   Param->setAccess(AS_public);
00709   
00710   if (Invalid)
00711     Param->setInvalidDecl();
00712 
00713   if (D.getIdentifier()) {
00714     // Add the template parameter into the current scope.
00715     S->AddDecl(Param);
00716     IdResolver.AddDecl(Param);
00717   }
00718 
00719   // C++0x [temp.param]p9:
00720   //   A default template-argument may be specified for any kind of
00721   //   template-parameter that is not a template parameter pack.
00722   if (Default && IsParameterPack) {
00723     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
00724     Default = 0;
00725   }
00726 
00727   // Check the well-formedness of the default template argument, if provided.
00728   if (Default) {
00729     // Check for unexpanded parameter packs.
00730     if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
00731       return Param;
00732 
00733     TemplateArgument Converted;
00734     ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
00735     if (DefaultRes.isInvalid()) {
00736       Param->setInvalidDecl();
00737       return Param;
00738     }
00739     Default = DefaultRes.take();
00740 
00741     Param->setDefaultArgument(Default, false);
00742   }
00743 
00744   return Param;
00745 }
00746 
00747 /// ActOnTemplateTemplateParameter - Called when a C++ template template
00748 /// parameter (e.g. T in template <template <typename> class T> class array)
00749 /// has been parsed. S is the current scope.
00750 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
00751                                            SourceLocation TmpLoc,
00752                                            TemplateParameterList *Params,
00753                                            SourceLocation EllipsisLoc,
00754                                            IdentifierInfo *Name,
00755                                            SourceLocation NameLoc,
00756                                            unsigned Depth,
00757                                            unsigned Position,
00758                                            SourceLocation EqualLoc,
00759                                            ParsedTemplateArgument Default) {
00760   assert(S->isTemplateParamScope() &&
00761          "Template template parameter not in template parameter scope!");
00762 
00763   // Construct the parameter object.
00764   bool IsParameterPack = EllipsisLoc.isValid();
00765   TemplateTemplateParmDecl *Param =
00766     TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
00767                                      NameLoc.isInvalid()? TmpLoc : NameLoc,
00768                                      Depth, Position, IsParameterPack,
00769                                      Name, Params);
00770   Param->setAccess(AS_public);
00771   
00772   // If the template template parameter has a name, then link the identifier
00773   // into the scope and lookup mechanisms.
00774   if (Name) {
00775     S->AddDecl(Param);
00776     IdResolver.AddDecl(Param);
00777   }
00778 
00779   if (Params->size() == 0) {
00780     Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
00781     << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
00782     Param->setInvalidDecl();
00783   }
00784 
00785   // C++0x [temp.param]p9:
00786   //   A default template-argument may be specified for any kind of
00787   //   template-parameter that is not a template parameter pack.
00788   if (IsParameterPack && !Default.isInvalid()) {
00789     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
00790     Default = ParsedTemplateArgument();
00791   }
00792 
00793   if (!Default.isInvalid()) {
00794     // Check only that we have a template template argument. We don't want to
00795     // try to check well-formedness now, because our template template parameter
00796     // might have dependent types in its template parameters, which we wouldn't
00797     // be able to match now.
00798     //
00799     // If none of the template template parameter's template arguments mention
00800     // other template parameters, we could actually perform more checking here.
00801     // However, it isn't worth doing.
00802     TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
00803     if (DefaultArg.getArgument().getAsTemplate().isNull()) {
00804       Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
00805         << DefaultArg.getSourceRange();
00806       return Param;
00807     }
00808 
00809     // Check for unexpanded parameter packs.
00810     if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
00811                                         DefaultArg.getArgument().getAsTemplate(),
00812                                         UPPC_DefaultArgument))
00813       return Param;
00814 
00815     Param->setDefaultArgument(DefaultArg, false);
00816   }
00817 
00818   return Param;
00819 }
00820 
00821 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
00822 /// contains the template parameters in Params/NumParams.
00823 TemplateParameterList *
00824 Sema::ActOnTemplateParameterList(unsigned Depth,
00825                                  SourceLocation ExportLoc,
00826                                  SourceLocation TemplateLoc,
00827                                  SourceLocation LAngleLoc,
00828                                  Decl **Params, unsigned NumParams,
00829                                  SourceLocation RAngleLoc) {
00830   if (ExportLoc.isValid())
00831     Diag(ExportLoc, diag::warn_template_export_unsupported);
00832 
00833   return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
00834                                        (NamedDecl**)Params, NumParams,
00835                                        RAngleLoc);
00836 }
00837 
00838 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
00839   if (SS.isSet())
00840     T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
00841 }
00842 
00843 DeclResult
00844 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
00845                          SourceLocation KWLoc, CXXScopeSpec &SS,
00846                          IdentifierInfo *Name, SourceLocation NameLoc,
00847                          AttributeList *Attr,
00848                          TemplateParameterList *TemplateParams,
00849                          AccessSpecifier AS, SourceLocation ModulePrivateLoc,
00850                          unsigned NumOuterTemplateParamLists,
00851                          TemplateParameterList** OuterTemplateParamLists) {
00852   assert(TemplateParams && TemplateParams->size() > 0 &&
00853          "No template parameters");
00854   assert(TUK != TUK_Reference && "Can only declare or define class templates");
00855   bool Invalid = false;
00856 
00857   // Check that we can declare a template here.
00858   if (CheckTemplateDeclScope(S, TemplateParams))
00859     return true;
00860 
00861   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
00862   assert(Kind != TTK_Enum && "can't build template of enumerated type");
00863 
00864   // There is no such thing as an unnamed class template.
00865   if (!Name) {
00866     Diag(KWLoc, diag::err_template_unnamed_class);
00867     return true;
00868   }
00869 
00870   // Find any previous declaration with this name. For a friend with no
00871   // scope explicitly specified, we only look for tag declarations (per
00872   // C++11 [basic.lookup.elab]p2).
00873   DeclContext *SemanticContext;
00874   LookupResult Previous(*this, Name, NameLoc,
00875                         (SS.isEmpty() && TUK == TUK_Friend)
00876                           ? LookupTagName : LookupOrdinaryName,
00877                         ForRedeclaration);
00878   if (SS.isNotEmpty() && !SS.isInvalid()) {
00879     SemanticContext = computeDeclContext(SS, true);
00880     if (!SemanticContext) {
00881       // FIXME: Horrible, horrible hack! We can't currently represent this
00882       // in the AST, and historically we have just ignored such friend
00883       // class templates, so don't complain here.
00884       if (TUK != TUK_Friend)
00885         Diag(NameLoc, diag::err_template_qualified_declarator_no_match)
00886           << SS.getScopeRep() << SS.getRange();
00887       return true;
00888     }
00889 
00890     if (RequireCompleteDeclContext(SS, SemanticContext))
00891       return true;
00892 
00893     // If we're adding a template to a dependent context, we may need to 
00894     // rebuilding some of the types used within the template parameter list, 
00895     // now that we know what the current instantiation is.
00896     if (SemanticContext->isDependentContext()) {
00897       ContextRAII SavedContext(*this, SemanticContext);
00898       if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
00899         Invalid = true;
00900     } else if (TUK != TUK_Friend && TUK != TUK_Reference)
00901       diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
00902 
00903     LookupQualifiedName(Previous, SemanticContext);
00904   } else {
00905     SemanticContext = CurContext;
00906     LookupName(Previous, S);
00907   }
00908 
00909   if (Previous.isAmbiguous())
00910     return true;
00911 
00912   NamedDecl *PrevDecl = 0;
00913   if (Previous.begin() != Previous.end())
00914     PrevDecl = (*Previous.begin())->getUnderlyingDecl();
00915 
00916   // If there is a previous declaration with the same name, check
00917   // whether this is a valid redeclaration.
00918   ClassTemplateDecl *PrevClassTemplate
00919     = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
00920 
00921   // We may have found the injected-class-name of a class template,
00922   // class template partial specialization, or class template specialization.
00923   // In these cases, grab the template that is being defined or specialized.
00924   if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
00925       cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
00926     PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
00927     PrevClassTemplate
00928       = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
00929     if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
00930       PrevClassTemplate
00931         = cast<ClassTemplateSpecializationDecl>(PrevDecl)
00932             ->getSpecializedTemplate();
00933     }
00934   }
00935 
00936   if (TUK == TUK_Friend) {
00937     // C++ [namespace.memdef]p3:
00938     //   [...] When looking for a prior declaration of a class or a function
00939     //   declared as a friend, and when the name of the friend class or
00940     //   function is neither a qualified name nor a template-id, scopes outside
00941     //   the innermost enclosing namespace scope are not considered.
00942     if (!SS.isSet()) {
00943       DeclContext *OutermostContext = CurContext;
00944       while (!OutermostContext->isFileContext())
00945         OutermostContext = OutermostContext->getLookupParent();
00946 
00947       if (PrevDecl &&
00948           (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
00949            OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
00950         SemanticContext = PrevDecl->getDeclContext();
00951       } else {
00952         // Declarations in outer scopes don't matter. However, the outermost
00953         // context we computed is the semantic context for our new
00954         // declaration.
00955         PrevDecl = PrevClassTemplate = 0;
00956         SemanticContext = OutermostContext;
00957 
00958         // Check that the chosen semantic context doesn't already contain a
00959         // declaration of this name as a non-tag type.
00960         LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
00961                               ForRedeclaration);
00962         DeclContext *LookupContext = SemanticContext;
00963         while (LookupContext->isTransparentContext())
00964           LookupContext = LookupContext->getLookupParent();
00965         LookupQualifiedName(Previous, LookupContext);
00966 
00967         if (Previous.isAmbiguous())
00968           return true;
00969 
00970         if (Previous.begin() != Previous.end())
00971           PrevDecl = (*Previous.begin())->getUnderlyingDecl();
00972       }
00973     }
00974   } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
00975     PrevDecl = PrevClassTemplate = 0;
00976 
00977   if (PrevClassTemplate) {
00978     // Ensure that the template parameter lists are compatible. Skip this check
00979     // for a friend in a dependent context: the template parameter list itself
00980     // could be dependent.
00981     if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
00982         !TemplateParameterListsAreEqual(TemplateParams,
00983                                    PrevClassTemplate->getTemplateParameters(),
00984                                         /*Complain=*/true,
00985                                         TPL_TemplateMatch))
00986       return true;
00987 
00988     // C++ [temp.class]p4:
00989     //   In a redeclaration, partial specialization, explicit
00990     //   specialization or explicit instantiation of a class template,
00991     //   the class-key shall agree in kind with the original class
00992     //   template declaration (7.1.5.3).
00993     RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
00994     if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
00995                                       TUK == TUK_Definition,  KWLoc, *Name)) {
00996       Diag(KWLoc, diag::err_use_with_wrong_tag)
00997         << Name
00998         << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
00999       Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
01000       Kind = PrevRecordDecl->getTagKind();
01001     }
01002 
01003     // Check for redefinition of this class template.
01004     if (TUK == TUK_Definition) {
01005       if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
01006         Diag(NameLoc, diag::err_redefinition) << Name;
01007         Diag(Def->getLocation(), diag::note_previous_definition);
01008         // FIXME: Would it make sense to try to "forget" the previous
01009         // definition, as part of error recovery?
01010         return true;
01011       }
01012     }    
01013   } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
01014     // Maybe we will complain about the shadowed template parameter.
01015     DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
01016     // Just pretend that we didn't see the previous declaration.
01017     PrevDecl = 0;
01018   } else if (PrevDecl) {
01019     // C++ [temp]p5:
01020     //   A class template shall not have the same name as any other
01021     //   template, class, function, object, enumeration, enumerator,
01022     //   namespace, or type in the same scope (3.3), except as specified
01023     //   in (14.5.4).
01024     Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
01025     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
01026     return true;
01027   }
01028 
01029   // Check the template parameter list of this declaration, possibly
01030   // merging in the template parameter list from the previous class
01031   // template declaration. Skip this check for a friend in a dependent
01032   // context, because the template parameter list might be dependent.
01033   if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
01034       CheckTemplateParameterList(TemplateParams,
01035             PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
01036                                  (SS.isSet() && SemanticContext &&
01037                                   SemanticContext->isRecord() &&
01038                                   SemanticContext->isDependentContext())
01039                                    ? TPC_ClassTemplateMember
01040                                    : TPC_ClassTemplate))
01041     Invalid = true;
01042 
01043   if (SS.isSet()) {
01044     // If the name of the template was qualified, we must be defining the
01045     // template out-of-line.
01046     if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
01047       Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
01048                                       : diag::err_member_def_does_not_match)
01049         << Name << SemanticContext << SS.getRange();
01050       Invalid = true;
01051     }
01052   }
01053 
01054   CXXRecordDecl *NewClass =
01055     CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
01056                           PrevClassTemplate?
01057                             PrevClassTemplate->getTemplatedDecl() : 0,
01058                           /*DelayTypeCreation=*/true);
01059   SetNestedNameSpecifier(NewClass, SS);
01060   if (NumOuterTemplateParamLists > 0)
01061     NewClass->setTemplateParameterListsInfo(Context,
01062                                             NumOuterTemplateParamLists,
01063                                             OuterTemplateParamLists);
01064 
01065   // Add alignment attributes if necessary; these attributes are checked when
01066   // the ASTContext lays out the structure.
01067   AddAlignmentAttributesForRecord(NewClass);
01068   AddMsStructLayoutForRecord(NewClass);
01069 
01070   ClassTemplateDecl *NewTemplate
01071     = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
01072                                 DeclarationName(Name), TemplateParams,
01073                                 NewClass, PrevClassTemplate);
01074   NewClass->setDescribedClassTemplate(NewTemplate);
01075   
01076   if (ModulePrivateLoc.isValid())
01077     NewTemplate->setModulePrivate();
01078   
01079   // Build the type for the class template declaration now.
01080   QualType T = NewTemplate->getInjectedClassNameSpecialization();
01081   T = Context.getInjectedClassNameType(NewClass, T);
01082   assert(T->isDependentType() && "Class template type is not dependent?");
01083   (void)T;
01084 
01085   // If we are providing an explicit specialization of a member that is a
01086   // class template, make a note of that.
01087   if (PrevClassTemplate &&
01088       PrevClassTemplate->getInstantiatedFromMemberTemplate())
01089     PrevClassTemplate->setMemberSpecialization();
01090 
01091   // Set the access specifier.
01092   if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
01093     SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
01094 
01095   // Set the lexical context of these templates
01096   NewClass->setLexicalDeclContext(CurContext);
01097   NewTemplate->setLexicalDeclContext(CurContext);
01098 
01099   if (TUK == TUK_Definition)
01100     NewClass->startDefinition();
01101 
01102   if (Attr)
01103     ProcessDeclAttributeList(S, NewClass, Attr);
01104 
01105   if (TUK != TUK_Friend)
01106     PushOnScopeChains(NewTemplate, S);
01107   else {
01108     if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
01109       NewTemplate->setAccess(PrevClassTemplate->getAccess());
01110       NewClass->setAccess(PrevClassTemplate->getAccess());
01111     }
01112 
01113     NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
01114                                        PrevClassTemplate != NULL);
01115 
01116     // Friend templates are visible in fairly strange ways.
01117     if (!CurContext->isDependentContext()) {
01118       DeclContext *DC = SemanticContext->getRedeclContext();
01119       DC->makeDeclVisibleInContext(NewTemplate);
01120       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
01121         PushOnScopeChains(NewTemplate, EnclosingScope,
01122                           /* AddToContext = */ false);
01123     }
01124 
01125     FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
01126                                             NewClass->getLocation(),
01127                                             NewTemplate,
01128                                     /*FIXME:*/NewClass->getLocation());
01129     Friend->setAccess(AS_public);
01130     CurContext->addDecl(Friend);
01131   }
01132 
01133   if (Invalid) {
01134     NewTemplate->setInvalidDecl();
01135     NewClass->setInvalidDecl();
01136   }
01137   return NewTemplate;
01138 }
01139 
01140 /// \brief Diagnose the presence of a default template argument on a
01141 /// template parameter, which is ill-formed in certain contexts.
01142 ///
01143 /// \returns true if the default template argument should be dropped.
01144 static bool DiagnoseDefaultTemplateArgument(Sema &S,
01145                                             Sema::TemplateParamListContext TPC,
01146                                             SourceLocation ParamLoc,
01147                                             SourceRange DefArgRange) {
01148   switch (TPC) {
01149   case Sema::TPC_ClassTemplate:
01150   case Sema::TPC_TypeAliasTemplate:
01151     return false;
01152 
01153   case Sema::TPC_FunctionTemplate:
01154   case Sema::TPC_FriendFunctionTemplateDefinition:
01155     // C++ [temp.param]p9:
01156     //   A default template-argument shall not be specified in a
01157     //   function template declaration or a function template
01158     //   definition [...]
01159     //   If a friend function template declaration specifies a default 
01160     //   template-argument, that declaration shall be a definition and shall be
01161     //   the only declaration of the function template in the translation unit.
01162     // (C++98/03 doesn't have this wording; see DR226).
01163     S.Diag(ParamLoc, S.getLangOpts().CPlusPlus0x ?
01164          diag::warn_cxx98_compat_template_parameter_default_in_function_template
01165            : diag::ext_template_parameter_default_in_function_template)
01166       << DefArgRange;
01167     return false;
01168 
01169   case Sema::TPC_ClassTemplateMember:
01170     // C++0x [temp.param]p9:
01171     //   A default template-argument shall not be specified in the
01172     //   template-parameter-lists of the definition of a member of a
01173     //   class template that appears outside of the member's class.
01174     S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
01175       << DefArgRange;
01176     return true;
01177 
01178   case Sema::TPC_FriendFunctionTemplate:
01179     // C++ [temp.param]p9:
01180     //   A default template-argument shall not be specified in a
01181     //   friend template declaration.
01182     S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
01183       << DefArgRange;
01184     return true;
01185 
01186     // FIXME: C++0x [temp.param]p9 allows default template-arguments
01187     // for friend function templates if there is only a single
01188     // declaration (and it is a definition). Strange!
01189   }
01190 
01191   llvm_unreachable("Invalid TemplateParamListContext!");
01192 }
01193 
01194 /// \brief Check for unexpanded parameter packs within the template parameters
01195 /// of a template template parameter, recursively.
01196 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
01197                                              TemplateTemplateParmDecl *TTP) {
01198   TemplateParameterList *Params = TTP->getTemplateParameters();
01199   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
01200     NamedDecl *P = Params->getParam(I);
01201     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
01202       if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
01203                                             NTTP->getTypeSourceInfo(),
01204                                       Sema::UPPC_NonTypeTemplateParameterType))
01205         return true;
01206 
01207       continue;
01208     }
01209 
01210     if (TemplateTemplateParmDecl *InnerTTP
01211                                         = dyn_cast<TemplateTemplateParmDecl>(P))
01212       if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
01213         return true;
01214   }
01215 
01216   return false;
01217 }
01218 
01219 /// \brief Checks the validity of a template parameter list, possibly
01220 /// considering the template parameter list from a previous
01221 /// declaration.
01222 ///
01223 /// If an "old" template parameter list is provided, it must be
01224 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
01225 /// template parameter list.
01226 ///
01227 /// \param NewParams Template parameter list for a new template
01228 /// declaration. This template parameter list will be updated with any
01229 /// default arguments that are carried through from the previous
01230 /// template parameter list.
01231 ///
01232 /// \param OldParams If provided, template parameter list from a
01233 /// previous declaration of the same template. Default template
01234 /// arguments will be merged from the old template parameter list to
01235 /// the new template parameter list.
01236 ///
01237 /// \param TPC Describes the context in which we are checking the given
01238 /// template parameter list.
01239 ///
01240 /// \returns true if an error occurred, false otherwise.
01241 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
01242                                       TemplateParameterList *OldParams,
01243                                       TemplateParamListContext TPC) {
01244   bool Invalid = false;
01245 
01246   // C++ [temp.param]p10:
01247   //   The set of default template-arguments available for use with a
01248   //   template declaration or definition is obtained by merging the
01249   //   default arguments from the definition (if in scope) and all
01250   //   declarations in scope in the same way default function
01251   //   arguments are (8.3.6).
01252   bool SawDefaultArgument = false;
01253   SourceLocation PreviousDefaultArgLoc;
01254 
01255   // Dummy initialization to avoid warnings.
01256   TemplateParameterList::iterator OldParam = NewParams->end();
01257   if (OldParams)
01258     OldParam = OldParams->begin();
01259 
01260   bool RemoveDefaultArguments = false;
01261   for (TemplateParameterList::iterator NewParam = NewParams->begin(),
01262                                     NewParamEnd = NewParams->end();
01263        NewParam != NewParamEnd; ++NewParam) {
01264     // Variables used to diagnose redundant default arguments
01265     bool RedundantDefaultArg = false;
01266     SourceLocation OldDefaultLoc;
01267     SourceLocation NewDefaultLoc;
01268 
01269     // Variable used to diagnose missing default arguments
01270     bool MissingDefaultArg = false;
01271 
01272     // Variable used to diagnose non-final parameter packs
01273     bool SawParameterPack = false;
01274 
01275     if (TemplateTypeParmDecl *NewTypeParm
01276           = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
01277       // Check the presence of a default argument here.
01278       if (NewTypeParm->hasDefaultArgument() &&
01279           DiagnoseDefaultTemplateArgument(*this, TPC,
01280                                           NewTypeParm->getLocation(),
01281                NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
01282                                                        .getSourceRange()))
01283         NewTypeParm->removeDefaultArgument();
01284 
01285       // Merge default arguments for template type parameters.
01286       TemplateTypeParmDecl *OldTypeParm
01287           = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
01288 
01289       if (NewTypeParm->isParameterPack()) {
01290         assert(!NewTypeParm->hasDefaultArgument() &&
01291                "Parameter packs can't have a default argument!");
01292         SawParameterPack = true;
01293       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
01294                  NewTypeParm->hasDefaultArgument()) {
01295         OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
01296         NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
01297         SawDefaultArgument = true;
01298         RedundantDefaultArg = true;
01299         PreviousDefaultArgLoc = NewDefaultLoc;
01300       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
01301         // Merge the default argument from the old declaration to the
01302         // new declaration.
01303         SawDefaultArgument = true;
01304         NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
01305                                         true);
01306         PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
01307       } else if (NewTypeParm->hasDefaultArgument()) {
01308         SawDefaultArgument = true;
01309         PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
01310       } else if (SawDefaultArgument)
01311         MissingDefaultArg = true;
01312     } else if (NonTypeTemplateParmDecl *NewNonTypeParm
01313                = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
01314       // Check for unexpanded parameter packs.
01315       if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
01316                                           NewNonTypeParm->getTypeSourceInfo(),
01317                                           UPPC_NonTypeTemplateParameterType)) {
01318         Invalid = true;
01319         continue;
01320       }
01321 
01322       // Check the presence of a default argument here.
01323       if (NewNonTypeParm->hasDefaultArgument() &&
01324           DiagnoseDefaultTemplateArgument(*this, TPC,
01325                                           NewNonTypeParm->getLocation(),
01326                     NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
01327         NewNonTypeParm->removeDefaultArgument();
01328       }
01329 
01330       // Merge default arguments for non-type template parameters
01331       NonTypeTemplateParmDecl *OldNonTypeParm
01332         = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
01333       if (NewNonTypeParm->isParameterPack()) {
01334         assert(!NewNonTypeParm->hasDefaultArgument() &&
01335                "Parameter packs can't have a default argument!");
01336         SawParameterPack = true;
01337       } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
01338           NewNonTypeParm->hasDefaultArgument()) {
01339         OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
01340         NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
01341         SawDefaultArgument = true;
01342         RedundantDefaultArg = true;
01343         PreviousDefaultArgLoc = NewDefaultLoc;
01344       } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
01345         // Merge the default argument from the old declaration to the
01346         // new declaration.
01347         SawDefaultArgument = true;
01348         // FIXME: We need to create a new kind of "default argument"
01349         // expression that points to a previous non-type template
01350         // parameter.
01351         NewNonTypeParm->setDefaultArgument(
01352                                          OldNonTypeParm->getDefaultArgument(),
01353                                          /*Inherited=*/ true);
01354         PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
01355       } else if (NewNonTypeParm->hasDefaultArgument()) {
01356         SawDefaultArgument = true;
01357         PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
01358       } else if (SawDefaultArgument)
01359         MissingDefaultArg = true;
01360     } else {
01361       TemplateTemplateParmDecl *NewTemplateParm
01362         = cast<TemplateTemplateParmDecl>(*NewParam);
01363 
01364       // Check for unexpanded parameter packs, recursively.
01365       if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
01366         Invalid = true;
01367         continue;
01368       }
01369 
01370       // Check the presence of a default argument here.
01371       if (NewTemplateParm->hasDefaultArgument() &&
01372           DiagnoseDefaultTemplateArgument(*this, TPC,
01373                                           NewTemplateParm->getLocation(),
01374                      NewTemplateParm->getDefaultArgument().getSourceRange()))
01375         NewTemplateParm->removeDefaultArgument();
01376 
01377       // Merge default arguments for template template parameters
01378       TemplateTemplateParmDecl *OldTemplateParm
01379         = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
01380       if (NewTemplateParm->isParameterPack()) {
01381         assert(!NewTemplateParm->hasDefaultArgument() &&
01382                "Parameter packs can't have a default argument!");
01383         SawParameterPack = true;
01384       } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
01385           NewTemplateParm->hasDefaultArgument()) {
01386         OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
01387         NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
01388         SawDefaultArgument = true;
01389         RedundantDefaultArg = true;
01390         PreviousDefaultArgLoc = NewDefaultLoc;
01391       } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
01392         // Merge the default argument from the old declaration to the
01393         // new declaration.
01394         SawDefaultArgument = true;
01395         // FIXME: We need to create a new kind of "default argument" expression
01396         // that points to a previous template template parameter.
01397         NewTemplateParm->setDefaultArgument(
01398                                           OldTemplateParm->getDefaultArgument(),
01399                                           /*Inherited=*/ true);
01400         PreviousDefaultArgLoc
01401           = OldTemplateParm->getDefaultArgument().getLocation();
01402       } else if (NewTemplateParm->hasDefaultArgument()) {
01403         SawDefaultArgument = true;
01404         PreviousDefaultArgLoc
01405           = NewTemplateParm->getDefaultArgument().getLocation();
01406       } else if (SawDefaultArgument)
01407         MissingDefaultArg = true;
01408     }
01409 
01410     // C++0x [temp.param]p11:
01411     //   If a template parameter of a primary class template or alias template
01412     //   is a template parameter pack, it shall be the last template parameter.
01413     if (SawParameterPack && (NewParam + 1) != NewParamEnd && 
01414         (TPC == TPC_ClassTemplate || TPC == TPC_TypeAliasTemplate)) {
01415       Diag((*NewParam)->getLocation(),
01416            diag::err_template_param_pack_must_be_last_template_parameter);
01417       Invalid = true;
01418     }
01419 
01420     if (RedundantDefaultArg) {
01421       // C++ [temp.param]p12:
01422       //   A template-parameter shall not be given default arguments
01423       //   by two different declarations in the same scope.
01424       Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
01425       Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
01426       Invalid = true;
01427     } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
01428       // C++ [temp.param]p11:
01429       //   If a template-parameter of a class template has a default
01430       //   template-argument, each subsequent template-parameter shall either
01431       //   have a default template-argument supplied or be a template parameter
01432       //   pack.
01433       Diag((*NewParam)->getLocation(),
01434            diag::err_template_param_default_arg_missing);
01435       Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
01436       Invalid = true;
01437       RemoveDefaultArguments = true;
01438     }
01439 
01440     // If we have an old template parameter list that we're merging
01441     // in, move on to the next parameter.
01442     if (OldParams)
01443       ++OldParam;
01444   }
01445 
01446   // We were missing some default arguments at the end of the list, so remove
01447   // all of the default arguments.
01448   if (RemoveDefaultArguments) {
01449     for (TemplateParameterList::iterator NewParam = NewParams->begin(),
01450                                       NewParamEnd = NewParams->end();
01451          NewParam != NewParamEnd; ++NewParam) {
01452       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
01453         TTP->removeDefaultArgument();
01454       else if (NonTypeTemplateParmDecl *NTTP
01455                                 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
01456         NTTP->removeDefaultArgument();
01457       else
01458         cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
01459     }
01460   }
01461 
01462   return Invalid;
01463 }
01464 
01465 namespace {
01466 
01467 /// A class which looks for a use of a certain level of template
01468 /// parameter.
01469 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
01470   typedef RecursiveASTVisitor<DependencyChecker> super;
01471 
01472   unsigned Depth;
01473   bool Match;
01474 
01475   DependencyChecker(TemplateParameterList *Params) : Match(false) {
01476     NamedDecl *ND = Params->getParam(0);
01477     if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
01478       Depth = PD->getDepth();
01479     } else if (NonTypeTemplateParmDecl *PD =
01480                  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
01481       Depth = PD->getDepth();
01482     } else {
01483       Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
01484     }
01485   }
01486 
01487   bool Matches(unsigned ParmDepth) {
01488     if (ParmDepth >= Depth) {
01489       Match = true;
01490       return true;
01491     }
01492     return false;
01493   }
01494 
01495   bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
01496     return !Matches(T->getDepth());
01497   }
01498 
01499   bool TraverseTemplateName(TemplateName N) {
01500     if (TemplateTemplateParmDecl *PD =
01501           dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
01502       if (Matches(PD->getDepth())) return false;
01503     return super::TraverseTemplateName(N);
01504   }
01505 
01506   bool VisitDeclRefExpr(DeclRefExpr *E) {
01507     if (NonTypeTemplateParmDecl *PD =
01508           dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
01509       if (PD->getDepth() == Depth) {
01510         Match = true;
01511         return false;
01512       }
01513     }
01514     return super::VisitDeclRefExpr(E);
01515   }
01516   
01517   bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
01518     return TraverseType(T->getInjectedSpecializationType());
01519   }
01520 };
01521 }
01522 
01523 /// Determines whether a given type depends on the given parameter
01524 /// list.
01525 static bool
01526 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
01527   DependencyChecker Checker(Params);
01528   Checker.TraverseType(T);
01529   return Checker.Match;
01530 }
01531 
01532 // Find the source range corresponding to the named type in the given
01533 // nested-name-specifier, if any.
01534 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
01535                                                        QualType T,
01536                                                        const CXXScopeSpec &SS) {
01537   NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
01538   while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
01539     if (const Type *CurType = NNS->getAsType()) {
01540       if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
01541         return NNSLoc.getTypeLoc().getSourceRange();
01542     } else
01543       break;
01544     
01545     NNSLoc = NNSLoc.getPrefix();
01546   }
01547   
01548   return SourceRange();
01549 }
01550 
01551 /// \brief Match the given template parameter lists to the given scope
01552 /// specifier, returning the template parameter list that applies to the
01553 /// name.
01554 ///
01555 /// \param DeclStartLoc the start of the declaration that has a scope
01556 /// specifier or a template parameter list.
01557 ///
01558 /// \param DeclLoc The location of the declaration itself.
01559 ///
01560 /// \param SS the scope specifier that will be matched to the given template
01561 /// parameter lists. This scope specifier precedes a qualified name that is
01562 /// being declared.
01563 ///
01564 /// \param ParamLists the template parameter lists, from the outermost to the
01565 /// innermost template parameter lists.
01566 ///
01567 /// \param NumParamLists the number of template parameter lists in ParamLists.
01568 ///
01569 /// \param IsFriend Whether to apply the slightly different rules for
01570 /// matching template parameters to scope specifiers in friend
01571 /// declarations.
01572 ///
01573 /// \param IsExplicitSpecialization will be set true if the entity being
01574 /// declared is an explicit specialization, false otherwise.
01575 ///
01576 /// \returns the template parameter list, if any, that corresponds to the
01577 /// name that is preceded by the scope specifier @p SS. This template
01578 /// parameter list may have template parameters (if we're declaring a
01579 /// template) or may have no template parameters (if we're declaring a
01580 /// template specialization), or may be NULL (if what we're declaring isn't
01581 /// itself a template).
01582 TemplateParameterList *
01583 Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
01584                                               SourceLocation DeclLoc,
01585                                               const CXXScopeSpec &SS,
01586                                           TemplateParameterList **ParamLists,
01587                                               unsigned NumParamLists,
01588                                               bool IsFriend,
01589                                               bool &IsExplicitSpecialization,
01590                                               bool &Invalid) {
01591   IsExplicitSpecialization = false;
01592   Invalid = false;
01593   
01594   // The sequence of nested types to which we will match up the template
01595   // parameter lists. We first build this list by starting with the type named
01596   // by the nested-name-specifier and walking out until we run out of types.
01597   SmallVector<QualType, 4> NestedTypes;
01598   QualType T;
01599   if (SS.getScopeRep()) {
01600     if (CXXRecordDecl *Record 
01601               = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
01602       T = Context.getTypeDeclType(Record);
01603     else
01604       T = QualType(SS.getScopeRep()->getAsType(), 0);
01605   }
01606   
01607   // If we found an explicit specialization that prevents us from needing
01608   // 'template<>' headers, this will be set to the location of that
01609   // explicit specialization.
01610   SourceLocation ExplicitSpecLoc;
01611   
01612   while (!T.isNull()) {
01613     NestedTypes.push_back(T);
01614     
01615     // Retrieve the parent of a record type.
01616     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
01617       // If this type is an explicit specialization, we're done.
01618       if (ClassTemplateSpecializationDecl *Spec
01619           = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
01620         if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) && 
01621             Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
01622           ExplicitSpecLoc = Spec->getLocation();
01623           break;
01624         }
01625       } else if (Record->getTemplateSpecializationKind()
01626                                                 == TSK_ExplicitSpecialization) {
01627         ExplicitSpecLoc = Record->getLocation();
01628         break;
01629       }
01630       
01631       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
01632         T = Context.getTypeDeclType(Parent);
01633       else
01634         T = QualType();
01635       continue;
01636     } 
01637     
01638     if (const TemplateSpecializationType *TST
01639                                      = T->getAs<TemplateSpecializationType>()) {
01640       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
01641         if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
01642           T = Context.getTypeDeclType(Parent);
01643         else
01644           T = QualType();
01645         continue;        
01646       }
01647     }
01648     
01649     // Look one step prior in a dependent template specialization type.
01650     if (const DependentTemplateSpecializationType *DependentTST
01651                           = T->getAs<DependentTemplateSpecializationType>()) {
01652       if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
01653         T = QualType(NNS->getAsType(), 0);
01654       else
01655         T = QualType();
01656       continue;
01657     }
01658     
01659     // Look one step prior in a dependent name type.
01660     if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
01661       if (NestedNameSpecifier *NNS = DependentName->getQualifier())
01662         T = QualType(NNS->getAsType(), 0);
01663       else
01664         T = QualType();
01665       continue;
01666     }
01667     
01668     // Retrieve the parent of an enumeration type.
01669     if (const EnumType *EnumT = T->getAs<EnumType>()) {
01670       // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
01671       // check here.
01672       EnumDecl *Enum = EnumT->getDecl();
01673       
01674       // Get to the parent type.
01675       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
01676         T = Context.getTypeDeclType(Parent);
01677       else
01678         T = QualType();      
01679       continue;
01680     }
01681 
01682     T = QualType();
01683   }
01684   // Reverse the nested types list, since we want to traverse from the outermost
01685   // to the innermost while checking template-parameter-lists.
01686   std::reverse(NestedTypes.begin(), NestedTypes.end());
01687 
01688   // C++0x [temp.expl.spec]p17:
01689   //   A member or a member template may be nested within many
01690   //   enclosing class templates. In an explicit specialization for
01691   //   such a member, the member declaration shall be preceded by a
01692   //   template<> for each enclosing class template that is
01693   //   explicitly specialized.
01694   bool SawNonEmptyTemplateParameterList = false;
01695   unsigned ParamIdx = 0;
01696   for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
01697        ++TypeIdx) {
01698     T = NestedTypes[TypeIdx];
01699     
01700     // Whether we expect a 'template<>' header.
01701     bool NeedEmptyTemplateHeader = false;
01702 
01703     // Whether we expect a template header with parameters.
01704     bool NeedNonemptyTemplateHeader = false;
01705     
01706     // For a dependent type, the set of template parameters that we
01707     // expect to see.
01708     TemplateParameterList *ExpectedTemplateParams = 0;
01709 
01710     // C++0x [temp.expl.spec]p15:
01711     //   A member or a member template may be nested within many enclosing 
01712     //   class templates. In an explicit specialization for such a member, the 
01713     //   member declaration shall be preceded by a template<> for each 
01714     //   enclosing class template that is explicitly specialized.
01715     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
01716       if (ClassTemplatePartialSpecializationDecl *Partial
01717             = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
01718         ExpectedTemplateParams = Partial->getTemplateParameters();
01719         NeedNonemptyTemplateHeader = true;
01720       } else if (Record->isDependentType()) {
01721         if (Record->getDescribedClassTemplate()) {
01722           ExpectedTemplateParams = Record->getDescribedClassTemplate()
01723                                                       ->getTemplateParameters();
01724           NeedNonemptyTemplateHeader = true;
01725         }
01726       } else if (ClassTemplateSpecializationDecl *Spec
01727                      = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
01728         // C++0x [temp.expl.spec]p4:
01729         //   Members of an explicitly specialized class template are defined
01730         //   in the same manner as members of normal classes, and not using 
01731         //   the template<> syntax. 
01732         if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
01733           NeedEmptyTemplateHeader = true;
01734         else
01735           continue;
01736       } else if (Record->getTemplateSpecializationKind()) {
01737         if (Record->getTemplateSpecializationKind() 
01738                                                 != TSK_ExplicitSpecialization &&
01739             TypeIdx == NumTypes - 1)
01740           IsExplicitSpecialization = true;
01741         
01742         continue;
01743       }
01744     } else if (const TemplateSpecializationType *TST
01745                                      = T->getAs<TemplateSpecializationType>()) {
01746       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {        
01747         ExpectedTemplateParams = Template->getTemplateParameters();
01748         NeedNonemptyTemplateHeader = true;        
01749       }
01750     } else if (T->getAs<DependentTemplateSpecializationType>()) {
01751       // FIXME:  We actually could/should check the template arguments here
01752       // against the corresponding template parameter list.
01753       NeedNonemptyTemplateHeader = false;
01754     } 
01755     
01756     // C++ [temp.expl.spec]p16:
01757     //   In an explicit specialization declaration for a member of a class 
01758     //   template or a member template that ap- pears in namespace scope, the 
01759     //   member template and some of its enclosing class templates may remain 
01760     //   unspecialized, except that the declaration shall not explicitly 
01761     //   specialize a class member template if its en- closing class templates 
01762     //   are not explicitly specialized as well.
01763     if (ParamIdx < NumParamLists) {
01764       if (ParamLists[ParamIdx]->size() == 0) {
01765         if (SawNonEmptyTemplateParameterList) {
01766           Diag(DeclLoc, diag::err_specialize_member_of_template)
01767             << ParamLists[ParamIdx]->getSourceRange();
01768           Invalid = true;
01769           IsExplicitSpecialization = false;
01770           return 0;
01771         }
01772       } else
01773         SawNonEmptyTemplateParameterList = true;
01774     }
01775     
01776     if (NeedEmptyTemplateHeader) {
01777       // If we're on the last of the types, and we need a 'template<>' header
01778       // here, then it's an explicit specialization.
01779       if (TypeIdx == NumTypes - 1)
01780         IsExplicitSpecialization = true;
01781       
01782       if (ParamIdx < NumParamLists) {
01783         if (ParamLists[ParamIdx]->size() > 0) {
01784           // The header has template parameters when it shouldn't. Complain.
01785           Diag(ParamLists[ParamIdx]->getTemplateLoc(), 
01786                diag::err_template_param_list_matches_nontemplate)
01787             << T
01788             << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
01789                            ParamLists[ParamIdx]->getRAngleLoc())
01790             << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
01791           Invalid = true;
01792           return 0;
01793         }
01794         
01795         // Consume this template header.
01796         ++ParamIdx;
01797         continue;
01798       } 
01799       
01800       if (!IsFriend) {
01801         // We don't have a template header, but we should.
01802         SourceLocation ExpectedTemplateLoc;
01803         if (NumParamLists > 0)
01804           ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
01805         else
01806           ExpectedTemplateLoc = DeclStartLoc;
01807 
01808         Diag(DeclLoc, diag::err_template_spec_needs_header)
01809           << getRangeOfTypeInNestedNameSpecifier(Context, T, SS)
01810           << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
01811       }
01812       
01813       continue;
01814     }
01815     
01816     if (NeedNonemptyTemplateHeader) {
01817       // In friend declarations we can have template-ids which don't
01818       // depend on the corresponding template parameter lists.  But
01819       // assume that empty parameter lists are supposed to match this
01820       // template-id.
01821       if (IsFriend && T->isDependentType()) {
01822         if (ParamIdx < NumParamLists &&
01823             DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
01824           ExpectedTemplateParams = 0;
01825         else 
01826           continue;
01827       }
01828 
01829       if (ParamIdx < NumParamLists) {
01830         // Check the template parameter list, if we can.        
01831         if (ExpectedTemplateParams &&
01832             !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
01833                                             ExpectedTemplateParams,
01834                                             true, TPL_TemplateMatch))
01835           Invalid = true;
01836         
01837         if (!Invalid &&
01838             CheckTemplateParameterList(ParamLists[ParamIdx], 0,
01839                                        TPC_ClassTemplateMember))
01840           Invalid = true;
01841         
01842         ++ParamIdx;
01843         continue;
01844       }
01845       
01846       Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
01847         << T
01848         << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
01849       Invalid = true;
01850       continue;
01851     }
01852   }
01853     
01854   // If there were at least as many template-ids as there were template
01855   // parameter lists, then there are no template parameter lists remaining for
01856   // the declaration itself.
01857   if (ParamIdx >= NumParamLists)
01858     return 0;
01859 
01860   // If there were too many template parameter lists, complain about that now.
01861   if (ParamIdx < NumParamLists - 1) {
01862     bool HasAnyExplicitSpecHeader = false;
01863     bool AllExplicitSpecHeaders = true;
01864     for (unsigned I = ParamIdx; I != NumParamLists - 1; ++I) {
01865       if (ParamLists[I]->size() == 0)
01866         HasAnyExplicitSpecHeader = true;
01867       else
01868         AllExplicitSpecHeaders = false;
01869     }
01870     
01871     Diag(ParamLists[ParamIdx]->getTemplateLoc(),
01872          AllExplicitSpecHeaders? diag::warn_template_spec_extra_headers
01873                                : diag::err_template_spec_extra_headers)
01874       << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
01875                      ParamLists[NumParamLists - 2]->getRAngleLoc());
01876 
01877     // If there was a specialization somewhere, such that 'template<>' is
01878     // not required, and there were any 'template<>' headers, note where the
01879     // specialization occurred.
01880     if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
01881       Diag(ExplicitSpecLoc, 
01882            diag::note_explicit_template_spec_does_not_need_header)
01883         << NestedTypes.back();
01884     
01885     // We have a template parameter list with no corresponding scope, which
01886     // means that the resulting template declaration can't be instantiated
01887     // properly (we'll end up with dependent nodes when we shouldn't).
01888     if (!AllExplicitSpecHeaders)
01889       Invalid = true;
01890   }
01891 
01892   // C++ [temp.expl.spec]p16:
01893   //   In an explicit specialization declaration for a member of a class 
01894   //   template or a member template that ap- pears in namespace scope, the 
01895   //   member template and some of its enclosing class templates may remain 
01896   //   unspecialized, except that the declaration shall not explicitly 
01897   //   specialize a class member template if its en- closing class templates 
01898   //   are not explicitly specialized as well.
01899   if (ParamLists[NumParamLists - 1]->size() == 0 && 
01900       SawNonEmptyTemplateParameterList) {
01901     Diag(DeclLoc, diag::err_specialize_member_of_template)
01902       << ParamLists[ParamIdx]->getSourceRange();
01903     Invalid = true;
01904     IsExplicitSpecialization = false;
01905     return 0;
01906   }
01907   
01908   // Return the last template parameter list, which corresponds to the
01909   // entity being declared.
01910   return ParamLists[NumParamLists - 1];
01911 }
01912 
01913 void Sema::NoteAllFoundTemplates(TemplateName Name) {
01914   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
01915     Diag(Template->getLocation(), diag::note_template_declared_here)
01916       << (isa<FunctionTemplateDecl>(Template)? 0
01917           : isa<ClassTemplateDecl>(Template)? 1
01918           : isa<TypeAliasTemplateDecl>(Template)? 2
01919           : 3)
01920       << Template->getDeclName();
01921     return;
01922   }
01923   
01924   if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
01925     for (OverloadedTemplateStorage::iterator I = OST->begin(), 
01926                                           IEnd = OST->end();
01927          I != IEnd; ++I)
01928       Diag((*I)->getLocation(), diag::note_template_declared_here)
01929         << 0 << (*I)->getDeclName();
01930     
01931     return;
01932   }
01933 }
01934 
01935 QualType Sema::CheckTemplateIdType(TemplateName Name,
01936                                    SourceLocation TemplateLoc,
01937                                    TemplateArgumentListInfo &TemplateArgs) {
01938   DependentTemplateName *DTN
01939     = Name.getUnderlying().getAsDependentTemplateName();
01940   if (DTN && DTN->isIdentifier())
01941     // When building a template-id where the template-name is dependent,
01942     // assume the template is a type template. Either our assumption is
01943     // correct, or the code is ill-formed and will be diagnosed when the
01944     // dependent name is substituted.
01945     return Context.getDependentTemplateSpecializationType(ETK_None,
01946                                                           DTN->getQualifier(),
01947                                                           DTN->getIdentifier(),
01948                                                           TemplateArgs);
01949 
01950   TemplateDecl *Template = Name.getAsTemplateDecl();
01951   if (!Template || isa<FunctionTemplateDecl>(Template)) {
01952     // We might have a substituted template template parameter pack. If so,
01953     // build a template specialization type for it.
01954     if (Name.getAsSubstTemplateTemplateParmPack())
01955       return Context.getTemplateSpecializationType(Name, TemplateArgs);
01956 
01957     Diag(TemplateLoc, diag::err_template_id_not_a_type)
01958       << Name;
01959     NoteAllFoundTemplates(Name);
01960     return QualType();
01961   }
01962 
01963   // Check that the template argument list is well-formed for this
01964   // template.
01965   SmallVector<TemplateArgument, 4> Converted;
01966   bool ExpansionIntoFixedList = false;
01967   if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
01968                                 false, Converted, &ExpansionIntoFixedList))
01969     return QualType();
01970 
01971   QualType CanonType;
01972 
01973   bool InstantiationDependent = false;
01974   TypeAliasTemplateDecl *AliasTemplate = 0;
01975   if (!ExpansionIntoFixedList &&
01976       (AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Template))) {
01977     // Find the canonical type for this type alias template specialization.
01978     TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
01979     if (Pattern->isInvalidDecl())
01980       return QualType();
01981 
01982     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
01983                                       Converted.data(), Converted.size());
01984 
01985     // Only substitute for the innermost template argument list.
01986     MultiLevelTemplateArgumentList TemplateArgLists;
01987     TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
01988     unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
01989     for (unsigned I = 0; I < Depth; ++I)
01990       TemplateArgLists.addOuterTemplateArguments(0, 0);
01991 
01992     InstantiatingTemplate Inst(*this, TemplateLoc, Template);
01993     CanonType = SubstType(Pattern->getUnderlyingType(),
01994                           TemplateArgLists, AliasTemplate->getLocation(),
01995                           AliasTemplate->getDeclName());
01996     if (CanonType.isNull())
01997       return QualType();
01998   } else if (Name.isDependent() ||
01999              TemplateSpecializationType::anyDependentTemplateArguments(
02000                TemplateArgs, InstantiationDependent)) {
02001     // This class template specialization is a dependent
02002     // type. Therefore, its canonical type is another class template
02003     // specialization type that contains all of the converted
02004     // arguments in canonical form. This ensures that, e.g., A<T> and
02005     // A<T, T> have identical types when A is declared as:
02006     //
02007     //   template<typename T, typename U = T> struct A;
02008     TemplateName CanonName = Context.getCanonicalTemplateName(Name);
02009     CanonType = Context.getTemplateSpecializationType(CanonName,
02010                                                       Converted.data(),
02011                                                       Converted.size());
02012 
02013     // FIXME: CanonType is not actually the canonical type, and unfortunately
02014     // it is a TemplateSpecializationType that we will never use again.
02015     // In the future, we need to teach getTemplateSpecializationType to only
02016     // build the canonical type and return that to us.
02017     CanonType = Context.getCanonicalType(CanonType);
02018 
02019     // This might work out to be a current instantiation, in which
02020     // case the canonical type needs to be the InjectedClassNameType.
02021     //
02022     // TODO: in theory this could be a simple hashtable lookup; most
02023     // changes to CurContext don't change the set of current
02024     // instantiations.
02025     if (isa<ClassTemplateDecl>(Template)) {
02026       for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
02027         // If we get out to a namespace, we're done.
02028         if (Ctx->isFileContext()) break;
02029 
02030         // If this isn't a record, keep looking.
02031         CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
02032         if (!Record) continue;
02033 
02034         // Look for one of the two cases with InjectedClassNameTypes
02035         // and check whether it's the same template.
02036         if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
02037             !Record->getDescribedClassTemplate())
02038           continue;
02039 
02040         // Fetch the injected class name type and check whether its
02041         // injected type is equal to the type we just built.
02042         QualType ICNT = Context.getTypeDeclType(Record);
02043         QualType Injected = cast<InjectedClassNameType>(ICNT)
02044           ->getInjectedSpecializationType();
02045 
02046         if (CanonType != Injected->getCanonicalTypeInternal())
02047           continue;
02048 
02049         // If so, the canonical type of this TST is the injected
02050         // class name type of the record we just found.
02051         assert(ICNT.isCanonical());
02052         CanonType = ICNT;
02053         break;
02054       }
02055     }
02056   } else if (ClassTemplateDecl *ClassTemplate
02057                = dyn_cast<ClassTemplateDecl>(Template)) {
02058     // Find the class template specialization declaration that
02059     // corresponds to these arguments.
02060     void *InsertPos = 0;
02061     ClassTemplateSpecializationDecl *Decl
02062       = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
02063                                           InsertPos);
02064     if (!Decl) {
02065       // This is the first time we have referenced this class template
02066       // specialization. Create the canonical declaration and add it to
02067       // the set of specializations.
02068       Decl = ClassTemplateSpecializationDecl::Create(Context,
02069                             ClassTemplate->getTemplatedDecl()->getTagKind(),
02070                                                 ClassTemplate->getDeclContext(),
02071                             ClassTemplate->getTemplatedDecl()->getLocStart(),
02072                                                 ClassTemplate->getLocation(),
02073                                                      ClassTemplate,
02074                                                      Converted.data(),
02075                                                      Converted.size(), 0);
02076       ClassTemplate->AddSpecialization(Decl, InsertPos);
02077       Decl->setLexicalDeclContext(CurContext);
02078     }
02079 
02080     CanonType = Context.getTypeDeclType(Decl);
02081     assert(isa<RecordType>(CanonType) &&
02082            "type of non-dependent specialization is not a RecordType");
02083   }
02084 
02085   // Build the fully-sugared type for this class template
02086   // specialization, which refers back to the class template
02087   // specialization we created or found.
02088   return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
02089 }
02090 
02091 TypeResult
02092 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
02093                           TemplateTy TemplateD, SourceLocation TemplateLoc,
02094                           SourceLocation LAngleLoc,
02095                           ASTTemplateArgsPtr TemplateArgsIn,
02096                           SourceLocation RAngleLoc,
02097                           bool IsCtorOrDtorName) {
02098   if (SS.isInvalid())
02099     return true;
02100 
02101   TemplateName Template = TemplateD.getAsVal<TemplateName>();
02102 
02103   // Translate the parser's template argument list in our AST format.
02104   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
02105   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
02106 
02107   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
02108     QualType T
02109       = Context.getDependentTemplateSpecializationType(ETK_None,
02110                                                        DTN->getQualifier(),
02111                                                        DTN->getIdentifier(),
02112                                                        TemplateArgs);
02113     // Build type-source information.
02114     TypeLocBuilder TLB;
02115     DependentTemplateSpecializationTypeLoc SpecTL
02116       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
02117     SpecTL.setElaboratedKeywordLoc(SourceLocation());
02118     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
02119     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
02120     SpecTL.setTemplateNameLoc(TemplateLoc);
02121     SpecTL.setLAngleLoc(LAngleLoc);
02122     SpecTL.setRAngleLoc(RAngleLoc);
02123     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
02124       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
02125     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
02126   }
02127   
02128   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
02129   TemplateArgsIn.release();
02130 
02131   if (Result.isNull())
02132     return true;
02133 
02134   // Build type-source information.
02135   TypeLocBuilder TLB;
02136   TemplateSpecializationTypeLoc SpecTL
02137     = TLB.push<TemplateSpecializationTypeLoc>(Result);
02138   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
02139   SpecTL.setTemplateNameLoc(TemplateLoc);
02140   SpecTL.setLAngleLoc(LAngleLoc);
02141   SpecTL.setRAngleLoc(RAngleLoc);
02142   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
02143     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
02144 
02145   // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
02146   // constructor or destructor name (in such a case, the scope specifier
02147   // will be attached to the enclosing Decl or Expr node).
02148   if (SS.isNotEmpty() && !IsCtorOrDtorName) {
02149     // Create an elaborated-type-specifier containing the nested-name-specifier.
02150     Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
02151     ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
02152     ElabTL.setElaboratedKeywordLoc(SourceLocation());
02153     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
02154   }
02155   
02156   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
02157 }
02158 
02159 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
02160                                         TypeSpecifierType TagSpec,
02161                                         SourceLocation TagLoc,
02162                                         CXXScopeSpec &SS,
02163                                         SourceLocation TemplateKWLoc,
02164                                         TemplateTy TemplateD,
02165                                         SourceLocation TemplateLoc,
02166                                         SourceLocation LAngleLoc,
02167                                         ASTTemplateArgsPtr TemplateArgsIn,
02168                                         SourceLocation RAngleLoc) {
02169   TemplateName Template = TemplateD.getAsVal<TemplateName>();
02170   
02171   // Translate the parser's template argument list in our AST format.
02172   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
02173   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
02174   
02175   // Determine the tag kind
02176   TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
02177   ElaboratedTypeKeyword Keyword
02178     = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
02179 
02180   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
02181     QualType T = Context.getDependentTemplateSpecializationType(Keyword,
02182                                                           DTN->getQualifier(), 
02183                                                           DTN->getIdentifier(), 
02184                                                                 TemplateArgs);
02185     
02186     // Build type-source information.    
02187     TypeLocBuilder TLB;
02188     DependentTemplateSpecializationTypeLoc SpecTL
02189       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
02190     SpecTL.setElaboratedKeywordLoc(TagLoc);
02191     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
02192     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
02193     SpecTL.setTemplateNameLoc(TemplateLoc);
02194     SpecTL.setLAngleLoc(LAngleLoc);
02195     SpecTL.setRAngleLoc(RAngleLoc);
02196     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
02197       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
02198     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
02199   }
02200 
02201   if (TypeAliasTemplateDecl *TAT =
02202         dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
02203     // C++0x [dcl.type.elab]p2:
02204     //   If the identifier resolves to a typedef-name or the simple-template-id
02205     //   resolves to an alias template specialization, the
02206     //   elaborated-type-specifier is ill-formed.
02207     Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
02208     Diag(TAT->getLocation(), diag::note_declared_at);
02209   }
02210   
02211   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
02212   if (Result.isNull())
02213     return TypeResult(true);
02214   
02215   // Check the tag kind
02216   if (const RecordType *RT = Result->getAs<RecordType>()) {
02217     RecordDecl *D = RT->getDecl();
02218     
02219     IdentifierInfo *Id = D->getIdentifier();
02220     assert(Id && "templated class must have an identifier");
02221     
02222     if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
02223                                       TagLoc, *Id)) {
02224       Diag(TagLoc, diag::err_use_with_wrong_tag)
02225         << Result
02226         << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
02227       Diag(D->getLocation(), diag::note_previous_use);
02228     }
02229   }
02230 
02231   // Provide source-location information for the template specialization.
02232   TypeLocBuilder TLB;
02233   TemplateSpecializationTypeLoc SpecTL
02234     = TLB.push<TemplateSpecializationTypeLoc>(Result);
02235   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
02236   SpecTL.setTemplateNameLoc(TemplateLoc);
02237   SpecTL.setLAngleLoc(LAngleLoc);
02238   SpecTL.setRAngleLoc(RAngleLoc);
02239   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
02240     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
02241 
02242   // Construct an elaborated type containing the nested-name-specifier (if any)
02243   // and tag keyword.
02244   Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
02245   ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
02246   ElabTL.setElaboratedKeywordLoc(TagLoc);
02247   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
02248   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
02249 }
02250 
02251 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
02252                                      SourceLocation TemplateKWLoc,
02253                                      LookupResult &R,
02254                                      bool RequiresADL,
02255                                  const TemplateArgumentListInfo *TemplateArgs) {
02256   // FIXME: Can we do any checking at this point? I guess we could check the
02257   // template arguments that we have against the template name, if the template
02258   // name refers to a single template. That's not a terribly common case,
02259   // though.
02260   // foo<int> could identify a single function unambiguously
02261   // This approach does NOT work, since f<int>(1);
02262   // gets resolved prior to resorting to overload resolution
02263   // i.e., template<class T> void f(double);
02264   //       vs template<class T, class U> void f(U);
02265 
02266   // These should be filtered out by our callers.
02267   assert(!R.empty() && "empty lookup results when building templateid");
02268   assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
02269 
02270   // We don't want lookup warnings at this point.
02271   R.suppressDiagnostics();
02272 
02273   UnresolvedLookupExpr *ULE
02274     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
02275                                    SS.getWithLocInContext(Context),
02276                                    TemplateKWLoc,
02277                                    R.getLookupNameInfo(),
02278                                    RequiresADL, TemplateArgs,
02279                                    R.begin(), R.end());
02280 
02281   return Owned(ULE);
02282 }
02283 
02284 // We actually only call this from template instantiation.
02285 ExprResult
02286 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
02287                                    SourceLocation TemplateKWLoc,
02288                                    const DeclarationNameInfo &NameInfo,
02289                              const TemplateArgumentListInfo *TemplateArgs) {
02290   assert(TemplateArgs || TemplateKWLoc.isValid());
02291   DeclContext *DC;
02292   if (!(DC = computeDeclContext(SS, false)) ||
02293       DC->isDependentContext() ||
02294       RequireCompleteDeclContext(SS, DC))
02295     return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
02296 
02297   bool MemberOfUnknownSpecialization;
02298   LookupResult R(*this, NameInfo, LookupOrdinaryName);
02299   LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
02300                      MemberOfUnknownSpecialization);
02301 
02302   if (R.isAmbiguous())
02303     return ExprError();
02304 
02305   if (R.empty()) {
02306     Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
02307       << NameInfo.getName() << SS.getRange();
02308     return ExprError();
02309   }
02310 
02311   if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
02312     Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
02313       << (NestedNameSpecifier*) SS.getScopeRep()
02314       << NameInfo.getName() << SS.getRange();
02315     Diag(Temp->getLocation(), diag::note_referenced_class_template);
02316     return ExprError();
02317   }
02318 
02319   return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
02320 }
02321 
02322 /// \brief Form a dependent template name.
02323 ///
02324 /// This action forms a dependent template name given the template
02325 /// name and its (presumably dependent) scope specifier. For
02326 /// example, given "MetaFun::template apply", the scope specifier \p
02327 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
02328 /// of the "template" keyword, and "apply" is the \p Name.
02329 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
02330                                                   CXXScopeSpec &SS,
02331                                                   SourceLocation TemplateKWLoc,
02332                                                   UnqualifiedId &Name,
02333                                                   ParsedType ObjectType,
02334                                                   bool EnteringContext,
02335                                                   TemplateTy &Result) {
02336   if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
02337     Diag(TemplateKWLoc,
02338          getLangOpts().CPlusPlus0x ?
02339            diag::warn_cxx98_compat_template_outside_of_template :
02340            diag::ext_template_outside_of_template)
02341       << FixItHint::CreateRemoval(TemplateKWLoc);
02342 
02343   DeclContext *LookupCtx = 0;
02344   if (SS.isSet())
02345     LookupCtx = computeDeclContext(SS, EnteringContext);
02346   if (!LookupCtx && ObjectType)
02347     LookupCtx = computeDeclContext(ObjectType.get());
02348   if (LookupCtx) {
02349     // C++0x [temp.names]p5:
02350     //   If a name prefixed by the keyword template is not the name of
02351     //   a template, the program is ill-formed. [Note: the keyword
02352     //   template may not be applied to non-template members of class
02353     //   templates. -end note ] [ Note: as is the case with the
02354     //   typename prefix, the template prefix is allowed in cases
02355     //   where it is not strictly necessary; i.e., when the
02356     //   nested-name-specifier or the expression on the left of the ->
02357     //   or . is not dependent on a template-parameter, or the use
02358     //   does not appear in the scope of a template. -end note]
02359     //
02360     // Note: C++03 was more strict here, because it banned the use of
02361     // the "template" keyword prior to a template-name that was not a
02362     // dependent name. C++ DR468 relaxed this requirement (the
02363     // "template" keyword is now permitted). We follow the C++0x
02364     // rules, even in C++03 mode with a warning, retroactively applying the DR.
02365     bool MemberOfUnknownSpecialization;
02366     TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
02367                                           ObjectType, EnteringContext, Result,
02368                                           MemberOfUnknownSpecialization);
02369     if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
02370         isa<CXXRecordDecl>(LookupCtx) &&
02371         (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
02372          cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
02373       // This is a dependent template. Handle it below.
02374     } else if (TNK == TNK_Non_template) {
02375       Diag(Name.getLocStart(),
02376            diag::err_template_kw_refers_to_non_template)
02377         << GetNameFromUnqualifiedId(Name).getName()
02378         << Name.getSourceRange()
02379         << TemplateKWLoc;
02380       return TNK_Non_template;
02381     } else {
02382       // We found something; return it.
02383       return TNK;
02384     }
02385   }
02386 
02387   NestedNameSpecifier *Qualifier
02388     = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
02389 
02390   switch (Name.getKind()) {
02391   case UnqualifiedId::IK_Identifier:
02392     Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
02393                                                               Name.Identifier));
02394     return TNK_Dependent_template_name;
02395 
02396   case UnqualifiedId::IK_OperatorFunctionId:
02397     Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
02398                                              Name.OperatorFunctionId.Operator));
02399     return TNK_Dependent_template_name;
02400 
02401   case UnqualifiedId::IK_LiteralOperatorId:
02402     llvm_unreachable(
02403             "We don't support these; Parse shouldn't have allowed propagation");
02404 
02405   default:
02406     break;
02407   }
02408 
02409   Diag(Name.getLocStart(),
02410        diag::err_template_kw_refers_to_non_template)
02411     << GetNameFromUnqualifiedId(Name).getName()
02412     << Name.getSourceRange()
02413     << TemplateKWLoc;
02414   return TNK_Non_template;
02415 }
02416 
02417 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
02418                                      const TemplateArgumentLoc &AL,
02419                           SmallVectorImpl<TemplateArgument> &Converted) {
02420   const TemplateArgument &Arg = AL.getArgument();
02421 
02422   // Check template type parameter.
02423   switch(Arg.getKind()) {
02424   case TemplateArgument::Type:
02425     // C++ [temp.arg.type]p1:
02426     //   A template-argument for a template-parameter which is a
02427     //   type shall be a type-id.
02428     break;
02429   case TemplateArgument::Template: {
02430     // We have a template type parameter but the template argument
02431     // is a template without any arguments.
02432     SourceRange SR = AL.getSourceRange();
02433     TemplateName Name = Arg.getAsTemplate();
02434     Diag(SR.getBegin(), diag::err_template_missing_args)
02435       << Name << SR;
02436     if (TemplateDecl *Decl = Name.getAsTemplateDecl())
02437       Diag(Decl->getLocation(), diag::note_template_decl_here);
02438 
02439     return true;
02440   }
02441   case TemplateArgument::Expression: {
02442     // We have a template type parameter but the template argument is an
02443     // expression; see if maybe it is missing the "typename" keyword.
02444     CXXScopeSpec SS;
02445     DeclarationNameInfo NameInfo;
02446 
02447     if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
02448       SS.Adopt(ArgExpr->getQualifierLoc());
02449       NameInfo = ArgExpr->getNameInfo();
02450     } else if (DependentScopeDeclRefExpr *ArgExpr =
02451                dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
02452       SS.Adopt(ArgExpr->getQualifierLoc());
02453       NameInfo = ArgExpr->getNameInfo();
02454     } else if (CXXDependentScopeMemberExpr *ArgExpr =
02455                dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
02456       SS.Adopt(ArgExpr->getQualifierLoc());
02457       NameInfo = ArgExpr->getMemberNameInfo();
02458     }
02459 
02460     if (NameInfo.getName()) {
02461       LookupResult Result(*this, NameInfo, LookupOrdinaryName);
02462       LookupParsedName(Result, CurScope, &SS);
02463 
02464       bool CouldBeType = Result.getResultKind() ==
02465           LookupResult::NotFoundInCurrentInstantiation;
02466 
02467       for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
02468            !CouldBeType && I != IEnd; ++I) {
02469         CouldBeType = isa<TypeDecl>(*I);
02470       }
02471       if (CouldBeType) {
02472         SourceLocation Loc = AL.getSourceRange().getBegin();
02473         Diag(Loc, diag::err_template_arg_must_be_type_suggest);
02474         Diag(Param->getLocation(), diag::note_template_param_here);
02475         return true;
02476       }
02477     }
02478     // fallthrough
02479   }
02480   default: {
02481     // We have a template type parameter but the template argument
02482     // is not a type.
02483     SourceRange SR = AL.getSourceRange();
02484     Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
02485     Diag(Param->getLocation(), diag::note_template_param_here);
02486 
02487     return true;
02488   }
02489   }
02490 
02491   if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
02492     return true;
02493 
02494   // Add the converted template type argument.
02495   QualType ArgType = Context.getCanonicalType(Arg.getAsType());
02496   
02497   // Objective-C ARC:
02498   //   If an explicitly-specified template argument type is a lifetime type
02499   //   with no lifetime qualifier, the __strong lifetime qualifier is inferred.
02500   if (getLangOpts().ObjCAutoRefCount &&
02501       ArgType->isObjCLifetimeType() &&
02502       !ArgType.getObjCLifetime()) {
02503     Qualifiers Qs;
02504     Qs.setObjCLifetime(Qualifiers::OCL_Strong);
02505     ArgType = Context.getQualifiedType(ArgType, Qs);
02506   }
02507   
02508   Converted.push_back(TemplateArgument(ArgType));
02509   return false;
02510 }
02511 
02512 /// \brief Substitute template arguments into the default template argument for
02513 /// the given template type parameter.
02514 ///
02515 /// \param SemaRef the semantic analysis object for which we are performing
02516 /// the substitution.
02517 ///
02518 /// \param Template the template that we are synthesizing template arguments
02519 /// for.
02520 ///
02521 /// \param TemplateLoc the location of the template name that started the
02522 /// template-id we are checking.
02523 ///
02524 /// \param RAngleLoc the location of the right angle bracket ('>') that
02525 /// terminates the template-id.
02526 ///
02527 /// \param Param the template template parameter whose default we are
02528 /// substituting into.
02529 ///
02530 /// \param Converted the list of template arguments provided for template
02531 /// parameters that precede \p Param in the template parameter list.
02532 /// \returns the substituted template argument, or NULL if an error occurred.
02533 static TypeSourceInfo *
02534 SubstDefaultTemplateArgument(Sema &SemaRef,
02535                              TemplateDecl *Template,
02536                              SourceLocation TemplateLoc,
02537                              SourceLocation RAngleLoc,
02538                              TemplateTypeParmDecl *Param,
02539                          SmallVectorImpl<TemplateArgument> &Converted) {
02540   TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
02541 
02542   // If the argument type is dependent, instantiate it now based
02543   // on the previously-computed template arguments.
02544   if (ArgType->getType()->isDependentType()) {
02545     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
02546                                       Converted.data(), Converted.size());
02547 
02548     MultiLevelTemplateArgumentList AllTemplateArgs
02549       = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
02550 
02551     Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
02552                                      Template, Converted.data(),
02553                                      Converted.size(),
02554                                      SourceRange(TemplateLoc, RAngleLoc));
02555 
02556     Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
02557     ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
02558                                 Param->getDefaultArgumentLoc(),
02559                                 Param->getDeclName());
02560   }
02561 
02562   return ArgType;
02563 }
02564 
02565 /// \brief Substitute template arguments into the default template argument for
02566 /// the given non-type template parameter.
02567 ///
02568 /// \param SemaRef the semantic analysis object for which we are performing
02569 /// the substitution.
02570 ///
02571 /// \param Template the template that we are synthesizing template arguments
02572 /// for.
02573 ///
02574 /// \param TemplateLoc the location of the template name that started the
02575 /// template-id we are checking.
02576 ///
02577 /// \param RAngleLoc the location of the right angle bracket ('>') that
02578 /// terminates the template-id.
02579 ///
02580 /// \param Param the non-type template parameter whose default we are
02581 /// substituting into.
02582 ///
02583 /// \param Converted the list of template arguments provided for template
02584 /// parameters that precede \p Param in the template parameter list.
02585 ///
02586 /// \returns the substituted template argument, or NULL if an error occurred.
02587 static ExprResult
02588 SubstDefaultTemplateArgument(Sema &SemaRef,
02589                              TemplateDecl *Template,
02590                              SourceLocation TemplateLoc,
02591                              SourceLocation RAngleLoc,
02592                              NonTypeTemplateParmDecl *Param,
02593                         SmallVectorImpl<TemplateArgument> &Converted) {
02594   TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
02595                                     Converted.data(), Converted.size());
02596 
02597   MultiLevelTemplateArgumentList AllTemplateArgs
02598     = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
02599 
02600   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
02601                                    Template, Converted.data(),
02602                                    Converted.size(),
02603                                    SourceRange(TemplateLoc, RAngleLoc));
02604 
02605   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
02606   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
02607   return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
02608 }
02609 
02610 /// \brief Substitute template arguments into the default template argument for
02611 /// the given template template parameter.
02612 ///
02613 /// \param SemaRef the semantic analysis object for which we are performing
02614 /// the substitution.
02615 ///
02616 /// \param Template the template that we are synthesizing template arguments
02617 /// for.
02618 ///
02619 /// \param TemplateLoc the location of the template name that started the
02620 /// template-id we are checking.
02621 ///
02622 /// \param RAngleLoc the location of the right angle bracket ('>') that
02623 /// terminates the template-id.
02624 ///
02625 /// \param Param the template template parameter whose default we are
02626 /// substituting into.
02627 ///
02628 /// \param Converted the list of template arguments provided for template
02629 /// parameters that precede \p Param in the template parameter list.
02630 ///
02631 /// \param QualifierLoc Will be set to the nested-name-specifier (with 
02632 /// source-location information) that precedes the template name.
02633 ///
02634 /// \returns the substituted template argument, or NULL if an error occurred.
02635 static TemplateName
02636 SubstDefaultTemplateArgument(Sema &SemaRef,
02637                              TemplateDecl *Template,
02638                              SourceLocation TemplateLoc,
02639                              SourceLocation RAngleLoc,
02640                              TemplateTemplateParmDecl *Param,
02641                        SmallVectorImpl<TemplateArgument> &Converted,
02642                              NestedNameSpecifierLoc &QualifierLoc) {
02643   TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
02644                                     Converted.data(), Converted.size());
02645 
02646   MultiLevelTemplateArgumentList AllTemplateArgs
02647     = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
02648 
02649   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
02650                                    Template, Converted.data(),
02651                                    Converted.size(),
02652                                    SourceRange(TemplateLoc, RAngleLoc));
02653 
02654   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
02655   // Substitute into the nested-name-specifier first, 
02656   QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
02657   if (QualifierLoc) {
02658     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 
02659                                                        AllTemplateArgs);
02660     if (!QualifierLoc)
02661       return TemplateName();
02662   }
02663   
02664   return SemaRef.SubstTemplateName(QualifierLoc,
02665                       Param->getDefaultArgument().getArgument().getAsTemplate(),
02666                               Param->getDefaultArgument().getTemplateNameLoc(),
02667                                    AllTemplateArgs);
02668 }
02669 
02670 /// \brief If the given template parameter has a default template
02671 /// argument, substitute into that default template argument and
02672 /// return the corresponding template argument.
02673 TemplateArgumentLoc
02674 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
02675                                               SourceLocation TemplateLoc,
02676                                               SourceLocation RAngleLoc,
02677                                               Decl *Param,
02678                       SmallVectorImpl<TemplateArgument> &Converted) {
02679    if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
02680     if (!TypeParm->hasDefaultArgument())
02681       return TemplateArgumentLoc();
02682 
02683     TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
02684                                                       TemplateLoc,
02685                                                       RAngleLoc,
02686                                                       TypeParm,
02687                                                       Converted);
02688     if (DI)
02689       return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
02690 
02691     return TemplateArgumentLoc();
02692   }
02693 
02694   if (NonTypeTemplateParmDecl *NonTypeParm
02695         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
02696     if (!NonTypeParm->hasDefaultArgument())
02697       return TemplateArgumentLoc();
02698 
02699     ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
02700                                                   TemplateLoc,
02701                                                   RAngleLoc,
02702                                                   NonTypeParm,
02703                                                   Converted);
02704     if (Arg.isInvalid())
02705       return TemplateArgumentLoc();
02706 
02707     Expr *ArgE = Arg.takeAs<Expr>();
02708     return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
02709   }
02710 
02711   TemplateTemplateParmDecl *TempTempParm
02712     = cast<TemplateTemplateParmDecl>(Param);
02713   if (!TempTempParm->hasDefaultArgument())
02714     return TemplateArgumentLoc();
02715 
02716 
02717   NestedNameSpecifierLoc QualifierLoc;
02718   TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
02719                                                     TemplateLoc,
02720                                                     RAngleLoc,
02721                                                     TempTempParm,
02722                                                     Converted,
02723                                                     QualifierLoc);
02724   if (TName.isNull())
02725     return TemplateArgumentLoc();
02726 
02727   return TemplateArgumentLoc(TemplateArgument(TName),
02728                 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
02729                 TempTempParm->getDefaultArgument().getTemplateNameLoc());
02730 }
02731 
02732 /// \brief Check that the given template argument corresponds to the given
02733 /// template parameter.
02734 ///
02735 /// \param Param The template parameter against which the argument will be
02736 /// checked.
02737 ///
02738 /// \param Arg The template argument.
02739 ///
02740 /// \param Template The template in which the template argument resides.
02741 ///
02742 /// \param TemplateLoc The location of the template name for the template
02743 /// whose argument list we're matching.
02744 ///
02745 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
02746 /// the template argument list.
02747 ///
02748 /// \param ArgumentPackIndex The index into the argument pack where this
02749 /// argument will be placed. Only valid if the parameter is a parameter pack.
02750 ///
02751 /// \param Converted The checked, converted argument will be added to the
02752 /// end of this small vector.
02753 ///
02754 /// \param CTAK Describes how we arrived at this particular template argument:
02755 /// explicitly written, deduced, etc.
02756 ///
02757 /// \returns true on error, false otherwise.
02758 bool Sema::CheckTemplateArgument(NamedDecl *Param,
02759                                  const TemplateArgumentLoc &Arg,
02760                                  NamedDecl *Template,
02761                                  SourceLocation TemplateLoc,
02762                                  SourceLocation RAngleLoc,
02763                                  unsigned ArgumentPackIndex,
02764                             SmallVectorImpl<TemplateArgument> &Converted,
02765                                  CheckTemplateArgumentKind CTAK) {
02766   // Check template type parameters.
02767   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
02768     return CheckTemplateTypeArgument(TTP, Arg, Converted);
02769 
02770   // Check non-type template parameters.
02771   if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
02772     // Do substitution on the type of the non-type template parameter
02773     // with the template arguments we've seen thus far.  But if the
02774     // template has a dependent context then we cannot substitute yet.
02775     QualType NTTPType = NTTP->getType();
02776     if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
02777       NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
02778 
02779     if (NTTPType->isDependentType() &&
02780         !isa<TemplateTemplateParmDecl>(Template) &&
02781         !Template->getDeclContext()->isDependentContext()) {
02782       // Do substitution on the type of the non-type template parameter.
02783       InstantiatingTemplate Inst(*this, TemplateLoc, Template,
02784                                  NTTP, Converted.data(), Converted.size(),
02785                                  SourceRange(TemplateLoc, RAngleLoc));
02786 
02787       TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
02788                                         Converted.data(), Converted.size());
02789       NTTPType = SubstType(NTTPType,
02790                            MultiLevelTemplateArgumentList(TemplateArgs),
02791                            NTTP->getLocation(),
02792                            NTTP->getDeclName());
02793       // If that worked, check the non-type template parameter type
02794       // for validity.
02795       if (!NTTPType.isNull())
02796         NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
02797                                                      NTTP->getLocation());
02798       if (NTTPType.isNull())
02799         return true;
02800     }
02801 
02802     switch (Arg.getArgument().getKind()) {
02803     case TemplateArgument::Null:
02804       llvm_unreachable("Should never see a NULL template argument here");
02805 
02806     case TemplateArgument::Expression: {
02807       TemplateArgument Result;
02808       ExprResult Res =
02809         CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
02810                               Result, CTAK);
02811       if (Res.isInvalid())
02812         return true;
02813 
02814       Converted.push_back(Result);
02815       break;
02816     }
02817 
02818     case TemplateArgument::Declaration:
02819     case TemplateArgument::Integral:
02820       // We've already checked this template argument, so just copy
02821       // it to the list of converted arguments.
02822       Converted.push_back(Arg.getArgument());
02823       break;
02824 
02825     case TemplateArgument::Template:
02826     case TemplateArgument::TemplateExpansion:
02827       // We were given a template template argument. It may not be ill-formed;
02828       // see below.
02829       if (DependentTemplateName *DTN
02830             = Arg.getArgument().getAsTemplateOrTemplatePattern()
02831                                               .getAsDependentTemplateName()) {
02832         // We have a template argument such as \c T::template X, which we
02833         // parsed as a template template argument. However, since we now
02834         // know that we need a non-type template argument, convert this
02835         // template name into an expression.
02836 
02837         DeclarationNameInfo NameInfo(DTN->getIdentifier(),
02838                                      Arg.getTemplateNameLoc());
02839 
02840         CXXScopeSpec SS;
02841         SS.Adopt(Arg.getTemplateQualifierLoc());
02842         // FIXME: the template-template arg was a DependentTemplateName,
02843         // so it was provided with a template keyword. However, its source
02844         // location is not stored in the template argument structure.
02845         SourceLocation TemplateKWLoc;
02846         ExprResult E = Owned(DependentScopeDeclRefExpr::Create(Context,
02847                                                 SS.getWithLocInContext(Context),
02848                                                                TemplateKWLoc,
02849                                                                NameInfo, 0));
02850 
02851         // If we parsed the template argument as a pack expansion, create a
02852         // pack expansion expression.
02853         if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
02854           E = ActOnPackExpansion(E.take(), Arg.getTemplateEllipsisLoc());
02855           if (E.isInvalid())
02856             return true;
02857         }
02858 
02859         TemplateArgument Result;
02860         E = CheckTemplateArgument(NTTP, NTTPType, E.take(), Result);
02861         if (E.isInvalid())
02862           return true;
02863 
02864         Converted.push_back(Result);
02865         break;
02866       }
02867 
02868       // We have a template argument that actually does refer to a class
02869       // template, alias template, or template template parameter, and
02870       // therefore cannot be a non-type template argument.
02871       Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
02872         << Arg.getSourceRange();
02873 
02874       Diag(Param->getLocation(), diag::note_template_param_here);
02875       return true;
02876 
02877     case TemplateArgument::Type: {
02878       // We have a non-type template parameter but the template
02879       // argument is a type.
02880 
02881       // C++ [temp.arg]p2:
02882       //   In a template-argument, an ambiguity between a type-id and
02883       //   an expression is resolved to a type-id, regardless of the
02884       //   form of the corresponding template-parameter.
02885       //
02886       // We warn specifically about this case, since it can be rather
02887       // confusing for users.
02888       QualType T = Arg.getArgument().getAsType();
02889       SourceRange SR = Arg.getSourceRange();
02890       if (T->isFunctionType())
02891         Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
02892       else
02893         Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
02894       Diag(Param->getLocation(), diag::note_template_param_here);
02895       return true;
02896     }
02897 
02898     case TemplateArgument::Pack:
02899       llvm_unreachable("Caller must expand template argument packs");
02900     }
02901 
02902     return false;
02903   }
02904 
02905 
02906   // Check template template parameters.
02907   TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
02908 
02909   // Substitute into the template parameter list of the template
02910   // template parameter, since previously-supplied template arguments
02911   // may appear within the template template parameter.
02912   {
02913     // Set up a template instantiation context.
02914     LocalInstantiationScope Scope(*this);
02915     InstantiatingTemplate Inst(*this, TemplateLoc, Template,
02916                                TempParm, Converted.data(), Converted.size(),
02917                                SourceRange(TemplateLoc, RAngleLoc));
02918 
02919     TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
02920                                       Converted.data(), Converted.size());
02921     TempParm = cast_or_null<TemplateTemplateParmDecl>(
02922                       SubstDecl(TempParm, CurContext,
02923                                 MultiLevelTemplateArgumentList(TemplateArgs)));
02924     if (!TempParm)
02925       return true;
02926   }
02927 
02928   switch (Arg.getArgument().getKind()) {
02929   case TemplateArgument::Null:
02930     llvm_unreachable("Should never see a NULL template argument here");
02931 
02932   case TemplateArgument::Template:
02933   case TemplateArgument::TemplateExpansion:
02934     if (CheckTemplateArgument(TempParm, Arg))
02935       return true;
02936 
02937     Converted.push_back(Arg.getArgument());
02938     break;
02939 
02940   case TemplateArgument::Expression:
02941   case TemplateArgument::Type:
02942     // We have a template template parameter but the template
02943     // argument does not refer to a template.
02944     Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
02945       << getLangOpts().CPlusPlus0x;
02946     return true;
02947 
02948   case TemplateArgument::Declaration:
02949     llvm_unreachable("Declaration argument with template template parameter");
02950   case TemplateArgument::Integral:
02951     llvm_unreachable("Integral argument with template template parameter");
02952 
02953   case TemplateArgument::Pack:
02954     llvm_unreachable("Caller must expand template argument packs");
02955   }
02956 
02957   return false;
02958 }
02959 
02960 /// \brief Diagnose an arity mismatch in the 
02961 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
02962                                   SourceLocation TemplateLoc,
02963                                   TemplateArgumentListInfo &TemplateArgs) {
02964   TemplateParameterList *Params = Template->getTemplateParameters();
02965   unsigned NumParams = Params->size();
02966   unsigned NumArgs = TemplateArgs.size();
02967 
02968   SourceRange Range;
02969   if (NumArgs > NumParams)
02970     Range = SourceRange(TemplateArgs[NumParams].getLocation(), 
02971                         TemplateArgs.getRAngleLoc());
02972   S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
02973     << (NumArgs > NumParams)
02974     << (isa<ClassTemplateDecl>(Template)? 0 :
02975         isa<FunctionTemplateDecl>(Template)? 1 :
02976         isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
02977     << Template << Range;
02978   S.Diag(Template->getLocation(), diag::note_template_decl_here)
02979     << Params->getSourceRange();
02980   return true;
02981 }
02982 
02983 /// \brief Check that the given template argument list is well-formed
02984 /// for specializing the given template.
02985 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
02986                                      SourceLocation TemplateLoc,
02987                                      TemplateArgumentListInfo &TemplateArgs,
02988                                      bool PartialTemplateArgs,
02989                           SmallVectorImpl<TemplateArgument> &Converted,
02990                                      bool *ExpansionIntoFixedList) {
02991   if (ExpansionIntoFixedList)
02992     *ExpansionIntoFixedList = false;
02993 
02994   TemplateParameterList *Params = Template->getTemplateParameters();
02995   unsigned NumParams = Params->size();
02996   unsigned NumArgs = TemplateArgs.size();
02997   bool Invalid = false;
02998 
02999   SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
03000 
03001   bool HasParameterPack =
03002     NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
03003   
03004   // C++ [temp.arg]p1:
03005   //   [...] The type and form of each template-argument specified in
03006   //   a template-id shall match the type and form specified for the
03007   //   corresponding parameter declared by the template in its
03008   //   template-parameter-list.
03009   bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
03010   SmallVector<TemplateArgument, 2> ArgumentPack;
03011   TemplateParameterList::iterator Param = Params->begin(),
03012                                ParamEnd = Params->end();
03013   unsigned ArgIdx = 0;
03014   LocalInstantiationScope InstScope(*this, true);
03015   bool SawPackExpansion = false;
03016   while (Param != ParamEnd) {
03017     if (ArgIdx < NumArgs) {
03018       // If we have an expanded parameter pack, make sure we don't have too
03019       // many arguments.
03020       // FIXME: This really should fall out from the normal arity checking.
03021       if (NonTypeTemplateParmDecl *NTTP
03022                                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
03023         if (NTTP->isExpandedParameterPack() &&
03024             ArgumentPack.size() >= NTTP->getNumExpansionTypes()) {
03025           Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
03026             << true
03027             << (isa<ClassTemplateDecl>(Template)? 0 :
03028                 isa<FunctionTemplateDecl>(Template)? 1 :
03029                 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
03030             << Template;
03031           Diag(Template->getLocation(), diag::note_template_decl_here)
03032             << Params->getSourceRange();
03033           return true;
03034         }
03035       }
03036 
03037       // Check the template argument we were given.
03038       if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
03039                                 TemplateLoc, RAngleLoc,
03040                                 ArgumentPack.size(), Converted))
03041         return true;
03042 
03043       if ((*Param)->isTemplateParameterPack()) {
03044         // The template parameter was a template parameter pack, so take the
03045         // deduced argument and place it on the argument pack. Note that we
03046         // stay on the same template parameter so that we can deduce more
03047         // arguments.
03048         ArgumentPack.push_back(Converted.back());
03049         Converted.pop_back();
03050       } else {
03051         // Move to the next template parameter.
03052         ++Param;
03053       }
03054       
03055       // If this template argument is a pack expansion, record that fact
03056       // and break out; we can't actually check any more.
03057       if (TemplateArgs[ArgIdx].getArgument().isPackExpansion()) {
03058         SawPackExpansion = true;
03059         ++ArgIdx;
03060         break;
03061       }
03062       
03063       ++ArgIdx;
03064       continue;
03065     }
03066 
03067     // If we're checking a partial template argument list, we're done.
03068     if (PartialTemplateArgs) {
03069       if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
03070         Converted.push_back(TemplateArgument::CreatePackCopy(Context,
03071                                                          ArgumentPack.data(),
03072                                                          ArgumentPack.size()));
03073         
03074       return Invalid;
03075     }
03076 
03077     // If we have a template parameter pack with no more corresponding
03078     // arguments, just break out now and we'll fill in the argument pack below.
03079     if ((*Param)->isTemplateParameterPack())
03080       break;
03081     
03082     // Check whether we have a default argument.
03083     TemplateArgumentLoc Arg;
03084 
03085     // Retrieve the default template argument from the template
03086     // parameter. For each kind of template parameter, we substitute the
03087     // template arguments provided thus far and any "outer" template arguments
03088     // (when the template parameter was part of a nested template) into
03089     // the default argument.
03090     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
03091       if (!TTP->hasDefaultArgument())
03092         return diagnoseArityMismatch(*this, Template, TemplateLoc, 
03093                                      TemplateArgs);
03094 
03095       TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
03096                                                              Template,
03097                                                              TemplateLoc,
03098                                                              RAngleLoc,
03099                                                              TTP,
03100                                                              Converted);
03101       if (!ArgType)
03102         return true;
03103 
03104       Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
03105                                 ArgType);
03106     } else if (NonTypeTemplateParmDecl *NTTP
03107                  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
03108       if (!NTTP->hasDefaultArgument())
03109         return diagnoseArityMismatch(*this, Template, TemplateLoc, 
03110                                      TemplateArgs);
03111 
03112       ExprResult E = SubstDefaultTemplateArgument(*this, Template,
03113                                                               TemplateLoc,
03114                                                               RAngleLoc,
03115                                                               NTTP,
03116                                                               Converted);
03117       if (E.isInvalid())
03118         return true;
03119 
03120       Expr *Ex = E.takeAs<Expr>();
03121       Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
03122     } else {
03123       TemplateTemplateParmDecl *TempParm
03124         = cast<TemplateTemplateParmDecl>(*Param);
03125 
03126       if (!TempParm->hasDefaultArgument())
03127         return diagnoseArityMismatch(*this, Template, TemplateLoc, 
03128                                      TemplateArgs);
03129 
03130       NestedNameSpecifierLoc QualifierLoc;
03131       TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
03132                                                        TemplateLoc,
03133                                                        RAngleLoc,
03134                                                        TempParm,
03135                                                        Converted,
03136                                                        QualifierLoc);
03137       if (Name.isNull())
03138         return true;
03139 
03140       Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
03141                            TempParm->getDefaultArgument().getTemplateNameLoc());
03142     }
03143 
03144     // Introduce an instantiation record that describes where we are using
03145     // the default template argument.
03146     InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
03147                                         Converted.data(), Converted.size(),
03148                                         SourceRange(TemplateLoc, RAngleLoc));
03149 
03150     // Check the default template argument.
03151     if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
03152                               RAngleLoc, 0, Converted))
03153       return true;
03154 
03155     // Core issue 150 (assumed resolution): if this is a template template 
03156     // parameter, keep track of the default template arguments from the 
03157     // template definition.
03158     if (isTemplateTemplateParameter)
03159       TemplateArgs.addArgument(Arg);
03160     
03161     // Move to the next template parameter and argument.
03162     ++Param;
03163     ++ArgIdx;
03164   }
03165 
03166   // If we saw a pack expansion, then directly convert the remaining arguments,
03167   // because we don't know what parameters they'll match up with.
03168   if (SawPackExpansion) {
03169     bool AddToArgumentPack
03170       = Param != ParamEnd && (*Param)->isTemplateParameterPack();
03171     while (ArgIdx < NumArgs) {
03172       if (AddToArgumentPack)
03173         ArgumentPack.push_back(TemplateArgs[ArgIdx].getArgument());
03174       else
03175         Converted.push_back(TemplateArgs[ArgIdx].getArgument());
03176       ++ArgIdx;
03177     }
03178 
03179     // Push the argument pack onto the list of converted arguments.
03180     if (AddToArgumentPack) {
03181       if (ArgumentPack.empty())
03182         Converted.push_back(TemplateArgument(0, 0));
03183       else {
03184         Converted.push_back(
03185           TemplateArgument::CreatePackCopy(Context,
03186                                            ArgumentPack.data(),
03187                                            ArgumentPack.size()));
03188         ArgumentPack.clear();
03189       }      
03190     } else if (ExpansionIntoFixedList) {
03191       // We have expanded a pack into a fixed list.
03192       *ExpansionIntoFixedList = true;
03193     }
03194 
03195     return Invalid;
03196   }
03197 
03198   // If we have any leftover arguments, then there were too many arguments.
03199   // Complain and fail.
03200   if (ArgIdx < NumArgs)
03201     return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
03202   
03203   // If we have an expanded parameter pack, make sure we don't have too
03204   // many arguments.
03205   // FIXME: This really should fall out from the normal arity checking.
03206   if (Param != ParamEnd) {
03207     if (NonTypeTemplateParmDecl *NTTP
03208           = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
03209       if (NTTP->isExpandedParameterPack() &&
03210           ArgumentPack.size() < NTTP->getNumExpansionTypes()) {
03211         Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
03212           << false
03213           << (isa<ClassTemplateDecl>(Template)? 0 :
03214               isa<FunctionTemplateDecl>(Template)? 1 :
03215               isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
03216           << Template;
03217         Diag(Template->getLocation(), diag::note_template_decl_here)
03218           << Params->getSourceRange();
03219         return true;
03220       }
03221     }
03222   }
03223   
03224   // Form argument packs for each of the parameter packs remaining.
03225   while (Param != ParamEnd) {
03226     // If we're checking a partial list of template arguments, don't fill
03227     // in arguments for non-template parameter packs.
03228     if ((*Param)->isTemplateParameterPack()) {
03229       if (!HasParameterPack)
03230         return true;
03231       if (ArgumentPack.empty())
03232         Converted.push_back(TemplateArgument(0, 0));
03233       else {
03234         Converted.push_back(TemplateArgument::CreatePackCopy(Context,
03235                                                           ArgumentPack.data(),
03236                                                          ArgumentPack.size()));
03237         ArgumentPack.clear();
03238       }
03239     } else if (!PartialTemplateArgs)
03240       return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
03241 
03242     ++Param;
03243   }
03244 
03245   return Invalid;
03246 }
03247 
03248 namespace {
03249   class UnnamedLocalNoLinkageFinder
03250     : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
03251   {
03252     Sema &S;
03253     SourceRange SR;
03254 
03255     typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
03256 
03257   public:
03258     UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
03259 
03260     bool Visit(QualType T) {
03261       return inherited::Visit(T.getTypePtr());
03262     }
03263 
03264 #define TYPE(Class, Parent) \
03265     bool Visit##Class##Type(const Class##Type *);
03266 #define ABSTRACT_TYPE(Class, Parent) \
03267     bool Visit##Class##Type(const Class##Type *) { return false; }
03268 #define NON_CANONICAL_TYPE(Class, Parent) \
03269     bool Visit##Class##Type(const Class##Type *) { return false; }
03270 #include "clang/AST/TypeNodes.def"
03271 
03272     bool VisitTagDecl(const TagDecl *Tag);
03273     bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
03274   };
03275 }
03276 
03277 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
03278   return false;
03279 }
03280 
03281 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
03282   return Visit(T->getElementType());
03283 }
03284 
03285 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
03286   return Visit(T->getPointeeType());
03287 }
03288 
03289 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
03290                                                     const BlockPointerType* T) {
03291   return Visit(T->getPointeeType());
03292 }
03293 
03294 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
03295                                                 const LValueReferenceType* T) {
03296   return Visit(T->getPointeeType());
03297 }
03298 
03299 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
03300                                                 const RValueReferenceType* T) {
03301   return Visit(T->getPointeeType());
03302 }
03303 
03304 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
03305                                                   const MemberPointerType* T) {
03306   return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
03307 }
03308 
03309 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
03310                                                   const ConstantArrayType* T) {
03311   return Visit(T->getElementType());
03312 }
03313 
03314 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
03315                                                  const IncompleteArrayType* T) {
03316   return Visit(T->getElementType());
03317 }
03318 
03319 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
03320                                                    const VariableArrayType* T) {
03321   return Visit(T->getElementType());
03322 }
03323 
03324 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
03325                                             const DependentSizedArrayType* T) {
03326   return Visit(T->getElementType());
03327 }
03328 
03329 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
03330                                          const DependentSizedExtVectorType* T) {
03331   return Visit(T->getElementType());
03332 }
03333 
03334 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
03335   return Visit(T->getElementType());
03336 }
03337 
03338 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
03339   return Visit(T->getElementType());
03340 }
03341 
03342 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
03343                                                   const FunctionProtoType* T) {
03344   for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
03345                                          AEnd = T->arg_type_end();
03346        A != AEnd; ++A) {
03347     if (Visit(*A))
03348       return true;
03349   }
03350 
03351   return Visit(T->getResultType());
03352 }
03353 
03354 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
03355                                                const FunctionNoProtoType* T) {
03356   return Visit(T->getResultType());
03357 }
03358 
03359 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
03360                                                   const UnresolvedUsingType*) {
03361   return false;
03362 }
03363 
03364 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
03365   return false;
03366 }
03367 
03368 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
03369   return Visit(T->getUnderlyingType());
03370 }
03371 
03372 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
03373   return false;
03374 }
03375 
03376 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
03377                                                     const UnaryTransformType*) {
03378   return false;
03379 }
03380 
03381 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
03382   return Visit(T->getDeducedType());
03383 }
03384 
03385 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
03386   return VisitTagDecl(T->getDecl());
03387 }
03388 
03389 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
03390   return VisitTagDecl(T->getDecl());
03391 }
03392 
03393 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
03394                                                  const TemplateTypeParmType*) {
03395   return false;
03396 }
03397 
03398 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
03399                                         const SubstTemplateTypeParmPackType *) {
03400   return false;
03401 }
03402 
03403 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
03404                                             const TemplateSpecializationType*) {
03405   return false;
03406 }
03407 
03408 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
03409                                               const InjectedClassNameType* T) {
03410   return VisitTagDecl(T->getDecl());
03411 }
03412 
03413 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
03414                                                    const DependentNameType* T) {
03415   return VisitNestedNameSpecifier(T->getQualifier());
03416 }
03417 
03418 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
03419                                  const DependentTemplateSpecializationType* T) {
03420   return VisitNestedNameSpecifier(T->getQualifier());
03421 }
03422 
03423 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
03424                                                    const PackExpansionType* T) {
03425   return Visit(T->getPattern());
03426 }
03427 
03428 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
03429   return false;
03430 }
03431 
03432 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
03433                                                    const ObjCInterfaceType *) {
03434   return false;
03435 }
03436 
03437 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
03438                                                 const ObjCObjectPointerType *) {
03439   return false;
03440 }
03441 
03442 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
03443   return Visit(T->getValueType());
03444 }
03445 
03446 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
03447   if (Tag->getDeclContext()->isFunctionOrMethod()) {
03448     S.Diag(SR.getBegin(),
03449            S.getLangOpts().CPlusPlus0x ?
03450              diag::warn_cxx98_compat_template_arg_local_type :
03451              diag::ext_template_arg_local_type)
03452       << S.Context.getTypeDeclType(Tag) << SR;
03453     return true;
03454   }
03455 
03456   if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl()) {
03457     S.Diag(SR.getBegin(),
03458            S.getLangOpts().CPlusPlus0x ?
03459              diag::warn_cxx98_compat_template_arg_unnamed_type :
03460              diag::ext_template_arg_unnamed_type) << SR;
03461     S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
03462     return true;
03463   }
03464 
03465   return false;
03466 }
03467 
03468 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
03469                                                     NestedNameSpecifier *NNS) {
03470   if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
03471     return true;
03472 
03473   switch (NNS->getKind()) {
03474   case NestedNameSpecifier::Identifier:
03475   case NestedNameSpecifier::Namespace:
03476   case NestedNameSpecifier::NamespaceAlias:
03477   case NestedNameSpecifier::Global:
03478     return false;
03479 
03480   case NestedNameSpecifier::TypeSpec:
03481   case NestedNameSpecifier::TypeSpecWithTemplate:
03482     return Visit(QualType(NNS->getAsType(), 0));
03483   }
03484   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
03485 }
03486 
03487 
03488 /// \brief Check a template argument against its corresponding
03489 /// template type parameter.
03490 ///
03491 /// This routine implements the semantics of C++ [temp.arg.type]. It
03492 /// returns true if an error occurred, and false otherwise.
03493 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
03494                                  TypeSourceInfo *ArgInfo) {
03495   assert(ArgInfo && "invalid TypeSourceInfo");
03496   QualType Arg = ArgInfo->getType();
03497   SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
03498 
03499   if (Arg->isVariablyModifiedType()) {
03500     return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
03501   } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
03502     return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
03503   }
03504 
03505   // C++03 [temp.arg.type]p2:
03506   //   A local type, a type with no linkage, an unnamed type or a type
03507   //   compounded from any of these types shall not be used as a
03508   //   template-argument for a template type-parameter.
03509   //
03510   // C++11 allows these, and even in C++03 we allow them as an extension with
03511   // a warning.
03512   if (LangOpts.CPlusPlus0x ?
03513      Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_unnamed_type,
03514                               SR.getBegin()) != DiagnosticsEngine::Ignored ||
03515       Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_local_type,
03516                                SR.getBegin()) != DiagnosticsEngine::Ignored :
03517       Arg->hasUnnamedOrLocalType()) {
03518     UnnamedLocalNoLinkageFinder Finder(*this, SR);
03519     (void)Finder.Visit(Context.getCanonicalType(Arg));
03520   }
03521 
03522   return false;
03523 }
03524 
03525 enum NullPointerValueKind {
03526   NPV_NotNullPointer,
03527   NPV_NullPointer,
03528   NPV_Error
03529 };
03530 
03531 /// \brief Determine whether the given template argument is a null pointer
03532 /// value of the appropriate type.
03533 static NullPointerValueKind
03534 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
03535                                    QualType ParamType, Expr *Arg) {
03536   if (Arg->isValueDependent() || Arg->isTypeDependent())
03537     return NPV_NotNullPointer;
03538   
03539   if (!S.getLangOpts().CPlusPlus0x)
03540     return NPV_NotNullPointer;
03541   
03542   // Determine whether we have a constant expression.
03543   ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
03544   if (ArgRV.isInvalid())
03545     return NPV_Error;
03546   Arg = ArgRV.take();
03547   
03548   Expr::EvalResult EvalResult;
03549   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
03550   EvalResult.Diag = &Notes;
03551   if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
03552       EvalResult.HasSideEffects) {
03553     SourceLocation DiagLoc = Arg->getExprLoc();
03554     
03555     // If our only note is the usual "invalid subexpression" note, just point
03556     // the caret at its location rather than producing an essentially
03557     // redundant note.
03558     if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
03559         diag::note_invalid_subexpr_in_const_expr) {
03560       DiagLoc = Notes[0].first;
03561       Notes.clear();
03562     }
03563     
03564     S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
03565       << Arg->getType() << Arg->getSourceRange();
03566     for (unsigned I = 0, N = Notes.size(); I != N; ++I)
03567       S.Diag(Notes[I].first, Notes[I].second);
03568     
03569     S.Diag(Param->getLocation(), diag::note_template_param_here);
03570     return NPV_Error;
03571   }
03572   
03573   // C++11 [temp.arg.nontype]p1:
03574   //   - an address constant expression of type std::nullptr_t
03575   if (Arg->getType()->isNullPtrType())
03576     return NPV_NullPointer;
03577   
03578   //   - a constant expression that evaluates to a null pointer value (4.10); or
03579   //   - a constant expression that evaluates to a null member pointer value
03580   //     (4.11); or
03581   if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
03582       (EvalResult.Val.isMemberPointer() &&
03583        !EvalResult.Val.getMemberPointerDecl())) {
03584     // If our expression has an appropriate type, we've succeeded.
03585     bool ObjCLifetimeConversion;
03586     if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
03587         S.IsQualificationConversion(Arg->getType(), ParamType, false,
03588                                      ObjCLifetimeConversion))
03589       return NPV_NullPointer;
03590     
03591     // The types didn't match, but we know we got a null pointer; complain,
03592     // then recover as if the types were correct.
03593     S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
03594       << Arg->getType() << ParamType << Arg->getSourceRange();
03595     S.Diag(Param->getLocation(), diag::note_template_param_here);
03596     return NPV_NullPointer;
03597   }
03598 
03599   // If we don't have a null pointer value, but we do have a NULL pointer
03600   // constant, suggest a cast to the appropriate type.
03601   if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
03602     std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
03603     S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
03604       << ParamType
03605       << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
03606       << FixItHint::CreateInsertion(S.PP.getLocForEndOfToken(Arg->getLocEnd()),
03607                                     ")");
03608     S.Diag(Param->getLocation(), diag::note_template_param_here);
03609     return NPV_NullPointer;
03610   }
03611   
03612   // FIXME: If we ever want to support general, address-constant expressions
03613   // as non-type template arguments, we should return the ExprResult here to
03614   // be interpreted by the caller.
03615   return NPV_NotNullPointer;
03616 }
03617 
03618 /// \brief Checks whether the given template argument is the address
03619 /// of an object or function according to C++ [temp.arg.nontype]p1.
03620 static bool
03621 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
03622                                                NonTypeTemplateParmDecl *Param,
03623                                                QualType ParamType,
03624                                                Expr *ArgIn,
03625                                                TemplateArgument &Converted) {
03626   bool Invalid = false;
03627   Expr *Arg = ArgIn;
03628   QualType ArgType = Arg->getType();
03629 
03630   // If our parameter has pointer type, check for a null template value.
03631   if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
03632     switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
03633     case NPV_NullPointer:
03634       S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
03635       Converted = TemplateArgument((Decl *)0);
03636       return false;
03637 
03638     case NPV_Error:
03639       return true;
03640         
03641     case NPV_NotNullPointer:
03642       break;
03643     }
03644   }
03645   
03646   // See through any implicit casts we added to fix the type.
03647   Arg = Arg->IgnoreImpCasts();
03648 
03649   // C++ [temp.arg.nontype]p1:
03650   //
03651   //   A template-argument for a non-type, non-template
03652   //   template-parameter shall be one of: [...]
03653   //
03654   //     -- the address of an object or function with external
03655   //        linkage, including function templates and function
03656   //        template-ids but excluding non-static class members,
03657   //        expressed as & id-expression where the & is optional if
03658   //        the name refers to a function or array, or if the
03659   //        corresponding template-parameter is a reference; or
03660 
03661   // In C++98/03 mode, give an extension warning on any extra parentheses.
03662   // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
03663   bool ExtraParens = false;
03664   while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
03665     if (!Invalid && !ExtraParens) {
03666       S.Diag(Arg->getLocStart(),
03667              S.getLangOpts().CPlusPlus0x ?
03668                diag::warn_cxx98_compat_template_arg_extra_parens :
03669                diag::ext_template_arg_extra_parens)
03670         << Arg->getSourceRange();
03671       ExtraParens = true;
03672     }
03673 
03674     Arg = Parens->getSubExpr();
03675   }
03676 
03677   while (SubstNonTypeTemplateParmExpr *subst =
03678            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
03679     Arg = subst->getReplacement()->IgnoreImpCasts();
03680 
03681   bool AddressTaken = false;
03682   SourceLocation AddrOpLoc;
03683   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
03684     if (UnOp->getOpcode() == UO_AddrOf) {
03685       Arg = UnOp->getSubExpr();
03686       AddressTaken = true;
03687       AddrOpLoc = UnOp->getOperatorLoc();
03688     }
03689   }
03690 
03691   if (S.getLangOpts().MicrosoftExt && isa<CXXUuidofExpr>(Arg)) {
03692     Converted = TemplateArgument(ArgIn);
03693     return false;
03694   }
03695 
03696   while (SubstNonTypeTemplateParmExpr *subst =
03697            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
03698     Arg = subst->getReplacement()->IgnoreImpCasts();
03699 
03700   // Stop checking the precise nature of the argument if it is value dependent,
03701   // it should be checked when instantiated.
03702   if (Arg->isValueDependent()) {
03703     Converted = TemplateArgument(ArgIn);
03704     return false;
03705   }
03706   
03707   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
03708   if (!DRE) {
03709     S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
03710     << Arg->getSourceRange();
03711     S.Diag(Param->getLocation(), diag::note_template_param_here);
03712     return true;
03713   }
03714 
03715   if (!isa<ValueDecl>(DRE->getDecl())) {
03716     S.Diag(Arg->getLocStart(),
03717            diag::err_template_arg_not_object_or_func_form)
03718       << Arg->getSourceRange();
03719     S.Diag(Param->getLocation(), diag::note_template_param_here);
03720     return true;
03721   }
03722 
03723   NamedDecl *Entity = DRE->getDecl();
03724 
03725   // Cannot refer to non-static data members
03726   if (FieldDecl *Field = dyn_cast<FieldDecl>(Entity)) {
03727     S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
03728       << Field << Arg->getSourceRange();
03729     S.Diag(Param->getLocation(), diag::note_template_param_here);
03730     return true;
03731   }
03732 
03733   // Cannot refer to non-static member functions
03734   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
03735     if (!Method->isStatic()) {
03736       S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
03737         << Method << Arg->getSourceRange();
03738       S.Diag(Param->getLocation(), diag::note_template_param_here);
03739       return true;
03740     }
03741   }
03742 
03743   FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
03744   VarDecl *Var = dyn_cast<VarDecl>(Entity);
03745 
03746   // A non-type template argument must refer to an object or function.
03747   if (!Func && !Var) {
03748     // We found something, but we don't know specifically what it is.
03749     S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
03750       << Arg->getSourceRange();
03751     S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
03752     return true;
03753   }
03754 
03755   // Address / reference template args must have external linkage in C++98.
03756   if (Entity->getLinkage() == InternalLinkage) {
03757     S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus0x ?
03758              diag::warn_cxx98_compat_template_arg_object_internal :
03759              diag::ext_template_arg_object_internal)
03760       << !Func << Entity << Arg->getSourceRange();
03761     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
03762       << !Func;
03763   } else if (Entity->getLinkage() == NoLinkage) {
03764     S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
03765       << !Func << Entity << Arg->getSourceRange();
03766     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
03767       << !Func;
03768     return true;
03769   }
03770 
03771   if (Func) {
03772     // If the template parameter has pointer type, the function decays.
03773     if (ParamType->isPointerType() && !AddressTaken)
03774       ArgType = S.Context.getPointerType(Func->getType());
03775     else if (AddressTaken && ParamType->isReferenceType()) {
03776       // If we originally had an address-of operator, but the
03777       // parameter has reference type, complain and (if things look
03778       // like they will work) drop the address-of operator.
03779       if (!S.Context.hasSameUnqualifiedType(Func->getType(),
03780                                             ParamType.getNonReferenceType())) {
03781         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
03782           << ParamType;
03783         S.Diag(Param->getLocation(), diag::note_template_param_here);
03784         return true;
03785       }
03786 
03787       S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
03788         << ParamType
03789         << FixItHint::CreateRemoval(AddrOpLoc);
03790       S.Diag(Param->getLocation(), diag::note_template_param_here);
03791 
03792       ArgType = Func->getType();
03793     }
03794   } else {
03795     // A value of reference type is not an object.
03796     if (Var->getType()->isReferenceType()) {
03797       S.Diag(Arg->getLocStart(),
03798              diag::err_template_arg_reference_var)
03799         << Var->getType() << Arg->getSourceRange();
03800       S.Diag(Param->getLocation(), diag::note_template_param_here);
03801       return true;
03802     }
03803 
03804     // A template argument must have static storage duration.
03805     // FIXME: Ensure this works for thread_local as well as __thread.
03806     if (Var->isThreadSpecified()) {
03807       S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
03808         << Arg->getSourceRange();
03809       S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
03810       return true;
03811     }
03812 
03813     // If the template parameter has pointer type, we must have taken
03814     // the address of this object.
03815     if (ParamType->isReferenceType()) {
03816       if (AddressTaken) {
03817         // If we originally had an address-of operator, but the
03818         // parameter has reference type, complain and (if things look
03819         // like they will work) drop the address-of operator.
03820         if (!S.Context.hasSameUnqualifiedType(Var->getType(),
03821                                             ParamType.getNonReferenceType())) {
03822           S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
03823             << ParamType;
03824           S.Diag(Param->getLocation(), diag::note_template_param_here);
03825           return true;
03826         }
03827 
03828         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
03829           << ParamType
03830           << FixItHint::CreateRemoval(AddrOpLoc);
03831         S.Diag(Param->getLocation(), diag::note_template_param_here);
03832 
03833         ArgType = Var->getType();
03834       }
03835     } else if (!AddressTaken && ParamType->isPointerType()) {
03836       if (Var->getType()->isArrayType()) {
03837         // Array-to-pointer decay.
03838         ArgType = S.Context.getArrayDecayedType(Var->getType());
03839       } else {
03840         // If the template parameter has pointer type but the address of
03841         // this object was not taken, complain and (possibly) recover by
03842         // taking the address of the entity.
03843         ArgType = S.Context.getPointerType(Var->getType());
03844         if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
03845           S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
03846             << ParamType;
03847           S.Diag(Param->getLocation(), diag::note_template_param_here);
03848           return true;
03849         }
03850 
03851         S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
03852           << ParamType
03853           << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
03854 
03855         S.Diag(Param->getLocation(), diag::note_template_param_here);
03856       }
03857     }
03858   }
03859 
03860   bool ObjCLifetimeConversion;
03861   if (ParamType->isPointerType() &&
03862       !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
03863       S.IsQualificationConversion(ArgType, ParamType, false, 
03864                                   ObjCLifetimeConversion)) {
03865     // For pointer-to-object types, qualification conversions are
03866     // permitted.
03867   } else {
03868     if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
03869       if (!ParamRef->getPointeeType()->isFunctionType()) {
03870         // C++ [temp.arg.nontype]p5b3:
03871         //   For a non-type template-parameter of type reference to
03872         //   object, no conversions apply. The type referred to by the
03873         //   reference may be more cv-qualified than the (otherwise
03874         //   identical) type of the template- argument. The
03875         //   template-parameter is bound directly to the
03876         //   template-argument, which shall be an lvalue.
03877 
03878         // FIXME: Other qualifiers?
03879         unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
03880         unsigned ArgQuals = ArgType.getCVRQualifiers();
03881 
03882         if ((ParamQuals | ArgQuals) != ParamQuals) {
03883           S.Diag(Arg->getLocStart(),
03884                  diag::err_template_arg_ref_bind_ignores_quals)
03885             << ParamType << Arg->getType()
03886             << Arg->getSourceRange();
03887           S.Diag(Param->getLocation(), diag::note_template_param_here);
03888           return true;
03889         }
03890       }
03891     }
03892 
03893     // At this point, the template argument refers to an object or
03894     // function with external linkage. We now need to check whether the
03895     // argument and parameter types are compatible.
03896     if (!S.Context.hasSameUnqualifiedType(ArgType,
03897                                           ParamType.getNonReferenceType())) {
03898       // We can't perform this conversion or binding.
03899       if (ParamType->isReferenceType())
03900         S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
03901           << ParamType << ArgIn->getType() << Arg->getSourceRange();
03902       else
03903         S.Diag(Arg->getLocStart(),  diag::err_template_arg_not_convertible)
03904           << ArgIn->getType() << ParamType << Arg->getSourceRange();
03905       S.Diag(Param->getLocation(), diag::note_template_param_here);
03906       return true;
03907     }
03908   }
03909 
03910   // Create the template argument.
03911   Converted = TemplateArgument(Entity->getCanonicalDecl());
03912   S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity);
03913   return false;
03914 }
03915 
03916 /// \brief Checks whether the given template argument is a pointer to
03917 /// member constant according to C++ [temp.arg.nontype]p1.
03918 static bool CheckTemplateArgumentPointerToMember(Sema &S,
03919                                                  NonTypeTemplateParmDecl *Param,
03920                                                  QualType ParamType,
03921                                                  Expr *&ResultArg,
03922                                                  TemplateArgument &Converted) {
03923   bool Invalid = false;
03924 
03925   // Check for a null pointer value.
03926   Expr *Arg = ResultArg;
03927   switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
03928   case NPV_Error:
03929     return true;
03930   case NPV_NullPointer:
03931     S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
03932     Converted = TemplateArgument((Decl *)0);
03933     return false;
03934   case NPV_NotNullPointer:
03935     break;
03936   }
03937 
03938   bool ObjCLifetimeConversion;
03939   if (S.IsQualificationConversion(Arg->getType(),
03940                                   ParamType.getNonReferenceType(),
03941                                   false, ObjCLifetimeConversion)) {
03942     Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
03943                               Arg->getValueKind()).take();
03944     ResultArg = Arg;
03945   } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
03946                 ParamType.getNonReferenceType())) {
03947     // We can't perform this conversion.
03948     S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
03949       << Arg->getType() << ParamType << Arg->getSourceRange();
03950     S.Diag(Param->getLocation(), diag::note_template_param_here);
03951     return true;
03952   }
03953 
03954   // See through any implicit casts we added to fix the type.
03955   while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
03956     Arg = Cast->getSubExpr();
03957 
03958   // C++ [temp.arg.nontype]p1:
03959   //
03960   //   A template-argument for a non-type, non-template
03961   //   template-parameter shall be one of: [...]
03962   //
03963   //     -- a pointer to member expressed as described in 5.3.1.
03964   DeclRefExpr *DRE = 0;
03965 
03966   // In C++98/03 mode, give an extension warning on any extra parentheses.
03967   // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
03968   bool ExtraParens = false;
03969   while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
03970     if (!Invalid && !ExtraParens) {
03971       S.Diag(Arg->getLocStart(),
03972              S.getLangOpts().CPlusPlus0x ?
03973                diag::warn_cxx98_compat_template_arg_extra_parens :
03974                diag::ext_template_arg_extra_parens)
03975         << Arg->getSourceRange();
03976       ExtraParens = true;
03977     }
03978 
03979     Arg = Parens->getSubExpr();
03980   }
03981 
03982   while (SubstNonTypeTemplateParmExpr *subst =
03983            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
03984     Arg = subst->getReplacement()->IgnoreImpCasts();
03985 
03986   // A pointer-to-member constant written &Class::member.
03987   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
03988     if (UnOp->getOpcode() == UO_AddrOf) {
03989       DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
03990       if (DRE && !DRE->getQualifier())
03991         DRE = 0;
03992     }
03993   }
03994   // A constant of pointer-to-member type.
03995   else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
03996     if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
03997       if (VD->getType()->isMemberPointerType()) {
03998         if (isa<NonTypeTemplateParmDecl>(VD) ||
03999             (isa<VarDecl>(VD) &&
04000              S.Context.getCanonicalType(VD->getType()).isConstQualified())) {
04001           if (Arg->isTypeDependent() || Arg->isValueDependent())
04002             Converted = TemplateArgument(Arg);
04003           else
04004             Converted = TemplateArgument(VD->getCanonicalDecl());
04005           return Invalid;
04006         }
04007       }
04008     }
04009 
04010     DRE = 0;
04011   }
04012 
04013   if (!DRE)
04014     return S.Diag(Arg->getLocStart(),
04015                   diag::err_template_arg_not_pointer_to_member_form)
04016       << Arg->getSourceRange();
04017 
04018   if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
04019     assert((isa<FieldDecl>(DRE->getDecl()) ||
04020             !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
04021            "Only non-static member pointers can make it here");
04022 
04023     // Okay: this is the address of a non-static member, and therefore
04024     // a member pointer constant.
04025     if (Arg->isTypeDependent() || Arg->isValueDependent())
04026       Converted = TemplateArgument(Arg);
04027     else
04028       Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
04029     return Invalid;
04030   }
04031 
04032   // We found something else, but we don't know specifically what it is.
04033   S.Diag(Arg->getLocStart(),
04034          diag::err_template_arg_not_pointer_to_member_form)
04035     << Arg->getSourceRange();
04036   S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
04037   return true;
04038 }
04039 
04040 /// \brief Check a template argument against its corresponding
04041 /// non-type template parameter.
04042 ///
04043 /// This routine implements the semantics of C++ [temp.arg.nontype].
04044 /// If an error occurred, it returns ExprError(); otherwise, it
04045 /// returns the converted template argument. \p
04046 /// InstantiatedParamType is the type of the non-type template
04047 /// parameter after it has been instantiated.
04048 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
04049                                        QualType InstantiatedParamType, Expr *Arg,
04050                                        TemplateArgument &Converted,
04051                                        CheckTemplateArgumentKind CTAK) {
04052   SourceLocation StartLoc = Arg->getLocStart();
04053 
04054   // If either the parameter has a dependent type or the argument is
04055   // type-dependent, there's nothing we can check now.
04056   if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
04057     // FIXME: Produce a cloned, canonical expression?
04058     Converted = TemplateArgument(Arg);
04059     return Owned(Arg);
04060   }
04061 
04062   // C++ [temp.arg.nontype]p5:
04063   //   The following conversions are performed on each expression used
04064   //   as a non-type template-argument. If a non-type
04065   //   template-argument cannot be converted to the type of the
04066   //   corresponding template-parameter then the program is
04067   //   ill-formed.
04068   QualType ParamType = InstantiatedParamType;
04069   if (ParamType->isIntegralOrEnumerationType()) {
04070     // C++11:
04071     //   -- for a non-type template-parameter of integral or
04072     //      enumeration type, conversions permitted in a converted
04073     //      constant expression are applied.
04074     //
04075     // C++98:
04076     //   -- for a non-type template-parameter of integral or
04077     //      enumeration type, integral promotions (4.5) and integral
04078     //      conversions (4.7) are applied.
04079 
04080     if (CTAK == CTAK_Deduced &&
04081         !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
04082       // C++ [temp.deduct.type]p17:
04083       //   If, in the declaration of a function template with a non-type
04084       //   template-parameter, the non-type template-parameter is used
04085       //   in an expression in the function parameter-list and, if the
04086       //   corresponding template-argument is deduced, the
04087       //   template-argument type shall match the type of the
04088       //   template-parameter exactly, except that a template-argument
04089       //   deduced from an array bound may be of any integral type.
04090       Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
04091         << Arg->getType().getUnqualifiedType()
04092         << ParamType.getUnqualifiedType();
04093       Diag(Param->getLocation(), diag::note_template_param_here);
04094       return ExprError();
04095     }
04096 
04097     if (getLangOpts().CPlusPlus0x) {
04098       // We can't check arbitrary value-dependent arguments.
04099       // FIXME: If there's no viable conversion to the template parameter type,
04100       // we should be able to diagnose that prior to instantiation.
04101       if (Arg->isValueDependent()) {
04102         Converted = TemplateArgument(Arg);
04103         return Owned(Arg);
04104       }
04105 
04106       // C++ [temp.arg.nontype]p1:
04107       //   A template-argument for a non-type, non-template template-parameter
04108       //   shall be one of:
04109       //
04110       //     -- for a non-type template-parameter of integral or enumeration
04111       //        type, a converted constant expression of the type of the
04112       //        template-parameter; or
04113       llvm::APSInt Value;
04114       ExprResult ArgResult =
04115         CheckConvertedConstantExpression(Arg, ParamType, Value,
04116                                          CCEK_TemplateArg);
04117       if (ArgResult.isInvalid())
04118         return ExprError();
04119 
04120       // Widen the argument value to sizeof(parameter type). This is almost
04121       // always a no-op, except when the parameter type is bool. In
04122       // that case, this may extend the argument from 1 bit to 8 bits.
04123       QualType IntegerType = ParamType;
04124       if (const EnumType *Enum = IntegerType->getAs<EnumType>())
04125         IntegerType = Enum->getDecl()->getIntegerType();
04126       Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
04127 
04128       Converted = TemplateArgument(Value, Context.getCanonicalType(ParamType));
04129       return ArgResult;
04130     }
04131 
04132     ExprResult ArgResult = DefaultLvalueConversion(Arg);
04133     if (ArgResult.isInvalid())
04134       return ExprError();
04135     Arg = ArgResult.take();
04136 
04137     QualType ArgType = Arg->getType();
04138 
04139     // C++ [temp.arg.nontype]p1:
04140     //   A template-argument for a non-type, non-template
04141     //   template-parameter shall be one of:
04142     //
04143     //     -- an integral constant-expression of integral or enumeration
04144     //        type; or
04145     //     -- the name of a non-type template-parameter; or
04146     SourceLocation NonConstantLoc;
04147     llvm::APSInt Value;
04148     if (!ArgType->isIntegralOrEnumerationType()) {
04149       Diag(Arg->getLocStart(),
04150            diag::err_template_arg_not_integral_or_enumeral)
04151         << ArgType << Arg->getSourceRange();
04152       Diag(Param->getLocation(), diag::note_template_param_here);
04153       return ExprError();
04154     } else if (!Arg->isValueDependent()) {
04155       class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
04156         QualType T;
04157         
04158       public:
04159         TmplArgICEDiagnoser(QualType T) : T(T) { }
04160         
04161         virtual void diagnoseNotICE(Sema &S, SourceLocation Loc,
04162                                     SourceRange SR) {
04163           S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
04164         }
04165       } Diagnoser(ArgType);
04166 
04167       Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
04168                                             false).take();
04169       if (!Arg)
04170         return ExprError();
04171     }
04172 
04173     // From here on out, all we care about are the unqualified forms
04174     // of the parameter and argument types.
04175     ParamType = ParamType.getUnqualifiedType();
04176     ArgType = ArgType.getUnqualifiedType();
04177 
04178     // Try to convert the argument to the parameter's type.
04179     if (Context.hasSameType(ParamType, ArgType)) {
04180       // Okay: no conversion necessary
04181     } else if (ParamType->isBooleanType()) {
04182       // This is an integral-to-boolean conversion.
04183       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).take();
04184     } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
04185                !ParamType->isEnumeralType()) {
04186       // This is an integral promotion or conversion.
04187       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).take();
04188     } else {
04189       // We can't perform this conversion.
04190       Diag(Arg->getLocStart(),
04191            diag::err_template_arg_not_convertible)
04192         << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
04193       Diag(Param->getLocation(), diag::note_template_param_here);
04194       return ExprError();
04195     }
04196 
04197     // Add the value of this argument to the list of converted
04198     // arguments. We use the bitwidth and signedness of the template
04199     // parameter.
04200     if (Arg->isValueDependent()) {
04201       // The argument is value-dependent. Create a new
04202       // TemplateArgument with the converted expression.
04203       Converted = TemplateArgument(Arg);
04204       return Owned(Arg);
04205     }
04206 
04207     QualType IntegerType = Context.getCanonicalType(ParamType);
04208     if (const EnumType *Enum = IntegerType->getAs<EnumType>())
04209       IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
04210 
04211     if (ParamType->isBooleanType()) {
04212       // Value must be zero or one.
04213       Value = Value != 0;
04214       unsigned AllowedBits = Context.getTypeSize(IntegerType);
04215       if (Value.getBitWidth() != AllowedBits)
04216         Value = Value.extOrTrunc(AllowedBits);
04217       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
04218     } else {
04219       llvm::APSInt OldValue = Value;
04220       
04221       // Coerce the template argument's value to the value it will have
04222       // based on the template parameter's type.
04223       unsigned AllowedBits = Context.getTypeSize(IntegerType);
04224       if (Value.getBitWidth() != AllowedBits)
04225         Value = Value.extOrTrunc(AllowedBits);
04226       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
04227       
04228       // Complain if an unsigned parameter received a negative value.
04229       if (IntegerType->isUnsignedIntegerOrEnumerationType()
04230                && (OldValue.isSigned() && OldValue.isNegative())) {
04231         Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
04232           << OldValue.toString(10) << Value.toString(10) << Param->getType()
04233           << Arg->getSourceRange();
04234         Diag(Param->getLocation(), diag::note_template_param_here);
04235       }
04236       
04237       // Complain if we overflowed the template parameter's type.
04238       unsigned RequiredBits;
04239       if (IntegerType->isUnsignedIntegerOrEnumerationType())
04240         RequiredBits = OldValue.getActiveBits();
04241       else if (OldValue.isUnsigned())
04242         RequiredBits = OldValue.getActiveBits() + 1;
04243       else
04244         RequiredBits = OldValue.getMinSignedBits();
04245       if (RequiredBits > AllowedBits) {
04246         Diag(Arg->getLocStart(),
04247              diag::warn_template_arg_too_large)
04248           << OldValue.toString(10) << Value.toString(10) << Param->getType()
04249           << Arg->getSourceRange();
04250         Diag(Param->getLocation(), diag::note_template_param_here);
04251       }
04252     }
04253 
04254     Converted = TemplateArgument(Value,
04255                                  ParamType->isEnumeralType() 
04256                                    ? Context.getCanonicalType(ParamType)
04257                                    : IntegerType);
04258     return Owned(Arg);
04259   }
04260 
04261   QualType ArgType = Arg->getType();
04262   DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
04263 
04264   // Handle pointer-to-function, reference-to-function, and
04265   // pointer-to-member-function all in (roughly) the same way.
04266   if (// -- For a non-type template-parameter of type pointer to
04267       //    function, only the function-to-pointer conversion (4.3) is
04268       //    applied. If the template-argument represents a set of
04269       //    overloaded functions (or a pointer to such), the matching
04270       //    function is selected from the set (13.4).
04271       (ParamType->isPointerType() &&
04272        ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
04273       // -- For a non-type template-parameter of type reference to
04274       //    function, no conversions apply. If the template-argument
04275       //    represents a set of overloaded functions, the matching
04276       //    function is selected from the set (13.4).
04277       (ParamType->isReferenceType() &&
04278        ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
04279       // -- For a non-type template-parameter of type pointer to
04280       //    member function, no conversions apply. If the
04281       //    template-argument represents a set of overloaded member
04282       //    functions, the matching member function is selected from
04283       //    the set (13.4).
04284       (ParamType->isMemberPointerType() &&
04285        ParamType->getAs<MemberPointerType>()->getPointeeType()
04286          ->isFunctionType())) {
04287 
04288     if (Arg->getType() == Context.OverloadTy) {
04289       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
04290                                                                 true,
04291                                                                 FoundResult)) {
04292         if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
04293           return ExprError();
04294 
04295         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
04296         ArgType = Arg->getType();
04297       } else
04298         return ExprError();
04299     }
04300 
04301     if (!ParamType->isMemberPointerType()) {
04302       if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
04303                                                          ParamType,
04304                                                          Arg, Converted))
04305         return ExprError();
04306       return Owned(Arg);
04307     }
04308 
04309     if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
04310                                              Converted))
04311       return ExprError();
04312     return Owned(Arg);
04313   }
04314 
04315   if (ParamType->isPointerType()) {
04316     //   -- for a non-type template-parameter of type pointer to
04317     //      object, qualification conversions (4.4) and the
04318     //      array-to-pointer conversion (4.2) are applied.
04319     // C++0x also allows a value of std::nullptr_t.
04320     assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
04321            "Only object pointers allowed here");
04322 
04323     if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
04324                                                        ParamType,
04325                                                        Arg, Converted))
04326       return ExprError();
04327     return Owned(Arg);
04328   }
04329 
04330   if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
04331     //   -- For a non-type template-parameter of type reference to
04332     //      object, no conversions apply. The type referred to by the
04333     //      reference may be more cv-qualified than the (otherwise
04334     //      identical) type of the template-argument. The
04335     //      template-parameter is bound directly to the
04336     //      template-argument, which must be an lvalue.
04337     assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
04338            "Only object references allowed here");
04339 
04340     if (Arg->getType() == Context.OverloadTy) {
04341       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
04342                                                  ParamRefType->getPointeeType(),
04343                                                                 true,
04344                                                                 FoundResult)) {
04345         if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
04346           return ExprError();
04347 
04348         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
04349         ArgType = Arg->getType();
04350       } else
04351         return ExprError();
04352     }
04353 
04354     if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
04355                                                        ParamType,
04356                                                        Arg, Converted))
04357       return ExprError();
04358     return Owned(Arg);
04359   }
04360 
04361   // Deal with parameters of type std::nullptr_t.
04362   if (ParamType->isNullPtrType()) {
04363     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
04364       Converted = TemplateArgument(Arg);
04365       return Owned(Arg);
04366     }
04367     
04368     switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
04369     case NPV_NotNullPointer:
04370       Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
04371         << Arg->getType() << ParamType;
04372       Diag(Param->getLocation(), diag::note_template_param_here);
04373       return ExprError();
04374       
04375     case NPV_Error:
04376       return ExprError();
04377       
04378     case NPV_NullPointer:
04379       Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
04380       Converted = TemplateArgument((Decl *)0);
04381       return Owned(Arg);;
04382     }
04383   }
04384 
04385   //     -- For a non-type template-parameter of type pointer to data
04386   //        member, qualification conversions (4.4) are applied.
04387   assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
04388 
04389   if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
04390                                            Converted))
04391     return ExprError();
04392   return Owned(Arg);
04393 }
04394 
04395 /// \brief Check a template argument against its corresponding
04396 /// template template parameter.
04397 ///
04398 /// This routine implements the semantics of C++ [temp.arg.template].
04399 /// It returns true if an error occurred, and false otherwise.
04400 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
04401                                  const TemplateArgumentLoc &Arg) {
04402   TemplateName Name = Arg.getArgument().getAsTemplate();
04403   TemplateDecl *Template = Name.getAsTemplateDecl();
04404   if (!Template) {
04405     // Any dependent template name is fine.
04406     assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
04407     return false;
04408   }
04409 
04410   // C++0x [temp.arg.template]p1:
04411   //   A template-argument for a template template-parameter shall be
04412   //   the name of a class template or an alias template, expressed as an
04413   //   id-expression. When the template-argument names a class template, only
04414   //   primary class templates are considered when matching the
04415   //   template template argument with the corresponding parameter;
04416   //   partial specializations are not considered even if their
04417   //   parameter lists match that of the template template parameter.
04418   //
04419   // Note that we also allow template template parameters here, which
04420   // will happen when we are dealing with, e.g., class template
04421   // partial specializations.
04422   if (!isa<ClassTemplateDecl>(Template) &&
04423       !isa<TemplateTemplateParmDecl>(Template) &&
04424       !isa<TypeAliasTemplateDecl>(Template)) {
04425     assert(isa<FunctionTemplateDecl>(Template) &&
04426            "Only function templates are possible here");
04427     Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
04428     Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
04429       << Template;
04430   }
04431 
04432   return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
04433                                          Param->getTemplateParameters(),
04434                                          true,
04435                                          TPL_TemplateTemplateArgumentMatch,
04436                                          Arg.getLocation());
04437 }
04438 
04439 /// \brief Given a non-type template argument that refers to a
04440 /// declaration and the type of its corresponding non-type template
04441 /// parameter, produce an expression that properly refers to that
04442 /// declaration.
04443 ExprResult
04444 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
04445                                               QualType ParamType,
04446                                               SourceLocation Loc) {
04447   assert(Arg.getKind() == TemplateArgument::Declaration &&
04448          "Only declaration template arguments permitted here");
04449   
04450   // For a NULL non-type template argument, return nullptr casted to the
04451   // parameter's type.
04452   if (!Arg.getAsDecl()) {
04453     return ImpCastExprToType(
04454              new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
04455                              ParamType,
04456                              ParamType->getAs<MemberPointerType>()
04457                                ? CK_NullToMemberPointer
04458                                : CK_NullToPointer);
04459   }
04460   
04461   ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
04462 
04463   if (VD->getDeclContext()->isRecord() &&
04464       (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
04465     // If the value is a class member, we might have a pointer-to-member.
04466     // Determine whether the non-type template template parameter is of
04467     // pointer-to-member type. If so, we need to build an appropriate
04468     // expression for a pointer-to-member, since a "normal" DeclRefExpr
04469     // would refer to the member itself.
04470     if (ParamType->isMemberPointerType()) {
04471       QualType ClassType
04472         = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
04473       NestedNameSpecifier *Qualifier
04474         = NestedNameSpecifier::Create(Context, 0, false,
04475                                       ClassType.getTypePtr());
04476       CXXScopeSpec SS;
04477       SS.MakeTrivial(Context, Qualifier, Loc);
04478 
04479       // The actual value-ness of this is unimportant, but for
04480       // internal consistency's sake, references to instance methods
04481       // are r-values.
04482       ExprValueKind VK = VK_LValue;
04483       if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
04484         VK = VK_RValue;
04485 
04486       ExprResult RefExpr = BuildDeclRefExpr(VD,
04487                                             VD->getType().getNonReferenceType(),
04488                                             VK,
04489                                             Loc,
04490                                             &SS);
04491       if (RefExpr.isInvalid())
04492         return ExprError();
04493 
04494       RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
04495 
04496       // We might need to perform a trailing qualification conversion, since
04497       // the element type on the parameter could be more qualified than the
04498       // element type in the expression we constructed.
04499       bool ObjCLifetimeConversion;
04500       if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
04501                                     ParamType.getUnqualifiedType(), false,
04502                                     ObjCLifetimeConversion))
04503         RefExpr = ImpCastExprToType(RefExpr.take(), ParamType.getUnqualifiedType(), CK_NoOp);
04504 
04505       assert(!RefExpr.isInvalid() &&
04506              Context.hasSameType(((Expr*) RefExpr.get())->getType(),
04507                                  ParamType.getUnqualifiedType()));
04508       return move(RefExpr);
04509     }
04510   }
04511 
04512   QualType T = VD->getType().getNonReferenceType();
04513   if (ParamType->isPointerType()) {
04514     // When the non-type template parameter is a pointer, take the
04515     // address of the declaration.
04516     ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
04517     if (RefExpr.isInvalid())
04518       return ExprError();
04519 
04520     if (T->isFunctionType() || T->isArrayType()) {
04521       // Decay functions and arrays.
04522       RefExpr = DefaultFunctionArrayConversion(RefExpr.take());
04523       if (RefExpr.isInvalid())
04524         return ExprError();
04525 
04526       return move(RefExpr);
04527     }
04528 
04529     // Take the address of everything else
04530     return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
04531   }
04532 
04533   ExprValueKind VK = VK_RValue;
04534 
04535   // If the non-type template parameter has reference type, qualify the
04536   // resulting declaration reference with the extra qualifiers on the
04537   // type that the reference refers to.
04538   if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
04539     VK = VK_LValue;
04540     T = Context.getQualifiedType(T,
04541                               TargetRef->getPointeeType().getQualifiers());
04542   }
04543 
04544   return BuildDeclRefExpr(VD, T, VK, Loc);
04545 }
04546 
04547 /// \brief Construct a new expression that refers to the given
04548 /// integral template argument with the given source-location
04549 /// information.
04550 ///
04551 /// This routine takes care of the mapping from an integral template
04552 /// argument (which may have any integral type) to the appropriate
04553 /// literal value.
04554 ExprResult
04555 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
04556                                                   SourceLocation Loc) {
04557   assert(Arg.getKind() == TemplateArgument::Integral &&
04558          "Operation is only valid for integral template arguments");
04559   QualType T = Arg.getIntegralType();
04560   if (T->isAnyCharacterType()) {
04561     CharacterLiteral::CharacterKind Kind;
04562     if (T->isWideCharType())
04563       Kind = CharacterLiteral::Wide;
04564     else if (T->isChar16Type())
04565       Kind = CharacterLiteral::UTF16;
04566     else if (T->isChar32Type())
04567       Kind = CharacterLiteral::UTF32;
04568     else
04569       Kind = CharacterLiteral::Ascii;
04570 
04571     return Owned(new (Context) CharacterLiteral(
04572                                             Arg.getAsIntegral()->getZExtValue(),
04573                                             Kind, T, Loc));
04574   }
04575 
04576   if (T->isBooleanType())
04577     return Owned(new (Context) CXXBoolLiteralExpr(
04578                                             Arg.getAsIntegral()->getBoolValue(),
04579                                             T, Loc));
04580 
04581   if (T->isNullPtrType())
04582     return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
04583   
04584   // If this is an enum type that we're instantiating, we need to use an integer
04585   // type the same size as the enumerator.  We don't want to build an
04586   // IntegerLiteral with enum type.
04587   QualType BT;
04588   if (const EnumType *ET = T->getAs<EnumType>())
04589     BT = ET->getDecl()->getIntegerType();
04590   else
04591     BT = T;
04592 
04593   Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
04594   if (T->isEnumeralType()) {
04595     // FIXME: This is a hack. We need a better way to handle substituted
04596     // non-type template parameters.
04597     E = CStyleCastExpr::Create(Context, T, VK_RValue, CK_IntegralCast, E, 0, 
04598                                Context.getTrivialTypeSourceInfo(T, Loc),
04599                                Loc, Loc);
04600   }
04601   
04602   return Owned(E);
04603 }
04604 
04605 /// \brief Match two template parameters within template parameter lists.
04606 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
04607                                        bool Complain,
04608                                      Sema::TemplateParameterListEqualKind Kind,
04609                                        SourceLocation TemplateArgLoc) {
04610   // Check the actual kind (type, non-type, template).
04611   if (Old->getKind() != New->getKind()) {
04612     if (Complain) {
04613       unsigned NextDiag = diag::err_template_param_different_kind;
04614       if (TemplateArgLoc.isValid()) {
04615         S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
04616         NextDiag = diag::note_template_param_different_kind;
04617       }
04618       S.Diag(New->getLocation(), NextDiag)
04619         << (Kind != Sema::TPL_TemplateMatch);
04620       S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
04621         << (Kind != Sema::TPL_TemplateMatch);
04622     }
04623 
04624     return false;
04625   }
04626 
04627   // Check that both are parameter packs are neither are parameter packs.
04628   // However, if we are matching a template template argument to a
04629   // template template parameter, the template template parameter can have
04630   // a parameter pack where the template template argument does not.
04631   if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
04632       !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
04633         Old->isTemplateParameterPack())) {
04634     if (Complain) {
04635       unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
04636       if (TemplateArgLoc.isValid()) {
04637         S.Diag(TemplateArgLoc,
04638              diag::err_template_arg_template_params_mismatch);
04639         NextDiag = diag::note_template_parameter_pack_non_pack;
04640       }
04641 
04642       unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
04643                       : isa<NonTypeTemplateParmDecl>(New)? 1
04644                       : 2;
04645       S.Diag(New->getLocation(), NextDiag)
04646         << ParamKind << New->isParameterPack();
04647       S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
04648         << ParamKind << Old->isParameterPack();
04649     }
04650 
04651     return false;
04652   }
04653 
04654   // For non-type template parameters, check the type of the parameter.
04655   if (NonTypeTemplateParmDecl *OldNTTP
04656                                     = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
04657     NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
04658 
04659     // If we are matching a template template argument to a template
04660     // template parameter and one of the non-type template parameter types
04661     // is dependent, then we must wait until template instantiation time
04662     // to actually compare the arguments.
04663     if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
04664         (OldNTTP->getType()->isDependentType() ||
04665          NewNTTP->getType()->isDependentType()))
04666       return true;
04667 
04668     if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
04669       if (Complain) {
04670         unsigned NextDiag = diag::err_template_nontype_parm_different_type;
04671         if (TemplateArgLoc.isValid()) {
04672           S.Diag(TemplateArgLoc,
04673                  diag::err_template_arg_template_params_mismatch);
04674           NextDiag = diag::note_template_nontype_parm_different_type;
04675         }
04676         S.Diag(NewNTTP->getLocation(), NextDiag)
04677           << NewNTTP->getType()
04678           << (Kind != Sema::TPL_TemplateMatch);
04679         S.Diag(OldNTTP->getLocation(),
04680                diag::note_template_nontype_parm_prev_declaration)
04681           << OldNTTP->getType();
04682       }
04683 
04684       return false;
04685     }
04686 
04687     return true;
04688   }
04689 
04690   // For template template parameters, check the template parameter types.
04691   // The template parameter lists of template template
04692   // parameters must agree.
04693   if (TemplateTemplateParmDecl *OldTTP
04694                                     = dyn_cast<TemplateTemplateParmDecl>(Old)) {
04695     TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
04696     return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
04697                                             OldTTP->getTemplateParameters(),
04698                                             Complain,
04699                                         (Kind == Sema::TPL_TemplateMatch
04700                                            ? Sema::TPL_TemplateTemplateParmMatch
04701                                            : Kind),
04702                                             TemplateArgLoc);
04703   }
04704 
04705   return true;
04706 }
04707 
04708 /// \brief Diagnose a known arity mismatch when comparing template argument
04709 /// lists.
04710 static
04711 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
04712                                                 TemplateParameterList *New,
04713                                                 TemplateParameterList *Old,
04714                                       Sema::TemplateParameterListEqualKind Kind,
04715                                                 SourceLocation TemplateArgLoc) {
04716   unsigned NextDiag = diag::err_template_param_list_different_arity;
04717   if (TemplateArgLoc.isValid()) {
04718     S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
04719     NextDiag = diag::note_template_param_list_different_arity;
04720   }
04721   S.Diag(New->getTemplateLoc(), NextDiag)
04722     << (New->size() > Old->size())
04723     << (Kind != Sema::TPL_TemplateMatch)
04724     << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
04725   S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
04726     << (Kind != Sema::TPL_TemplateMatch)
04727     << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
04728 }
04729 
04730 /// \brief Determine whether the given template parameter lists are
04731 /// equivalent.
04732 ///
04733 /// \param New  The new template parameter list, typically written in the
04734 /// source code as part of a new template declaration.
04735 ///
04736 /// \param Old  The old template parameter list, typically found via
04737 /// name lookup of the template declared with this template parameter
04738 /// list.
04739 ///
04740 /// \param Complain  If true, this routine will produce a diagnostic if
04741 /// the template parameter lists are not equivalent.
04742 ///
04743 /// \param Kind describes how we are to match the template parameter lists.
04744 ///
04745 /// \param TemplateArgLoc If this source location is valid, then we
04746 /// are actually checking the template parameter list of a template
04747 /// argument (New) against the template parameter list of its
04748 /// corresponding template template parameter (Old). We produce
04749 /// slightly different diagnostics in this scenario.
04750 ///
04751 /// \returns True if the template parameter lists are equal, false
04752 /// otherwise.
04753 bool
04754 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
04755                                      TemplateParameterList *Old,
04756                                      bool Complain,
04757                                      TemplateParameterListEqualKind Kind,
04758                                      SourceLocation TemplateArgLoc) {
04759   if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
04760     if (Complain)
04761       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
04762                                                  TemplateArgLoc);
04763 
04764     return false;
04765   }
04766 
04767   // C++0x [temp.arg.template]p3:
04768   //   A template-argument matches a template template-parameter (call it P)
04769   //   when each of the template parameters in the template-parameter-list of
04770   //   the template-argument's corresponding class template or alias template
04771   //   (call it A) matches the corresponding template parameter in the
04772   //   template-parameter-list of P. [...]
04773   TemplateParameterList::iterator NewParm = New->begin();
04774   TemplateParameterList::iterator NewParmEnd = New->end();
04775   for (TemplateParameterList::iterator OldParm = Old->begin(),
04776                                     OldParmEnd = Old->end();
04777        OldParm != OldParmEnd; ++OldParm) {
04778     if (Kind != TPL_TemplateTemplateArgumentMatch ||
04779         !(*OldParm)->isTemplateParameterPack()) {
04780       if (NewParm == NewParmEnd) {
04781         if (Complain)
04782           DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
04783                                                      TemplateArgLoc);
04784 
04785         return false;
04786       }
04787 
04788       if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
04789                                       Kind, TemplateArgLoc))
04790         return false;
04791 
04792       ++NewParm;
04793       continue;
04794     }
04795 
04796     // C++0x [temp.arg.template]p3:
04797     //   [...] When P's template- parameter-list contains a template parameter
04798     //   pack (14.5.3), the template parameter pack will match zero or more
04799     //   template parameters or template parameter packs in the
04800     //   template-parameter-list of A with the same type and form as the
04801     //   template parameter pack in P (ignoring whether those template
04802     //   parameters are template parameter packs).
04803     for (; NewParm != NewParmEnd; ++NewParm) {
04804       if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
04805                                       Kind, TemplateArgLoc))
04806         return false;
04807     }
04808   }
04809 
04810   // Make sure we exhausted all of the arguments.
04811   if (NewParm != NewParmEnd) {
04812     if (Complain)
04813       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
04814                                                  TemplateArgLoc);
04815 
04816     return false;
04817   }
04818 
04819   return true;
04820 }
04821 
04822 /// \brief Check whether a template can be declared within this scope.
04823 ///
04824 /// If the template declaration is valid in this scope, returns
04825 /// false. Otherwise, issues a diagnostic and returns true.
04826 bool
04827 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
04828   if (!S)
04829     return false;
04830 
04831   // Find the nearest enclosing declaration scope.
04832   while ((S->getFlags() & Scope::DeclScope) == 0 ||
04833          (S->getFlags() & Scope::TemplateParamScope) != 0)
04834     S = S->getParent();
04835 
04836   // C++ [temp]p2:
04837   //   A template-declaration can appear only as a namespace scope or
04838   //   class scope declaration.
04839   DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
04840   if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
04841       cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
04842     return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
04843              << TemplateParams->getSourceRange();
04844 
04845   while (Ctx && isa<LinkageSpecDecl>(Ctx))
04846     Ctx = Ctx->getParent();
04847 
04848   if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
04849     return false;
04850 
04851   return Diag(TemplateParams->getTemplateLoc(),
04852               diag::err_template_outside_namespace_or_class_scope)
04853     << TemplateParams->getSourceRange();
04854 }
04855 
04856 /// \brief Determine what kind of template specialization the given declaration
04857 /// is.
04858 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
04859   if (!D)
04860     return TSK_Undeclared;
04861 
04862   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
04863     return Record->getTemplateSpecializationKind();
04864   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
04865     return Function->getTemplateSpecializationKind();
04866   if (VarDecl *Var = dyn_cast<VarDecl>(D))
04867     return Var->getTemplateSpecializationKind();
04868 
04869   return TSK_Undeclared;
04870 }
04871 
04872 /// \brief Check whether a specialization is well-formed in the current
04873 /// context.
04874 ///
04875 /// This routine determines whether a template specialization can be declared
04876 /// in the current context (C++ [temp.expl.spec]p2).
04877 ///
04878 /// \param S the semantic analysis object for which this check is being
04879 /// performed.
04880 ///
04881 /// \param Specialized the entity being specialized or instantiated, which
04882 /// may be a kind of template (class template, function template, etc.) or
04883 /// a member of a class template (member function, static data member,
04884 /// member class).
04885 ///
04886 /// \param PrevDecl the previous declaration of this entity, if any.
04887 ///
04888 /// \param Loc the location of the explicit specialization or instantiation of
04889 /// this entity.
04890 ///
04891 /// \param IsPartialSpecialization whether this is a partial specialization of
04892 /// a class template.
04893 ///
04894 /// \returns true if there was an error that we cannot recover from, false
04895 /// otherwise.
04896 static bool CheckTemplateSpecializationScope(Sema &S,
04897                                              NamedDecl *Specialized,
04898                                              NamedDecl *PrevDecl,
04899                                              SourceLocation Loc,
04900                                              bool IsPartialSpecialization) {
04901   // Keep these "kind" numbers in sync with the %select statements in the
04902   // various diagnostics emitted by this routine.
04903   int EntityKind = 0;
04904   if (isa<ClassTemplateDecl>(Specialized))
04905     EntityKind = IsPartialSpecialization? 1 : 0;
04906   else if (isa<FunctionTemplateDecl>(Specialized))
04907     EntityKind = 2;
04908   else if (isa<CXXMethodDecl>(Specialized))
04909     EntityKind = 3;
04910   else if (isa<VarDecl>(Specialized))
04911     EntityKind = 4;
04912   else if (isa<RecordDecl>(Specialized))
04913     EntityKind = 5;
04914   else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus0x)
04915     EntityKind = 6;
04916   else {
04917     S.Diag(Loc, diag::err_template_spec_unknown_kind)
04918       << S.getLangOpts().CPlusPlus0x;
04919     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
04920     return true;
04921   }
04922 
04923   // C++ [temp.expl.spec]p2:
04924   //   An explicit specialization shall be declared in the namespace
04925   //   of which the template is a member, or, for member templates, in
04926   //   the namespace of which the enclosing class or enclosing class
04927   //   template is a member. An explicit specialization of a member
04928   //   function, member class or static data member of a class
04929   //   template shall be declared in the namespace of which the class
04930   //   template is a member. Such a declaration may also be a
04931   //   definition. If the declaration is not a definition, the
04932   //   specialization may be defined later in the name- space in which
04933   //   the explicit specialization was declared, or in a namespace
04934   //   that encloses the one in which the explicit specialization was
04935   //   declared.
04936   if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
04937     S.Diag(Loc, diag::err_template_spec_decl_function_scope)
04938       << Specialized;
04939     return true;
04940   }
04941 
04942   if (S.CurContext->isRecord() && !IsPartialSpecialization) {
04943     if (S.getLangOpts().MicrosoftExt) {
04944       // Do not warn for class scope explicit specialization during
04945       // instantiation, warning was already emitted during pattern
04946       // semantic analysis.
04947       if (!S.ActiveTemplateInstantiations.size())
04948         S.Diag(Loc, diag::ext_function_specialization_in_class)
04949           << Specialized;
04950     } else {
04951       S.Diag(Loc, diag::err_template_spec_decl_class_scope)
04952         << Specialized;
04953       return true;
04954     }
04955   }
04956 
04957   if (S.CurContext->isRecord() &&
04958       !S.CurContext->Equals(Specialized->getDeclContext())) {
04959     // Make sure that we're specializing in the right record context.
04960     // Otherwise, things can go horribly wrong.
04961     S.Diag(Loc, diag::err_template_spec_decl_class_scope)
04962       << Specialized;
04963     return true;
04964   }
04965   
04966   // C++ [temp.class.spec]p6:
04967   //   A class template partial specialization may be declared or redeclared
04968   //   in any namespace scope in which its definition may be defined (14.5.1
04969   //   and 14.5.2).
04970   bool ComplainedAboutScope = false;
04971   DeclContext *SpecializedContext 
04972     = Specialized->getDeclContext()->getEnclosingNamespaceContext();
04973   DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
04974   if ((!PrevDecl ||
04975        getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
04976        getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
04977     // C++ [temp.exp.spec]p2:
04978     //   An explicit specialization shall be declared in the namespace of which
04979     //   the template is a member, or, for member templates, in the namespace
04980     //   of which the enclosing class or enclosing class template is a member.
04981     //   An explicit specialization of a member function, member class or
04982     //   static data member of a class template shall be declared in the
04983     //   namespace of which the class template is a member.
04984     //
04985     // C++0x [temp.expl.spec]p2:
04986     //   An explicit specialization shall be declared in a namespace enclosing
04987     //   the specialized template.
04988     if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
04989       bool IsCPlusPlus0xExtension = DC->Encloses(SpecializedContext);
04990       if (isa<TranslationUnitDecl>(SpecializedContext)) {
04991         assert(!IsCPlusPlus0xExtension &&
04992                "DC encloses TU but isn't in enclosing namespace set");
04993         S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
04994           << EntityKind << Specialized;
04995       } else if (isa<NamespaceDecl>(SpecializedContext)) {
04996         int Diag;
04997         if (!IsCPlusPlus0xExtension)
04998           Diag = diag::err_template_spec_decl_out_of_scope;
04999         else if (!S.getLangOpts().CPlusPlus0x)
05000           Diag = diag::ext_template_spec_decl_out_of_scope;
05001         else
05002           Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
05003         S.Diag(Loc, Diag)
05004           << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
05005       }
05006 
05007       S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
05008       ComplainedAboutScope =
05009         !(IsCPlusPlus0xExtension && S.getLangOpts().CPlusPlus0x);
05010     }
05011   }
05012 
05013   // Make sure that this redeclaration (or definition) occurs in an enclosing
05014   // namespace.
05015   // Note that HandleDeclarator() performs this check for explicit
05016   // specializations of function templates, static data members, and member
05017   // functions, so we skip the check here for those kinds of entities.
05018   // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
05019   // Should we refactor that check, so that it occurs later?
05020   if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
05021       !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
05022         isa<FunctionDecl>(Specialized))) {
05023     if (isa<TranslationUnitDecl>(SpecializedContext))
05024       S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
05025         << EntityKind << Specialized;
05026     else if (isa<NamespaceDecl>(SpecializedContext))
05027       S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
05028         << EntityKind << Specialized
05029         << cast<NamedDecl>(SpecializedContext);
05030 
05031     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
05032   }
05033 
05034   // FIXME: check for specialization-after-instantiation errors and such.
05035 
05036   return false;
05037 }
05038 
05039 /// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs
05040 /// that checks non-type template partial specialization arguments.
05041 static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S,
05042                                                 NonTypeTemplateParmDecl *Param,
05043                                                   const TemplateArgument *Args,
05044                                                         unsigned NumArgs) {
05045   for (unsigned I = 0; I != NumArgs; ++I) {
05046     if (Args[I].getKind() == TemplateArgument::Pack) {
05047       if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
05048                                                            Args[I].pack_begin(),
05049                                                            Args[I].pack_size()))
05050         return true;
05051 
05052       continue;
05053     }
05054 
05055     Expr *ArgExpr = Args[I].getAsExpr();
05056     if (!ArgExpr) {
05057       continue;
05058     }
05059 
05060     // We can have a pack expansion of any of the bullets below.
05061     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
05062       ArgExpr = Expansion->getPattern();
05063 
05064     // Strip off any implicit casts we added as part of type checking.
05065     while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
05066       ArgExpr = ICE->getSubExpr();
05067 
05068     // C++ [temp.class.spec]p8:
05069     //   A non-type argument is non-specialized if it is the name of a
05070     //   non-type parameter. All other non-type arguments are
05071     //   specialized.
05072     //
05073     // Below, we check the two conditions that only apply to
05074     // specialized non-type arguments, so skip any non-specialized
05075     // arguments.
05076     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
05077       if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
05078         continue;
05079 
05080     // C++ [temp.class.spec]p9:
05081     //   Within the argument list of a class template partial
05082     //   specialization, the following restrictions apply:
05083     //     -- A partially specialized non-type argument expression
05084     //        shall not involve a template parameter of the partial
05085     //        specialization except when the argument expression is a
05086     //        simple identifier.
05087     if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
05088       S.Diag(ArgExpr->getLocStart(),
05089            diag::err_dependent_non_type_arg_in_partial_spec)
05090         << ArgExpr->getSourceRange();
05091       return true;
05092     }
05093 
05094     //     -- The type of a template parameter corresponding to a
05095     //        specialized non-type argument shall not be dependent on a
05096     //        parameter of the specialization.
05097     if (Param->getType()->isDependentType()) {
05098       S.Diag(ArgExpr->getLocStart(),
05099            diag::err_dependent_typed_non_type_arg_in_partial_spec)
05100         << Param->getType()
05101         << ArgExpr->getSourceRange();
05102       S.Diag(Param->getLocation(), diag::note_template_param_here);
05103       return true;
05104     }
05105   }
05106 
05107   return false;
05108 }
05109 
05110 /// \brief Check the non-type template arguments of a class template
05111 /// partial specialization according to C++ [temp.class.spec]p9.
05112 ///
05113 /// \param TemplateParams the template parameters of the primary class
05114 /// template.
05115 ///
05116 /// \param TemplateArg the template arguments of the class template
05117 /// partial specialization.
05118 ///
05119 /// \returns true if there was an error, false otherwise.
05120 static bool CheckClassTemplatePartialSpecializationArgs(Sema &S,
05121                                         TemplateParameterList *TemplateParams,
05122                        SmallVectorImpl<TemplateArgument> &TemplateArgs) {
05123   const TemplateArgument *ArgList = TemplateArgs.data();
05124 
05125   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
05126     NonTypeTemplateParmDecl *Param
05127       = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
05128     if (!Param)
05129       continue;
05130 
05131     if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
05132                                                            &ArgList[I], 1))
05133       return true;
05134   }
05135 
05136   return false;
05137 }
05138 
05139 DeclResult
05140 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
05141                                        TagUseKind TUK,
05142                                        SourceLocation KWLoc,
05143                                        SourceLocation ModulePrivateLoc,
05144                                        CXXScopeSpec &SS,
05145                                        TemplateTy TemplateD,
05146                                        SourceLocation TemplateNameLoc,
05147                                        SourceLocation LAngleLoc,
05148                                        ASTTemplateArgsPtr TemplateArgsIn,
05149                                        SourceLocation RAngleLoc,
05150                                        AttributeList *Attr,
05151                                MultiTemplateParamsArg TemplateParameterLists) {
05152   assert(TUK != TUK_Reference && "References are not specializations");
05153 
05154   // NOTE: KWLoc is the location of the tag keyword. This will instead
05155   // store the location of the outermost template keyword in the declaration.
05156   SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
05157     ? TemplateParameterLists.get()[0]->getTemplateLoc() : SourceLocation();
05158 
05159   // Find the class template we're specializing
05160   TemplateName Name = TemplateD.getAsVal<TemplateName>();
05161   ClassTemplateDecl *ClassTemplate
05162     = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
05163 
05164   if (!ClassTemplate) {
05165     Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
05166       << (Name.getAsTemplateDecl() &&
05167           isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
05168     return true;
05169   }
05170 
05171   bool isExplicitSpecialization = false;
05172   bool isPartialSpecialization = false;
05173 
05174   // Check the validity of the template headers that introduce this
05175   // template.
05176   // FIXME: We probably shouldn't complain about these headers for
05177   // friend declarations.
05178   bool Invalid = false;
05179   TemplateParameterList *TemplateParams
05180     = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, 
05181                                               TemplateNameLoc,
05182                                               SS,
05183                         (TemplateParameterList**)TemplateParameterLists.get(),
05184                                               TemplateParameterLists.size(),
05185                                               TUK == TUK_Friend,
05186                                               isExplicitSpecialization,
05187                                               Invalid);
05188   if (Invalid)
05189     return true;
05190 
05191   if (TemplateParams && TemplateParams->size() > 0) {
05192     isPartialSpecialization = true;
05193 
05194     if (TUK == TUK_Friend) {
05195       Diag(KWLoc, diag::err_partial_specialization_friend)
05196         << SourceRange(LAngleLoc, RAngleLoc);
05197       return true;
05198     }
05199 
05200     // C++ [temp.class.spec]p10:
05201     //   The template parameter list of a specialization shall not
05202     //   contain default template argument values.
05203     for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
05204       Decl *Param = TemplateParams->getParam(I);
05205       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
05206         if (TTP->hasDefaultArgument()) {
05207           Diag(TTP->getDefaultArgumentLoc(),
05208                diag::err_default_arg_in_partial_spec);
05209           TTP->removeDefaultArgument();
05210         }
05211       } else if (NonTypeTemplateParmDecl *NTTP
05212                    = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
05213         if (Expr *DefArg = NTTP->getDefaultArgument()) {
05214           Diag(NTTP->getDefaultArgumentLoc(),
05215                diag::err_default_arg_in_partial_spec)
05216             << DefArg->getSourceRange();
05217           NTTP->removeDefaultArgument();
05218         }
05219       } else {
05220         TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
05221         if (TTP->hasDefaultArgument()) {
05222           Diag(TTP->getDefaultArgument().getLocation(),
05223                diag::err_default_arg_in_partial_spec)
05224             << TTP->getDefaultArgument().getSourceRange();
05225           TTP->removeDefaultArgument();
05226         }
05227       }
05228     }
05229   } else if (TemplateParams) {
05230     if (TUK == TUK_Friend)
05231       Diag(KWLoc, diag::err_template_spec_friend)
05232         << FixItHint::CreateRemoval(
05233                                 SourceRange(TemplateParams->getTemplateLoc(),
05234                                             TemplateParams->getRAngleLoc()))
05235         << SourceRange(LAngleLoc, RAngleLoc);
05236     else
05237       isExplicitSpecialization = true;
05238   } else if (TUK != TUK_Friend) {
05239     Diag(KWLoc, diag::err_template_spec_needs_header)
05240       << FixItHint::CreateInsertion(KWLoc, "template<> ");
05241     isExplicitSpecialization = true;
05242   }
05243 
05244   // Check that the specialization uses the same tag kind as the
05245   // original template.
05246   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
05247   assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
05248   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
05249                                     Kind, TUK == TUK_Definition, KWLoc,
05250                                     *ClassTemplate->getIdentifier())) {
05251     Diag(KWLoc, diag::err_use_with_wrong_tag)
05252       << ClassTemplate
05253       << FixItHint::CreateReplacement(KWLoc,
05254                             ClassTemplate->getTemplatedDecl()->getKindName());
05255     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
05256          diag::note_previous_use);
05257     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
05258   }
05259 
05260   // Translate the parser's template argument list in our AST format.
05261   TemplateArgumentListInfo TemplateArgs;
05262   TemplateArgs.setLAngleLoc(LAngleLoc);
05263   TemplateArgs.setRAngleLoc(RAngleLoc);
05264   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
05265 
05266   // Check for unexpanded parameter packs in any of the template arguments.
05267   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
05268     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
05269                                         UPPC_PartialSpecialization))
05270       return true;
05271 
05272   // Check that the template argument list is well-formed for this
05273   // template.
05274   SmallVector<TemplateArgument, 4> Converted;
05275   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
05276                                 TemplateArgs, false, Converted))
05277     return true;
05278 
05279   // Find the class template (partial) specialization declaration that
05280   // corresponds to these arguments.
05281   if (isPartialSpecialization) {
05282     if (CheckClassTemplatePartialSpecializationArgs(*this,
05283                                          ClassTemplate->getTemplateParameters(),
05284                                          Converted))
05285       return true;
05286 
05287     bool InstantiationDependent;
05288     if (!Name.isDependent() &&
05289         !TemplateSpecializationType::anyDependentTemplateArguments(
05290                                              TemplateArgs.getArgumentArray(),
05291                                                          TemplateArgs.size(),
05292                                                      InstantiationDependent)) {
05293       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
05294         << ClassTemplate->getDeclName();
05295       isPartialSpecialization = false;
05296     }
05297   }
05298 
05299   void *InsertPos = 0;
05300   ClassTemplateSpecializationDecl *PrevDecl = 0;
05301 
05302   if (isPartialSpecialization)
05303     // FIXME: Template parameter list matters, too
05304     PrevDecl
05305       = ClassTemplate->findPartialSpecialization(Converted.data(),
05306                                                  Converted.size(),
05307                                                  InsertPos);
05308   else
05309     PrevDecl
05310       = ClassTemplate->findSpecialization(Converted.data(),
05311                                           Converted.size(), InsertPos);
05312 
05313   ClassTemplateSpecializationDecl *Specialization = 0;
05314 
05315   // Check whether we can declare a class template specialization in
05316   // the current scope.
05317   if (TUK != TUK_Friend &&
05318       CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
05319                                        TemplateNameLoc,
05320                                        isPartialSpecialization))
05321     return true;
05322 
05323   // The canonical type
05324   QualType CanonType;
05325   if (PrevDecl &&
05326       (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
05327                TUK == TUK_Friend)) {
05328     // Since the only prior class template specialization with these
05329     // arguments was referenced but not declared, or we're only
05330     // referencing this specialization as a friend, reuse that
05331     // declaration node as our own, updating its source location and
05332     // the list of outer template parameters to reflect our new declaration.
05333     Specialization = PrevDecl;
05334     Specialization->setLocation(TemplateNameLoc);
05335     if (TemplateParameterLists.size() > 0) {
05336       Specialization->setTemplateParameterListsInfo(Context,
05337                                               TemplateParameterLists.size(),
05338                     (TemplateParameterList**) TemplateParameterLists.release());
05339     }
05340     PrevDecl = 0;
05341     CanonType = Context.getTypeDeclType(Specialization);
05342   } else if (isPartialSpecialization) {
05343     // Build the canonical type that describes the converted template
05344     // arguments of the class template partial specialization.
05345     TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
05346     CanonType = Context.getTemplateSpecializationType(CanonTemplate,
05347                                                       Converted.data(),
05348                                                       Converted.size());
05349 
05350     if (Context.hasSameType(CanonType,
05351                         ClassTemplate->getInjectedClassNameSpecialization())) {
05352       // C++ [temp.class.spec]p9b3:
05353       //
05354       //   -- The argument list of the specialization shall not be identical
05355       //      to the implicit argument list of the primary template.
05356       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
05357         << (TUK == TUK_Definition)
05358         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
05359       return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
05360                                 ClassTemplate->getIdentifier(),
05361                                 TemplateNameLoc,
05362                                 Attr,
05363                                 TemplateParams,
05364                                 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
05365                                 TemplateParameterLists.size() - 1,
05366                   (TemplateParameterList**) TemplateParameterLists.release());
05367     }
05368 
05369     // Create a new class template partial specialization declaration node.
05370     ClassTemplatePartialSpecializationDecl *PrevPartial
05371       = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
05372     unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
05373                             : ClassTemplate->getNextPartialSpecSequenceNumber();
05374     ClassTemplatePartialSpecializationDecl *Partial
05375       = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
05376                                              ClassTemplate->getDeclContext(),
05377                                                        KWLoc, TemplateNameLoc,
05378                                                        TemplateParams,
05379                                                        ClassTemplate,
05380                                                        Converted.data(),
05381                                                        Converted.size(),
05382                                                        TemplateArgs,
05383                                                        CanonType,
05384                                                        PrevPartial,
05385                                                        SequenceNumber);
05386     SetNestedNameSpecifier(Partial, SS);
05387     if (TemplateParameterLists.size() > 1 && SS.isSet()) {
05388       Partial->setTemplateParameterListsInfo(Context,
05389                                              TemplateParameterLists.size() - 1,
05390                     (TemplateParameterList**) TemplateParameterLists.release());
05391     }
05392 
05393     if (!PrevPartial)
05394       ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
05395     Specialization = Partial;
05396 
05397     // If we are providing an explicit specialization of a member class
05398     // template specialization, make a note of that.
05399     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
05400       PrevPartial->setMemberSpecialization();
05401 
05402     // Check that all of the template parameters of the class template
05403     // partial specialization are deducible from the template
05404     // arguments. If not, this class template partial specialization
05405     // will never be used.
05406     llvm::SmallBitVector DeducibleParams(TemplateParams->size());
05407     MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
05408                                TemplateParams->getDepth(),
05409                                DeducibleParams);
05410 
05411     if (!DeducibleParams.all()) {
05412       unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
05413       Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
05414         << (NumNonDeducible > 1)
05415         << SourceRange(TemplateNameLoc, RAngleLoc);
05416       for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
05417         if (!DeducibleParams[I]) {
05418           NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
05419           if (Param->getDeclName())
05420             Diag(Param->getLocation(),
05421                  diag::note_partial_spec_unused_parameter)
05422               << Param->getDeclName();
05423           else
05424             Diag(Param->getLocation(),
05425                  diag::note_partial_spec_unused_parameter)
05426               << "<anonymous>";
05427         }
05428       }
05429     }
05430   } else {
05431     // Create a new class template specialization declaration node for
05432     // this explicit specialization or friend declaration.
05433     Specialization
05434       = ClassTemplateSpecializationDecl::Create(Context, Kind,
05435                                              ClassTemplate->getDeclContext(),
05436                                                 KWLoc, TemplateNameLoc,
05437                                                 ClassTemplate,
05438                                                 Converted.data(),
05439                                                 Converted.size(),
05440                                                 PrevDecl);
05441     SetNestedNameSpecifier(Specialization, SS);
05442     if (TemplateParameterLists.size() > 0) {
05443       Specialization->setTemplateParameterListsInfo(Context,
05444                                               TemplateParameterLists.size(),
05445                     (TemplateParameterList**) TemplateParameterLists.release());
05446     }
05447 
05448     if (!PrevDecl)
05449       ClassTemplate->AddSpecialization(Specialization, InsertPos);
05450 
05451     CanonType = Context.getTypeDeclType(Specialization);
05452   }
05453 
05454   // C++ [temp.expl.spec]p6:
05455   //   If a template, a member template or the member of a class template is
05456   //   explicitly specialized then that specialization shall be declared
05457   //   before the first use of that specialization that would cause an implicit
05458   //   instantiation to take place, in every translation unit in which such a
05459   //   use occurs; no diagnostic is required.
05460   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
05461     bool Okay = false;
05462     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
05463       // Is there any previous explicit specialization declaration?
05464       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
05465         Okay = true;
05466         break;
05467       }
05468     }
05469 
05470     if (!Okay) {
05471       SourceRange Range(TemplateNameLoc, RAngleLoc);
05472       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
05473         << Context.getTypeDeclType(Specialization) << Range;
05474 
05475       Diag(PrevDecl->getPointOfInstantiation(),
05476            diag::note_instantiation_required_here)
05477         << (PrevDecl->getTemplateSpecializationKind()
05478                                                 != TSK_ImplicitInstantiation);
05479       return true;
05480     }
05481   }
05482 
05483   // If this is not a friend, note that this is an explicit specialization.
05484   if (TUK != TUK_Friend)
05485     Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
05486 
05487   // Check that this isn't a redefinition of this specialization.
05488   if (TUK == TUK_Definition) {
05489     if (RecordDecl *Def = Specialization->getDefinition()) {
05490       SourceRange Range(TemplateNameLoc, RAngleLoc);
05491       Diag(TemplateNameLoc, diag::err_redefinition)
05492         << Context.getTypeDeclType(Specialization) << Range;
05493       Diag(Def->getLocation(), diag::note_previous_definition);
05494       Specialization->setInvalidDecl();
05495       return true;
05496     }
05497   }
05498 
05499   if (Attr)
05500     ProcessDeclAttributeList(S, Specialization, Attr);
05501 
05502   if (ModulePrivateLoc.isValid())
05503     Diag(Specialization->getLocation(), diag::err_module_private_specialization)
05504       << (isPartialSpecialization? 1 : 0)
05505       << FixItHint::CreateRemoval(ModulePrivateLoc);
05506   
05507   // Build the fully-sugared type for this class template
05508   // specialization as the user wrote in the specialization
05509   // itself. This means that we'll pretty-print the type retrieved
05510   // from the specialization's declaration the way that the user
05511   // actually wrote the specialization, rather than formatting the
05512   // name based on the "canonical" representation used to store the
05513   // template arguments in the specialization.
05514   TypeSourceInfo *WrittenTy
05515     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
05516                                                 TemplateArgs, CanonType);
05517   if (TUK != TUK_Friend) {
05518     Specialization->setTypeAsWritten(WrittenTy);
05519     Specialization->setTemplateKeywordLoc(TemplateKWLoc);
05520   }
05521   TemplateArgsIn.release();
05522 
05523   // C++ [temp.expl.spec]p9:
05524   //   A template explicit specialization is in the scope of the
05525   //   namespace in which the template was defined.
05526   //
05527   // We actually implement this paragraph where we set the semantic
05528   // context (in the creation of the ClassTemplateSpecializationDecl),
05529   // but we also maintain the lexical context where the actual
05530   // definition occurs.
05531   Specialization->setLexicalDeclContext(CurContext);
05532 
05533   // We may be starting the definition of this specialization.
05534   if (TUK == TUK_Definition)
05535     Specialization->startDefinition();
05536 
05537   if (TUK == TUK_Friend) {
05538     FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
05539                                             TemplateNameLoc,
05540                                             WrittenTy,
05541                                             /*FIXME:*/KWLoc);
05542     Friend->setAccess(AS_public);
05543     CurContext->addDecl(Friend);
05544   } else {
05545     // Add the specialization into its lexical context, so that it can
05546     // be seen when iterating through the list of declarations in that
05547     // context. However, specializations are not found by name lookup.
05548     CurContext->addDecl(Specialization);
05549   }
05550   return Specialization;
05551 }
05552 
05553 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
05554                               MultiTemplateParamsArg TemplateParameterLists,
05555                                     Declarator &D) {
05556   return HandleDeclarator(S, D, move(TemplateParameterLists));
05557 }
05558 
05559 Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
05560                                MultiTemplateParamsArg TemplateParameterLists,
05561                                             Declarator &D) {
05562   assert(getCurFunctionDecl() == 0 && "Function parsing confused");
05563   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
05564 
05565   if (FTI.hasPrototype) {
05566     // FIXME: Diagnose arguments without names in C.
05567   }
05568 
05569   Scope *ParentScope = FnBodyScope->getParent();
05570 
05571   D.setFunctionDefinitionKind(FDK_Definition);
05572   Decl *DP = HandleDeclarator(ParentScope, D,
05573                               move(TemplateParameterLists));
05574   if (FunctionTemplateDecl *FunctionTemplate
05575         = dyn_cast_or_null<FunctionTemplateDecl>(DP))
05576     return ActOnStartOfFunctionDef(FnBodyScope,
05577                                    FunctionTemplate->getTemplatedDecl());
05578   if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
05579     return ActOnStartOfFunctionDef(FnBodyScope, Function);
05580   return 0;
05581 }
05582 
05583 /// \brief Strips various properties off an implicit instantiation
05584 /// that has just been explicitly specialized.
05585 static void StripImplicitInstantiation(NamedDecl *D) {
05586   // FIXME: "make check" is clean if the call to dropAttrs() is commented out.
05587   D->dropAttrs();
05588 
05589   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
05590     FD->setInlineSpecified(false);
05591   }
05592 }
05593 
05594 /// \brief Compute the diagnostic location for an explicit instantiation
05595 //  declaration or definition.
05596 static SourceLocation DiagLocForExplicitInstantiation(
05597     NamedDecl* D, SourceLocation PointOfInstantiation) {
05598   // Explicit instantiations following a specialization have no effect and
05599   // hence no PointOfInstantiation. In that case, walk decl backwards
05600   // until a valid name loc is found.
05601   SourceLocation PrevDiagLoc = PointOfInstantiation;
05602   for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
05603        Prev = Prev->getPreviousDecl()) {
05604     PrevDiagLoc = Prev->getLocation();
05605   }
05606   assert(PrevDiagLoc.isValid() &&
05607          "Explicit instantiation without point of instantiation?");
05608   return PrevDiagLoc;
05609 }
05610 
05611 /// \brief Diagnose cases where we have an explicit template specialization
05612 /// before/after an explicit template instantiation, producing diagnostics
05613 /// for those cases where they are required and determining whether the
05614 /// new specialization/instantiation will have any effect.
05615 ///
05616 /// \param NewLoc the location of the new explicit specialization or
05617 /// instantiation.
05618 ///
05619 /// \param NewTSK the kind of the new explicit specialization or instantiation.
05620 ///
05621 /// \param PrevDecl the previous declaration of the entity.
05622 ///
05623 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
05624 ///
05625 /// \param PrevPointOfInstantiation if valid, indicates where the previus
05626 /// declaration was instantiated (either implicitly or explicitly).
05627 ///
05628 /// \param HasNoEffect will be set to true to indicate that the new
05629 /// specialization or instantiation has no effect and should be ignored.
05630 ///
05631 /// \returns true if there was an error that should prevent the introduction of
05632 /// the new declaration into the AST, false otherwise.
05633 bool
05634 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
05635                                              TemplateSpecializationKind NewTSK,
05636                                              NamedDecl *PrevDecl,
05637                                              TemplateSpecializationKind PrevTSK,
05638                                         SourceLocation PrevPointOfInstantiation,
05639                                              bool &HasNoEffect) {
05640   HasNoEffect = false;
05641 
05642   switch (NewTSK) {
05643   case TSK_Undeclared:
05644   case TSK_ImplicitInstantiation:
05645     llvm_unreachable("Don't check implicit instantiations here");
05646 
05647   case TSK_ExplicitSpecialization:
05648     switch (PrevTSK) {
05649     case TSK_Undeclared:
05650     case TSK_ExplicitSpecialization:
05651       // Okay, we're just specializing something that is either already
05652       // explicitly specialized or has merely been mentioned without any
05653       // instantiation.
05654       return false;
05655 
05656     case TSK_ImplicitInstantiation:
05657       if (PrevPointOfInstantiation.isInvalid()) {
05658         // The declaration itself has not actually been instantiated, so it is
05659         // still okay to specialize it.
05660         StripImplicitInstantiation(PrevDecl);
05661         return false;
05662       }
05663       // Fall through
05664 
05665     case TSK_ExplicitInstantiationDeclaration:
05666     case TSK_ExplicitInstantiationDefinition:
05667       assert((PrevTSK == TSK_ImplicitInstantiation ||
05668               PrevPointOfInstantiation.isValid()) &&
05669              "Explicit instantiation without point of instantiation?");
05670 
05671       // C++ [temp.expl.spec]p6:
05672       //   If a template, a member template or the member of a class template
05673       //   is explicitly specialized then that specialization shall be declared
05674       //   before the first use of that specialization that would cause an
05675       //   implicit instantiation to take place, in every translation unit in
05676       //   which such a use occurs; no diagnostic is required.
05677       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
05678         // Is there any previous explicit specialization declaration?
05679         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
05680           return false;
05681       }
05682 
05683       Diag(NewLoc, diag::err_specialization_after_instantiation)
05684         << PrevDecl;
05685       Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
05686         << (PrevTSK != TSK_ImplicitInstantiation);
05687 
05688       return true;
05689     }
05690 
05691   case TSK_ExplicitInstantiationDeclaration:
05692     switch (PrevTSK) {
05693     case TSK_ExplicitInstantiationDeclaration:
05694       // This explicit instantiation declaration is redundant (that's okay).
05695       HasNoEffect = true;
05696       return false;
05697 
05698     case TSK_Undeclared:
05699     case TSK_ImplicitInstantiation:
05700       // We're explicitly instantiating something that may have already been
05701       // implicitly instantiated; that's fine.
05702       return false;
05703 
05704     case TSK_ExplicitSpecialization:
05705       // C++0x [temp.explicit]p4:
05706       //   For a given set of template parameters, if an explicit instantiation
05707       //   of a template appears after a declaration of an explicit
05708       //   specialization for that template, the explicit instantiation has no
05709       //   effect.
05710       HasNoEffect = true;
05711       return false;
05712 
05713     case TSK_ExplicitInstantiationDefinition:
05714       // C++0x [temp.explicit]p10:
05715       //   If an entity is the subject of both an explicit instantiation
05716       //   declaration and an explicit instantiation definition in the same
05717       //   translation unit, the definition shall follow the declaration.
05718       Diag(NewLoc,
05719            diag::err_explicit_instantiation_declaration_after_definition);
05720 
05721       // Explicit instantiations following a specialization have no effect and
05722       // hence no PrevPointOfInstantiation. In that case, walk decl backwards
05723       // until a valid name loc is found.
05724       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
05725            diag::note_explicit_instantiation_definition_here);
05726       HasNoEffect = true;
05727       return false;
05728     }
05729 
05730   case TSK_ExplicitInstantiationDefinition:
05731     switch (PrevTSK) {
05732     case TSK_Undeclared:
05733     case TSK_ImplicitInstantiation:
05734       // We're explicitly instantiating something that may have already been
05735       // implicitly instantiated; that's fine.
05736       return false;
05737 
05738     case TSK_ExplicitSpecialization:
05739       // C++ DR 259, C++0x [temp.explicit]p4:
05740       //   For a given set of template parameters, if an explicit
05741       //   instantiation of a template appears after a declaration of
05742       //   an explicit specialization for that template, the explicit
05743       //   instantiation has no effect.
05744       //
05745       // In C++98/03 mode, we only give an extension warning here, because it
05746       // is not harmful to try to explicitly instantiate something that
05747       // has been explicitly specialized.
05748       Diag(NewLoc, getLangOpts().CPlusPlus0x ?
05749            diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
05750            diag::ext_explicit_instantiation_after_specialization)
05751         << PrevDecl;
05752       Diag(PrevDecl->getLocation(),
05753            diag::note_previous_template_specialization);
05754       HasNoEffect = true;
05755       return false;
05756 
05757     case TSK_ExplicitInstantiationDeclaration:
05758       // We're explicity instantiating a definition for something for which we
05759       // were previously asked to suppress instantiations. That's fine.
05760 
05761       // C++0x [temp.explicit]p4:
05762       //   For a given set of template parameters, if an explicit instantiation
05763       //   of a template appears after a declaration of an explicit
05764       //   specialization for that template, the explicit instantiation has no
05765       //   effect.
05766       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
05767         // Is there any previous explicit specialization declaration?
05768         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
05769           HasNoEffect = true;
05770           break;
05771         }
05772       }
05773 
05774       return false;
05775 
05776     case TSK_ExplicitInstantiationDefinition:
05777       // C++0x [temp.spec]p5:
05778       //   For a given template and a given set of template-arguments,
05779       //     - an explicit instantiation definition shall appear at most once
05780       //       in a program,
05781       Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
05782         << PrevDecl;
05783       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
05784            diag::note_previous_explicit_instantiation);
05785       HasNoEffect = true;
05786       return false;
05787     }
05788   }
05789 
05790   llvm_unreachable("Missing specialization/instantiation case?");
05791 }
05792 
05793 /// \brief Perform semantic analysis for the given dependent function
05794 /// template specialization.  The only possible way to get a dependent
05795 /// function template specialization is with a friend declaration,
05796 /// like so:
05797 ///
05798 ///   template <class T> void foo(T);
05799 ///   template <class T> class A {
05800 ///     friend void foo<>(T);
05801 ///   };
05802 ///
05803 /// There really isn't any useful analysis we can do here, so we
05804 /// just store the information.
05805 bool
05806 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
05807                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
05808                                                    LookupResult &Previous) {
05809   // Remove anything from Previous that isn't a function template in
05810   // the correct context.
05811   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
05812   LookupResult::Filter F = Previous.makeFilter();
05813   while (F.hasNext()) {
05814     NamedDecl *D = F.next()->getUnderlyingDecl();
05815     if (!isa<FunctionTemplateDecl>(D) ||
05816         !FDLookupContext->InEnclosingNamespaceSetOf(
05817                               D->getDeclContext()->getRedeclContext()))
05818       F.erase();
05819   }
05820   F.done();
05821 
05822   // Should this be diagnosed here?
05823   if (Previous.empty()) return true;
05824 
05825   FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
05826                                          ExplicitTemplateArgs);
05827   return false;
05828 }
05829 
05830 /// \brief Perform semantic analysis for the given function template
05831 /// specialization.
05832 ///
05833 /// This routine performs all of the semantic analysis required for an
05834 /// explicit function template specialization. On successful completion,
05835 /// the function declaration \p FD will become a function template
05836 /// specialization.
05837 ///
05838 /// \param FD the function declaration, which will be updated to become a
05839 /// function template specialization.
05840 ///
05841 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
05842 /// if any. Note that this may be valid info even when 0 arguments are
05843 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
05844 /// as it anyway contains info on the angle brackets locations.
05845 ///
05846 /// \param Previous the set of declarations that may be specialized by
05847 /// this function specialization.
05848 bool
05849 Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
05850                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
05851                                           LookupResult &Previous) {
05852   // The set of function template specializations that could match this
05853   // explicit function template specialization.
05854   UnresolvedSet<8> Candidates;
05855 
05856   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
05857   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
05858          I != E; ++I) {
05859     NamedDecl *Ovl = (*I)->getUnderlyingDecl();
05860     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
05861       // Only consider templates found within the same semantic lookup scope as
05862       // FD.
05863       if (!FDLookupContext->InEnclosingNamespaceSetOf(
05864                                 Ovl->getDeclContext()->getRedeclContext()))
05865         continue;
05866 
05867       // C++ [temp.expl.spec]p11:
05868       //   A trailing template-argument can be left unspecified in the
05869       //   template-id naming an explicit function template specialization
05870       //   provided it can be deduced from the function argument type.
05871       // Perform template argument deduction to determine whether we may be
05872       // specializing this template.
05873       // FIXME: It is somewhat wasteful to build
05874       TemplateDeductionInfo Info(Context, FD->getLocation());
05875       FunctionDecl *Specialization = 0;
05876       if (TemplateDeductionResult TDK
05877             = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
05878                                       FD->getType(),
05879                                       Specialization,
05880                                       Info)) {
05881         // FIXME: Template argument deduction failed; record why it failed, so
05882         // that we can provide nifty diagnostics.
05883         (void)TDK;
05884         continue;
05885       }
05886 
05887       // Record this candidate.
05888       Candidates.addDecl(Specialization, I.getAccess());
05889     }
05890   }
05891 
05892   // Find the most specialized function template.
05893   UnresolvedSetIterator Result
05894     = getMostSpecialized(Candidates.begin(), Candidates.end(),
05895                          TPOC_Other, 0, FD->getLocation(),
05896                   PDiag(diag::err_function_template_spec_no_match)
05897                     << FD->getDeclName(),
05898                   PDiag(diag::err_function_template_spec_ambiguous)
05899                     << FD->getDeclName() << (ExplicitTemplateArgs != 0),
05900                   PDiag(diag::note_function_template_spec_matched));
05901   if (Result == Candidates.end())
05902     return true;
05903 
05904   // Ignore access information;  it doesn't figure into redeclaration checking.
05905   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
05906 
05907   FunctionTemplateSpecializationInfo *SpecInfo
05908     = Specialization->getTemplateSpecializationInfo();
05909   assert(SpecInfo && "Function template specialization info missing?");
05910 
05911   // Note: do not overwrite location info if previous template
05912   // specialization kind was explicit.
05913   TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
05914   if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
05915     Specialization->setLocation(FD->getLocation());
05916     // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
05917     // function can differ from the template declaration with respect to
05918     // the constexpr specifier.
05919     Specialization->setConstexpr(FD->isConstexpr());
05920   }
05921 
05922   // FIXME: Check if the prior specialization has a point of instantiation.
05923   // If so, we have run afoul of .
05924 
05925   // If this is a friend declaration, then we're not really declaring
05926   // an explicit specialization.
05927   bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
05928 
05929   // Check the scope of this explicit specialization.
05930   if (!isFriend &&
05931       CheckTemplateSpecializationScope(*this,
05932                                        Specialization->getPrimaryTemplate(),
05933                                        Specialization, FD->getLocation(),
05934                                        false))
05935     return true;
05936 
05937   // C++ [temp.expl.spec]p6:
05938   //   If a template, a member template or the member of a class template is
05939   //   explicitly specialized then that specialization shall be declared
05940   //   before the first use of that specialization that would cause an implicit
05941   //   instantiation to take place, in every translation unit in which such a
05942   //   use occurs; no diagnostic is required.
05943   bool HasNoEffect = false;
05944   if (!isFriend &&
05945       CheckSpecializationInstantiationRedecl(FD->getLocation(),
05946                                              TSK_ExplicitSpecialization,
05947                                              Specialization,
05948                                    SpecInfo->getTemplateSpecializationKind(),
05949                                          SpecInfo->getPointOfInstantiation(),
05950                                              HasNoEffect))
05951     return true;
05952   
05953   // Mark the prior declaration as an explicit specialization, so that later
05954   // clients know that this is an explicit specialization.
05955   if (!isFriend) {
05956     SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
05957     MarkUnusedFileScopedDecl(Specialization);
05958   }
05959 
05960   // Turn the given function declaration into a function template
05961   // specialization, with the template arguments from the previous
05962   // specialization.
05963   // Take copies of (semantic and syntactic) template argument lists.
05964   const TemplateArgumentList* TemplArgs = new (Context)
05965     TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
05966   FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
05967                                         TemplArgs, /*InsertPos=*/0,
05968                                     SpecInfo->getTemplateSpecializationKind(),
05969                                         ExplicitTemplateArgs);
05970   FD->setStorageClass(Specialization->getStorageClass());
05971   
05972   // The "previous declaration" for this function template specialization is
05973   // the prior function template specialization.
05974   Previous.clear();
05975   Previous.addDecl(Specialization);
05976   return false;
05977 }
05978 
05979 /// \brief Perform semantic analysis for the given non-template member
05980 /// specialization.
05981 ///
05982 /// This routine performs all of the semantic analysis required for an
05983 /// explicit member function specialization. On successful completion,
05984 /// the function declaration \p FD will become a member function
05985 /// specialization.
05986 ///
05987 /// \param Member the member declaration, which will be updated to become a
05988 /// specialization.
05989 ///
05990 /// \param Previous the set of declarations, one of which may be specialized
05991 /// by this function specialization;  the set will be modified to contain the
05992 /// redeclared member.
05993 bool
05994 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
05995   assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
05996 
05997   // Try to find the member we are instantiating.
05998   NamedDecl *Instantiation = 0;
05999   NamedDecl *InstantiatedFrom = 0;
06000   MemberSpecializationInfo *MSInfo = 0;
06001 
06002   if (Previous.empty()) {
06003     // Nowhere to look anyway.
06004   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
06005     for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
06006            I != E; ++I) {
06007       NamedDecl *D = (*I)->getUnderlyingDecl();
06008       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
06009         if (Context.hasSameType(Function->getType(), Method->getType())) {
06010           Instantiation = Method;
06011           InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
06012           MSInfo = Method->getMemberSpecializationInfo();
06013           break;
06014         }
06015       }
06016     }
06017   } else if (isa<VarDecl>(Member)) {
06018     VarDecl *PrevVar;
06019     if (Previous.isSingleResult() &&
06020         (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
06021       if (PrevVar->isStaticDataMember()) {
06022         Instantiation = PrevVar;
06023         InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
06024         MSInfo = PrevVar->getMemberSpecializationInfo();
06025       }
06026   } else if (isa<RecordDecl>(Member)) {
06027     CXXRecordDecl *PrevRecord;
06028     if (Previous.isSingleResult() &&
06029         (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
06030       Instantiation = PrevRecord;
06031       InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
06032       MSInfo = PrevRecord->getMemberSpecializationInfo();
06033     }
06034   } else if (isa<EnumDecl>(Member)) {
06035     EnumDecl *PrevEnum;
06036     if (Previous.isSingleResult() &&
06037         (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
06038       Instantiation = PrevEnum;
06039       InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
06040       MSInfo = PrevEnum->getMemberSpecializationInfo();
06041     }
06042   }
06043 
06044   if (!Instantiation) {
06045     // There is no previous declaration that matches. Since member
06046     // specializations are always out-of-line, the caller will complain about
06047     // this mismatch later.
06048     return false;
06049   }
06050 
06051   // If this is a friend, just bail out here before we start turning
06052   // things into explicit specializations.
06053   if (Member->getFriendObjectKind() != Decl::FOK_None) {
06054     // Preserve instantiation information.
06055     if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
06056       cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
06057                                       cast<CXXMethodDecl>(InstantiatedFrom),
06058         cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
06059     } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
06060       cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
06061                                       cast<CXXRecordDecl>(InstantiatedFrom),
06062         cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
06063     }
06064 
06065     Previous.clear();
06066     Previous.addDecl(Instantiation);
06067     return false;
06068   }
06069 
06070   // Make sure that this is a specialization of a member.
06071   if (!InstantiatedFrom) {
06072     Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
06073       << Member;
06074     Diag(Instantiation->getLocation(), diag::note_specialized_decl);
06075     return true;
06076   }
06077 
06078   // C++ [temp.expl.spec]p6:
06079   //   If a template, a member template or the member of a class template is
06080   //   explicitly specialized then that specialization shall be declared
06081   //   before the first use of that specialization that would cause an implicit
06082   //   instantiation to take place, in every translation unit in which such a
06083   //   use occurs; no diagnostic is required.
06084   assert(MSInfo && "Member specialization info missing?");
06085 
06086   bool HasNoEffect = false;
06087   if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
06088                                              TSK_ExplicitSpecialization,
06089                                              Instantiation,
06090                                      MSInfo->getTemplateSpecializationKind(),
06091                                            MSInfo->getPointOfInstantiation(),
06092                                              HasNoEffect))
06093     return true;
06094 
06095   // Check the scope of this explicit specialization.
06096   if (CheckTemplateSpecializationScope(*this,
06097                                        InstantiatedFrom,
06098                                        Instantiation, Member->getLocation(),
06099                                        false))
06100     return true;
06101 
06102   // Note that this is an explicit instantiation of a member.
06103   // the original declaration to note that it is an explicit specialization
06104   // (if it was previously an implicit instantiation). This latter step
06105   // makes bookkeeping easier.
06106   if (isa<FunctionDecl>(Member)) {
06107     FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
06108     if (InstantiationFunction->getTemplateSpecializationKind() ==
06109           TSK_ImplicitInstantiation) {
06110       InstantiationFunction->setTemplateSpecializationKind(
06111                                                   TSK_ExplicitSpecialization);
06112       InstantiationFunction->setLocation(Member->getLocation());
06113     }
06114 
06115     cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
06116                                         cast<CXXMethodDecl>(InstantiatedFrom),
06117                                                   TSK_ExplicitSpecialization);
06118     MarkUnusedFileScopedDecl(InstantiationFunction);
06119   } else if (isa<VarDecl>(Member)) {
06120     VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
06121     if (InstantiationVar->getTemplateSpecializationKind() ==
06122           TSK_ImplicitInstantiation) {
06123       InstantiationVar->setTemplateSpecializationKind(
06124                                                   TSK_ExplicitSpecialization);
06125       InstantiationVar->setLocation(Member->getLocation());
06126     }
06127 
06128     Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
06129                                                 cast<VarDecl>(InstantiatedFrom),
06130                                                 TSK_ExplicitSpecialization);
06131     MarkUnusedFileScopedDecl(InstantiationVar);
06132   } else if (isa<CXXRecordDecl>(Member)) {
06133     CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
06134     if (InstantiationClass->getTemplateSpecializationKind() ==
06135           TSK_ImplicitInstantiation) {
06136       InstantiationClass->setTemplateSpecializationKind(
06137                                                    TSK_ExplicitSpecialization);
06138       InstantiationClass->setLocation(Member->getLocation());
06139     }
06140 
06141     cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
06142                                         cast<CXXRecordDecl>(InstantiatedFrom),
06143                                                    TSK_ExplicitSpecialization);
06144   } else {
06145     assert(isa<EnumDecl>(Member) && "Only member enums remain");
06146     EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
06147     if (InstantiationEnum->getTemplateSpecializationKind() ==
06148           TSK_ImplicitInstantiation) {
06149       InstantiationEnum->setTemplateSpecializationKind(
06150                                                    TSK_ExplicitSpecialization);
06151       InstantiationEnum->setLocation(Member->getLocation());
06152     }
06153 
06154     cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
06155         cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
06156   }
06157 
06158   // Save the caller the trouble of having to figure out which declaration
06159   // this specialization matches.
06160   Previous.clear();
06161   Previous.addDecl(Instantiation);
06162   return false;
06163 }
06164 
06165 /// \brief Check the scope of an explicit instantiation.
06166 ///
06167 /// \returns true if a serious error occurs, false otherwise.
06168 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
06169                                             SourceLocation InstLoc,
06170                                             bool WasQualifiedName) {
06171   DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
06172   DeclContext *CurContext = S.CurContext->getRedeclContext();
06173 
06174   if (CurContext->isRecord()) {
06175     S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
06176       << D;
06177     return true;
06178   }
06179 
06180   // C++11 [temp.explicit]p3:
06181   //   An explicit instantiation shall appear in an enclosing namespace of its
06182   //   template. If the name declared in the explicit instantiation is an
06183   //   unqualified name, the explicit instantiation shall appear in the
06184   //   namespace where its template is declared or, if that namespace is inline
06185   //   (7.3.1), any namespace from its enclosing namespace set.
06186   //
06187   // This is DR275, which we do not retroactively apply to C++98/03.
06188   if (WasQualifiedName) {
06189     if (CurContext->Encloses(OrigContext))
06190       return false;
06191   } else {
06192     if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
06193       return false;
06194   }
06195 
06196   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
06197     if (WasQualifiedName)
06198       S.Diag(InstLoc,
06199              S.getLangOpts().CPlusPlus0x?
06200                diag::err_explicit_instantiation_out_of_scope :
06201                diag::warn_explicit_instantiation_out_of_scope_0x)
06202         << D << NS;
06203     else
06204       S.Diag(InstLoc,
06205              S.getLangOpts().CPlusPlus0x?
06206                diag::err_explicit_instantiation_unqualified_wrong_namespace :
06207                diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
06208         << D << NS;
06209   } else
06210     S.Diag(InstLoc,
06211            S.getLangOpts().CPlusPlus0x?
06212              diag::err_explicit_instantiation_must_be_global :
06213              diag::warn_explicit_instantiation_must_be_global_0x)
06214       << D;
06215   S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
06216   return false;
06217 }
06218 
06219 /// \brief Determine whether the given scope specifier has a template-id in it.
06220 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
06221   if (!SS.isSet())
06222     return false;
06223 
06224   // C++11 [temp.explicit]p3:
06225   //   If the explicit instantiation is for a member function, a member class
06226   //   or a static data member of a class template specialization, the name of
06227   //   the class template specialization in the qualified-id for the member
06228   //   name shall be a simple-template-id.
06229   //
06230   // C++98 has the same restriction, just worded differently.
06231   for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
06232        NNS; NNS = NNS->getPrefix())
06233     if (const Type *T = NNS->getAsType())
06234       if (isa<TemplateSpecializationType>(T))
06235         return true;
06236 
06237   return false;
06238 }
06239 
06240 // Explicit instantiation of a class template specialization
06241 DeclResult
06242 Sema::ActOnExplicitInstantiation(Scope *S,
06243                                  SourceLocation ExternLoc,
06244                                  SourceLocation TemplateLoc,
06245                                  unsigned TagSpec,
06246                                  SourceLocation KWLoc,
06247                                  const CXXScopeSpec &SS,
06248                                  TemplateTy TemplateD,
06249                                  SourceLocation TemplateNameLoc,
06250                                  SourceLocation LAngleLoc,
06251                                  ASTTemplateArgsPtr TemplateArgsIn,
06252                                  SourceLocation RAngleLoc,
06253                                  AttributeList *Attr) {
06254   // Find the class template we're specializing
06255   TemplateName Name = TemplateD.getAsVal<TemplateName>();
06256   ClassTemplateDecl *ClassTemplate
06257     = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
06258 
06259   // Check that the specialization uses the same tag kind as the
06260   // original template.
06261   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
06262   assert(Kind != TTK_Enum &&
06263          "Invalid enum tag in class template explicit instantiation!");
06264   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
06265                                     Kind, /*isDefinition*/false, KWLoc,
06266                                     *ClassTemplate->getIdentifier())) {
06267     Diag(KWLoc, diag::err_use_with_wrong_tag)
06268       << ClassTemplate
06269       << FixItHint::CreateReplacement(KWLoc,
06270                             ClassTemplate->getTemplatedDecl()->getKindName());
06271     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
06272          diag::note_previous_use);
06273     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
06274   }
06275 
06276   // C++0x [temp.explicit]p2:
06277   //   There are two forms of explicit instantiation: an explicit instantiation
06278   //   definition and an explicit instantiation declaration. An explicit
06279   //   instantiation declaration begins with the extern keyword. [...]
06280   TemplateSpecializationKind TSK
06281     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
06282                            : TSK_ExplicitInstantiationDeclaration;
06283 
06284   // Translate the parser's template argument list in our AST format.
06285   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
06286   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
06287 
06288   // Check that the template argument list is well-formed for this
06289   // template.
06290   SmallVector<TemplateArgument, 4> Converted;
06291   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
06292                                 TemplateArgs, false, Converted))
06293     return true;
06294 
06295   // Find the class template specialization declaration that
06296   // corresponds to these arguments.
06297   void *InsertPos = 0;
06298   ClassTemplateSpecializationDecl *PrevDecl
06299     = ClassTemplate->findSpecialization(Converted.data(),
06300                                         Converted.size(), InsertPos);
06301 
06302   TemplateSpecializationKind PrevDecl_TSK
06303     = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
06304 
06305   // C++0x [temp.explicit]p2:
06306   //   [...] An explicit instantiation shall appear in an enclosing
06307   //   namespace of its template. [...]
06308   //
06309   // This is C++ DR 275.
06310   if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
06311                                       SS.isSet()))
06312     return true;
06313 
06314   ClassTemplateSpecializationDecl *Specialization = 0;
06315 
06316   bool HasNoEffect = false;
06317   if (PrevDecl) {
06318     if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
06319                                                PrevDecl, PrevDecl_TSK,
06320                                             PrevDecl->getPointOfInstantiation(),
06321                                                HasNoEffect))
06322       return PrevDecl;
06323 
06324     // Even though HasNoEffect == true means that this explicit instantiation
06325     // has no effect on semantics, we go on to put its syntax in the AST.
06326 
06327     if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
06328         PrevDecl_TSK == TSK_Undeclared) {
06329       // Since the only prior class template specialization with these
06330       // arguments was referenced but not declared, reuse that
06331       // declaration node as our own, updating the source location
06332       // for the template name to reflect our new declaration.
06333       // (Other source locations will be updated later.)
06334       Specialization = PrevDecl;
06335       Specialization->setLocation(TemplateNameLoc);
06336       PrevDecl = 0;
06337     }
06338   }
06339 
06340   if (!Specialization) {
06341     // Create a new class template specialization declaration node for
06342     // this explicit specialization.
06343     Specialization
06344       = ClassTemplateSpecializationDecl::Create(Context, Kind,
06345                                              ClassTemplate->getDeclContext(),
06346                                                 KWLoc, TemplateNameLoc,
06347                                                 ClassTemplate,
06348                                                 Converted.data(),
06349                                                 Converted.size(),
06350                                                 PrevDecl);
06351     SetNestedNameSpecifier(Specialization, SS);
06352 
06353     if (!HasNoEffect && !PrevDecl) {
06354       // Insert the new specialization.
06355       ClassTemplate->AddSpecialization(Specialization, InsertPos);
06356     }
06357   }
06358 
06359   // Build the fully-sugared type for this explicit instantiation as
06360   // the user wrote in the explicit instantiation itself. This means
06361   // that we'll pretty-print the type retrieved from the
06362   // specialization's declaration the way that the user actually wrote
06363   // the explicit instantiation, rather than formatting the name based
06364   // on the "canonical" representation used to store the template
06365   // arguments in the specialization.
06366   TypeSourceInfo *WrittenTy
06367     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
06368                                                 TemplateArgs,
06369                                   Context.getTypeDeclType(Specialization));
06370   Specialization->setTypeAsWritten(WrittenTy);
06371   TemplateArgsIn.release();
06372 
06373   // Set source locations for keywords.
06374   Specialization->setExternLoc(ExternLoc);
06375   Specialization->setTemplateKeywordLoc(TemplateLoc);
06376 
06377   if (Attr)
06378     ProcessDeclAttributeList(S, Specialization, Attr);
06379 
06380   // Add the explicit instantiation into its lexical context. However,
06381   // since explicit instantiations are never found by name lookup, we
06382   // just put it into the declaration context directly.
06383   Specialization->setLexicalDeclContext(CurContext);
06384   CurContext->addDecl(Specialization);
06385 
06386   // Syntax is now OK, so return if it has no other effect on semantics.
06387   if (HasNoEffect) {
06388     // Set the template specialization kind.
06389     Specialization->setTemplateSpecializationKind(TSK);
06390     return Specialization;
06391   }
06392 
06393   // C++ [temp.explicit]p3:
06394   //   A definition of a class template or class member template
06395   //   shall be in scope at the point of the explicit instantiation of
06396   //   the class template or class member template.
06397   //
06398   // This check comes when we actually try to perform the
06399   // instantiation.
06400   ClassTemplateSpecializationDecl *Def
06401     = cast_or_null<ClassTemplateSpecializationDecl>(
06402                                               Specialization->getDefinition());
06403   if (!Def)
06404     InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
06405   else if (TSK == TSK_ExplicitInstantiationDefinition) {
06406     MarkVTableUsed(TemplateNameLoc, Specialization, true);
06407     Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
06408   }
06409 
06410   // Instantiate the members of this class template specialization.
06411   Def = cast_or_null<ClassTemplateSpecializationDecl>(
06412                                        Specialization->getDefinition());
06413   if (Def) {
06414     TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
06415 
06416     // Fix a TSK_ExplicitInstantiationDeclaration followed by a
06417     // TSK_ExplicitInstantiationDefinition
06418     if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
06419         TSK == TSK_ExplicitInstantiationDefinition)
06420       Def->setTemplateSpecializationKind(TSK);
06421 
06422     InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
06423   }
06424 
06425   // Set the template specialization kind.
06426   Specialization->setTemplateSpecializationKind(TSK);
06427   return Specialization;
06428 }
06429 
06430 // Explicit instantiation of a member class of a class template.
06431 DeclResult
06432 Sema::ActOnExplicitInstantiation(Scope *S,
06433                                  SourceLocation ExternLoc,
06434                                  SourceLocation TemplateLoc,
06435                                  unsigned TagSpec,
06436                                  SourceLocation KWLoc,
06437                                  CXXScopeSpec &SS,
06438                                  IdentifierInfo *Name,
06439                                  SourceLocation NameLoc,
06440                                  AttributeList *Attr) {
06441 
06442   bool Owned = false;
06443   bool IsDependent = false;
06444   Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
06445                         KWLoc, SS, Name, NameLoc, Attr, AS_none,
06446                         /*ModulePrivateLoc=*/SourceLocation(),
06447                         MultiTemplateParamsArg(*this, 0, 0),
06448                         Owned, IsDependent, SourceLocation(), false,
06449                         TypeResult());
06450   assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
06451 
06452   if (!TagD)
06453     return true;
06454 
06455   TagDecl *Tag = cast<TagDecl>(TagD);
06456   assert(!Tag->isEnum() && "shouldn't see enumerations here");
06457 
06458   if (Tag->isInvalidDecl())
06459     return true;
06460 
06461   CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
06462   CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
06463   if (!Pattern) {
06464     Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
06465       << Context.getTypeDeclType(Record);
06466     Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
06467     return true;
06468   }
06469 
06470   // C++0x [temp.explicit]p2:
06471   //   If the explicit instantiation is for a class or member class, the
06472   //   elaborated-type-specifier in the declaration shall include a
06473   //   simple-template-id.
06474   //
06475   // C++98 has the same restriction, just worded differently.
06476   if (!ScopeSpecifierHasTemplateId(SS))
06477     Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
06478       << Record << SS.getRange();
06479 
06480   // C++0x [temp.explicit]p2:
06481   //   There are two forms of explicit instantiation: an explicit instantiation
06482   //   definition and an explicit instantiation declaration. An explicit
06483   //   instantiation declaration begins with the extern keyword. [...]
06484   TemplateSpecializationKind TSK
06485     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
06486                            : TSK_ExplicitInstantiationDeclaration;
06487 
06488   // C++0x [temp.explicit]p2:
06489   //   [...] An explicit instantiation shall appear in an enclosing
06490   //   namespace of its template. [...]
06491   //
06492   // This is C++ DR 275.
06493   CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
06494 
06495   // Verify that it is okay to explicitly instantiate here.
06496   CXXRecordDecl *PrevDecl
06497     = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
06498   if (!PrevDecl && Record->getDefinition())
06499     PrevDecl = Record;
06500   if (PrevDecl) {
06501     MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
06502     bool HasNoEffect = false;
06503     assert(MSInfo && "No member specialization information?");
06504     if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
06505                                                PrevDecl,
06506                                         MSInfo->getTemplateSpecializationKind(),
06507                                              MSInfo->getPointOfInstantiation(),
06508                                                HasNoEffect))
06509       return true;
06510     if (HasNoEffect)
06511       return TagD;
06512   }
06513 
06514   CXXRecordDecl *RecordDef
06515     = cast_or_null<CXXRecordDecl>(Record->getDefinition());
06516   if (!RecordDef) {
06517     // C++ [temp.explicit]p3:
06518     //   A definition of a member class of a class template shall be in scope
06519     //   at the point of an explicit instantiation of the member class.
06520     CXXRecordDecl *Def
06521       = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
06522     if (!Def) {
06523       Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
06524         << 0 << Record->getDeclName() << Record->getDeclContext();
06525       Diag(Pattern->getLocation(), diag::note_forward_declaration)
06526         << Pattern;
06527       return true;
06528     } else {
06529       if (InstantiateClass(NameLoc, Record, Def,
06530                            getTemplateInstantiationArgs(Record),
06531                            TSK))
06532         return true;
06533 
06534       RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
06535       if (!RecordDef)
06536         return true;
06537     }
06538   }
06539 
06540   // Instantiate all of the members of the class.
06541   InstantiateClassMembers(NameLoc, RecordDef,
06542                           getTemplateInstantiationArgs(Record), TSK);
06543 
06544   if (TSK == TSK_ExplicitInstantiationDefinition)
06545     MarkVTableUsed(NameLoc, RecordDef, true);
06546 
06547   // FIXME: We don't have any representation for explicit instantiations of
06548   // member classes. Such a representation is not needed for compilation, but it
06549   // should be available for clients that want to see all of the declarations in
06550   // the source code.
06551   return TagD;
06552 }
06553 
06554 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
06555                                             SourceLocation ExternLoc,
06556                                             SourceLocation TemplateLoc,
06557                                             Declarator &D) {
06558   // Explicit instantiations always require a name.
06559   // TODO: check if/when DNInfo should replace Name.
06560   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
06561   DeclarationName Name = NameInfo.getName();
06562   if (!Name) {
06563     if (!D.isInvalidType())
06564       Diag(D.getDeclSpec().getLocStart(),
06565            diag::err_explicit_instantiation_requires_name)
06566         << D.getDeclSpec().getSourceRange()
06567         << D.getSourceRange();
06568 
06569     return true;
06570   }
06571 
06572   // The scope passed in may not be a decl scope.  Zip up the scope tree until
06573   // we find one that is.
06574   while ((S->getFlags() & Scope::DeclScope) == 0 ||
06575          (S->getFlags() & Scope::TemplateParamScope) != 0)
06576     S = S->getParent();
06577 
06578   // Determine the type of the declaration.
06579   TypeSourceInfo *T = GetTypeForDeclarator(D, S);
06580   QualType R = T->getType();
06581   if (R.isNull())
06582     return true;
06583 
06584   // C++ [dcl.stc]p1:
06585   //   A storage-class-specifier shall not be specified in [...] an explicit 
06586   //   instantiation (14.7.2) directive.
06587   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
06588     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
06589       << Name;
06590     return true;
06591   } else if (D.getDeclSpec().getStorageClassSpec() 
06592                                                 != DeclSpec::SCS_unspecified) {
06593     // Complain about then remove the storage class specifier.
06594     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
06595       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
06596     
06597     D.getMutableDeclSpec().ClearStorageClassSpecs();
06598   }
06599 
06600   // C++0x [temp.explicit]p1:
06601   //   [...] An explicit instantiation of a function template shall not use the
06602   //   inline or constexpr specifiers.
06603   // Presumably, this also applies to member functions of class templates as
06604   // well.
06605   if (D.getDeclSpec().isInlineSpecified())
06606     Diag(D.getDeclSpec().getInlineSpecLoc(),
06607          getLangOpts().CPlusPlus0x ?
06608            diag::err_explicit_instantiation_inline :
06609            diag::warn_explicit_instantiation_inline_0x)
06610       << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
06611   if (D.getDeclSpec().isConstexprSpecified())
06612     // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
06613     // not already specified.
06614     Diag(D.getDeclSpec().getConstexprSpecLoc(),
06615          diag::err_explicit_instantiation_constexpr);
06616 
06617   // C++0x [temp.explicit]p2:
06618   //   There are two forms of explicit instantiation: an explicit instantiation
06619   //   definition and an explicit instantiation declaration. An explicit
06620   //   instantiation declaration begins with the extern keyword. [...]
06621   TemplateSpecializationKind TSK
06622     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
06623                            : TSK_ExplicitInstantiationDeclaration;
06624 
06625   LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
06626   LookupParsedName(Previous, S, &D.getCXXScopeSpec());
06627 
06628   if (!R->isFunctionType()) {
06629     // C++ [temp.explicit]p1:
06630     //   A [...] static data member of a class template can be explicitly
06631     //   instantiated from the member definition associated with its class
06632     //   template.
06633     if (Previous.isAmbiguous())
06634       return true;
06635 
06636     VarDecl *Prev = Previous.getAsSingle<VarDecl>();
06637     if (!Prev || !Prev->isStaticDataMember()) {
06638       // We expect to see a data data member here.
06639       Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
06640         << Name;
06641       for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
06642            P != PEnd; ++P)
06643         Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
06644       return true;
06645     }
06646 
06647     if (!Prev->getInstantiatedFromStaticDataMember()) {
06648       // FIXME: Check for explicit specialization?
06649       Diag(D.getIdentifierLoc(),
06650            diag::err_explicit_instantiation_data_member_not_instantiated)
06651         << Prev;
06652       Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
06653       // FIXME: Can we provide a note showing where this was declared?
06654       return true;
06655     }
06656 
06657     // C++0x [temp.explicit]p2:
06658     //   If the explicit instantiation is for a member function, a member class
06659     //   or a static data member of a class template specialization, the name of
06660     //   the class template specialization in the qualified-id for the member
06661     //   name shall be a simple-template-id.
06662     //
06663     // C++98 has the same restriction, just worded differently.
06664     if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
06665       Diag(D.getIdentifierLoc(),
06666            diag::ext_explicit_instantiation_without_qualified_id)
06667         << Prev << D.getCXXScopeSpec().getRange();
06668 
06669     // Check the scope of this explicit instantiation.
06670     CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
06671 
06672     // Verify that it is okay to explicitly instantiate here.
06673     MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
06674     assert(MSInfo && "Missing static data member specialization info?");
06675     bool HasNoEffect = false;
06676     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
06677                                         MSInfo->getTemplateSpecializationKind(),
06678                                               MSInfo->getPointOfInstantiation(),
06679                                                HasNoEffect))
06680       return true;
06681     if (HasNoEffect)
06682       return (Decl*) 0;
06683 
06684     // Instantiate static data member.
06685     Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
06686     if (TSK == TSK_ExplicitInstantiationDefinition)
06687       InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
06688 
06689     // FIXME: Create an ExplicitInstantiation node?
06690     return (Decl*) 0;
06691   }
06692 
06693   // If the declarator is a template-id, translate the parser's template
06694   // argument list into our AST format.
06695   bool HasExplicitTemplateArgs = false;
06696   TemplateArgumentListInfo TemplateArgs;
06697   if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
06698     TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
06699     TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
06700     TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
06701     ASTTemplateArgsPtr TemplateArgsPtr(*this,
06702                                        TemplateId->getTemplateArgs(),
06703                                        TemplateId->NumArgs);
06704     translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
06705     HasExplicitTemplateArgs = true;
06706     TemplateArgsPtr.release();
06707   }
06708 
06709   // C++ [temp.explicit]p1:
06710   //   A [...] function [...] can be explicitly instantiated from its template.
06711   //   A member function [...] of a class template can be explicitly
06712   //  instantiated from the member definition associated with its class
06713   //  template.
06714   UnresolvedSet<8> Matches;
06715   for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
06716        P != PEnd; ++P) {
06717     NamedDecl *Prev = *P;
06718     if (!HasExplicitTemplateArgs) {
06719       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
06720         if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
06721           Matches.clear();
06722 
06723           Matches.addDecl(Method, P.getAccess());
06724           if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
06725             break;
06726         }
06727       }
06728     }
06729 
06730     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
06731     if (!FunTmpl)
06732       continue;
06733 
06734     TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
06735     FunctionDecl *Specialization = 0;
06736     if (TemplateDeductionResult TDK
06737           = DeduceTemplateArguments(FunTmpl,
06738                                (HasExplicitTemplateArgs ? &TemplateArgs : 0),
06739                                     R, Specialization, Info)) {
06740       // FIXME: Keep track of almost-matches?
06741       (void)TDK;
06742       continue;
06743     }
06744 
06745     Matches.addDecl(Specialization, P.getAccess());
06746   }
06747 
06748   // Find the most specialized function template specialization.
06749   UnresolvedSetIterator Result
06750     = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0,
06751                          D.getIdentifierLoc(),
06752                      PDiag(diag::err_explicit_instantiation_not_known) << Name,
06753                      PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
06754                          PDiag(diag::note_explicit_instantiation_candidate));
06755 
06756   if (Result == Matches.end())
06757     return true;
06758 
06759   // Ignore access control bits, we don't need them for redeclaration checking.
06760   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
06761 
06762   if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
06763     Diag(D.getIdentifierLoc(),
06764          diag::err_explicit_instantiation_member_function_not_instantiated)
06765       << Specialization
06766       << (Specialization->getTemplateSpecializationKind() ==
06767           TSK_ExplicitSpecialization);
06768     Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
06769     return true;
06770   }
06771 
06772   FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
06773   if (!PrevDecl && Specialization->isThisDeclarationADefinition())
06774     PrevDecl = Specialization;
06775 
06776   if (PrevDecl) {
06777     bool HasNoEffect = false;
06778     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
06779                                                PrevDecl,
06780                                      PrevDecl->getTemplateSpecializationKind(),
06781                                           PrevDecl->getPointOfInstantiation(),
06782                                                HasNoEffect))
06783       return true;
06784 
06785     // FIXME: We may still want to build some representation of this
06786     // explicit specialization.
06787     if (HasNoEffect)
06788       return (Decl*) 0;
06789   }
06790 
06791   Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
06792   AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
06793   if (Attr)
06794     ProcessDeclAttributeList(S, Specialization, Attr);
06795 
06796   if (TSK == TSK_ExplicitInstantiationDefinition)
06797     InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
06798 
06799   // C++0x [temp.explicit]p2:
06800   //   If the explicit instantiation is for a member function, a member class
06801   //   or a static data member of a class template specialization, the name of
06802   //   the class template specialization in the qualified-id for the member
06803   //   name shall be a simple-template-id.
06804   //
06805   // C++98 has the same restriction, just worded differently.
06806   FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
06807   if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
06808       D.getCXXScopeSpec().isSet() &&
06809       !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
06810     Diag(D.getIdentifierLoc(),
06811          diag::ext_explicit_instantiation_without_qualified_id)
06812     << Specialization << D.getCXXScopeSpec().getRange();
06813 
06814   CheckExplicitInstantiationScope(*this,
06815                    FunTmpl? (NamedDecl *)FunTmpl
06816                           : Specialization->getInstantiatedFromMemberFunction(),
06817                                   D.getIdentifierLoc(),
06818                                   D.getCXXScopeSpec().isSet());
06819 
06820   // FIXME: Create some kind of ExplicitInstantiationDecl here.
06821   return (Decl*) 0;
06822 }
06823 
06824 TypeResult
06825 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
06826                         const CXXScopeSpec &SS, IdentifierInfo *Name,
06827                         SourceLocation TagLoc, SourceLocation NameLoc) {
06828   // This has to hold, because SS is expected to be defined.
06829   assert(Name && "Expected a name in a dependent tag");
06830 
06831   NestedNameSpecifier *NNS
06832     = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
06833   if (!NNS)
06834     return true;
06835 
06836   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
06837 
06838   if (TUK == TUK_Declaration || TUK == TUK_Definition) {
06839     Diag(NameLoc, diag::err_dependent_tag_decl)
06840       << (TUK == TUK_Definition) << Kind << SS.getRange();
06841     return true;
06842   }
06843 
06844   // Create the resulting type.
06845   ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
06846   QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
06847   
06848   // Create type-source location information for this type.
06849   TypeLocBuilder TLB;
06850   DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
06851   TL.setElaboratedKeywordLoc(TagLoc);
06852   TL.setQualifierLoc(SS.getWithLocInContext(Context));
06853   TL.setNameLoc(NameLoc);
06854   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
06855 }
06856 
06857 TypeResult
06858 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
06859                         const CXXScopeSpec &SS, const IdentifierInfo &II,
06860                         SourceLocation IdLoc) {
06861   if (SS.isInvalid())
06862     return true;
06863   
06864   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
06865     Diag(TypenameLoc,
06866          getLangOpts().CPlusPlus0x ?
06867            diag::warn_cxx98_compat_typename_outside_of_template :
06868            diag::ext_typename_outside_of_template)
06869       << FixItHint::CreateRemoval(TypenameLoc);
06870 
06871   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
06872   QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
06873                                  TypenameLoc, QualifierLoc, II, IdLoc);
06874   if (T.isNull())
06875     return true;
06876 
06877   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
06878   if (isa<DependentNameType>(T)) {
06879     DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
06880     TL.setElaboratedKeywordLoc(TypenameLoc);
06881     TL.setQualifierLoc(QualifierLoc);
06882     TL.setNameLoc(IdLoc);
06883   } else {
06884     ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
06885     TL.setElaboratedKeywordLoc(TypenameLoc);
06886     TL.setQualifierLoc(QualifierLoc);
06887     cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
06888   }
06889 
06890   return CreateParsedType(T, TSI);
06891 }
06892 
06893 TypeResult
06894 Sema::ActOnTypenameType(Scope *S,
06895                         SourceLocation TypenameLoc,
06896                         const CXXScopeSpec &SS,
06897                         SourceLocation TemplateKWLoc,
06898                         TemplateTy TemplateIn,
06899                         SourceLocation TemplateNameLoc,
06900                         SourceLocation LAngleLoc,
06901                         ASTTemplateArgsPtr TemplateArgsIn,
06902                         SourceLocation RAngleLoc) {
06903   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
06904     Diag(TypenameLoc,
06905          getLangOpts().CPlusPlus0x ?
06906            diag::warn_cxx98_compat_typename_outside_of_template :
06907            diag::ext_typename_outside_of_template)
06908       << FixItHint::CreateRemoval(TypenameLoc);
06909   
06910   // Translate the parser's template argument list in our AST format.
06911   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
06912   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
06913   
06914   TemplateName Template = TemplateIn.get();
06915   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
06916     // Construct a dependent template specialization type.
06917     assert(DTN && "dependent template has non-dependent name?");
06918     assert(DTN->getQualifier()
06919            == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
06920     QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
06921                                                           DTN->getQualifier(),
06922                                                           DTN->getIdentifier(),
06923                                                                 TemplateArgs);
06924     
06925     // Create source-location information for this type.
06926     TypeLocBuilder Builder;
06927     DependentTemplateSpecializationTypeLoc SpecTL 
06928     = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
06929     SpecTL.setElaboratedKeywordLoc(TypenameLoc);
06930     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
06931     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
06932     SpecTL.setTemplateNameLoc(TemplateNameLoc);
06933     SpecTL.setLAngleLoc(LAngleLoc);
06934     SpecTL.setRAngleLoc(RAngleLoc);
06935     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
06936       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
06937     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
06938   }
06939   
06940   QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
06941   if (T.isNull())
06942     return true;
06943   
06944   // Provide source-location information for the template specialization type.
06945   TypeLocBuilder Builder;
06946   TemplateSpecializationTypeLoc SpecTL
06947     = Builder.push<TemplateSpecializationTypeLoc>(T);
06948   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
06949   SpecTL.setTemplateNameLoc(TemplateNameLoc);
06950   SpecTL.setLAngleLoc(LAngleLoc);
06951   SpecTL.setRAngleLoc(RAngleLoc);
06952   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
06953     SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
06954   
06955   T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
06956   ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
06957   TL.setElaboratedKeywordLoc(TypenameLoc);
06958   TL.setQualifierLoc(SS.getWithLocInContext(Context));
06959   
06960   TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
06961   return CreateParsedType(T, TSI);
06962 }
06963 
06964 
06965 /// Determine whether this failed name lookup should be treated as being
06966 /// disabled by a usage of std::enable_if.
06967 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
06968                        SourceRange &CondRange) {
06969   // We must be looking for a ::type...
06970   if (!II.isStr("type"))
06971     return false;
06972 
06973   // ... within an explicitly-written template specialization...
06974   if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
06975     return false;
06976   TypeLoc EnableIfTy = NNS.getTypeLoc();
06977   TemplateSpecializationTypeLoc *EnableIfTSTLoc =
06978     dyn_cast<TemplateSpecializationTypeLoc>(&EnableIfTy);
06979   if (!EnableIfTSTLoc || EnableIfTSTLoc->getNumArgs() == 0)
06980     return false;
06981   const TemplateSpecializationType *EnableIfTST =
06982     cast<TemplateSpecializationType>(EnableIfTSTLoc->getTypePtr());
06983 
06984   // ... which names a complete class template declaration...
06985   const TemplateDecl *EnableIfDecl =
06986     EnableIfTST->getTemplateName().getAsTemplateDecl();
06987   if (!EnableIfDecl || EnableIfTST->isIncompleteType())
06988     return false;
06989 
06990   // ... called "enable_if".
06991   const IdentifierInfo *EnableIfII =
06992     EnableIfDecl->getDeclName().getAsIdentifierInfo();
06993   if (!EnableIfII || !EnableIfII->isStr("enable_if"))
06994     return false;
06995 
06996   // Assume the first template argument is the condition.
06997   CondRange = EnableIfTSTLoc->getArgLoc(0).getSourceRange();
06998   return true;
06999 }
07000 
07001 /// \brief Build the type that describes a C++ typename specifier,
07002 /// e.g., "typename T::type".
07003 QualType
07004 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword, 
07005                         SourceLocation KeywordLoc,
07006                         NestedNameSpecifierLoc QualifierLoc, 
07007                         const IdentifierInfo &II,
07008                         SourceLocation IILoc) {
07009   CXXScopeSpec SS;
07010   SS.Adopt(QualifierLoc);
07011 
07012   DeclContext *Ctx = computeDeclContext(SS);
07013   if (!Ctx) {
07014     // If the nested-name-specifier is dependent and couldn't be
07015     // resolved to a type, build a typename type.
07016     assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
07017     return Context.getDependentNameType(Keyword, 
07018                                         QualifierLoc.getNestedNameSpecifier(), 
07019                                         &II);
07020   }
07021 
07022   // If the nested-name-specifier refers to the current instantiation,
07023   // the "typename" keyword itself is superfluous. In C++03, the
07024   // program is actually ill-formed. However, DR 382 (in C++0x CD1)
07025   // allows such extraneous "typename" keywords, and we retroactively
07026   // apply this DR to C++03 code with only a warning. In any case we continue.
07027 
07028   if (RequireCompleteDeclContext(SS, Ctx))
07029     return QualType();
07030 
07031   DeclarationName Name(&II);
07032   LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
07033   LookupQualifiedName(Result, Ctx);
07034   unsigned DiagID = 0;
07035   Decl *Referenced = 0;
07036   switch (Result.getResultKind()) {
07037   case LookupResult::NotFound: {
07038     // If we're looking up 'type' within a template named 'enable_if', produce
07039     // a more specific diagnostic.
07040     SourceRange CondRange;
07041     if (isEnableIf(QualifierLoc, II, CondRange)) {
07042       Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
07043         << Ctx << CondRange;
07044       return QualType();
07045     }
07046 
07047     DiagID = diag::err_typename_nested_not_found;
07048     break;
07049   }
07050 
07051   case LookupResult::FoundUnresolvedValue: {
07052     // We found a using declaration that is a value. Most likely, the using
07053     // declaration itself is meant to have the 'typename' keyword.
07054     SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
07055                           IILoc);
07056     Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
07057       << Name << Ctx << FullRange;
07058     if (UnresolvedUsingValueDecl *Using
07059           = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
07060       SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
07061       Diag(Loc, diag::note_using_value_decl_missing_typename)
07062         << FixItHint::CreateInsertion(Loc, "typename ");
07063     }
07064   }
07065   // Fall through to create a dependent typename type, from which we can recover
07066   // better.
07067 
07068   case LookupResult::NotFoundInCurrentInstantiation:
07069     // Okay, it's a member of an unknown instantiation.
07070     return Context.getDependentNameType(Keyword, 
07071                                         QualifierLoc.getNestedNameSpecifier(), 
07072                                         &II);
07073 
07074   case LookupResult::Found:
07075     if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
07076       // We found a type. Build an ElaboratedType, since the
07077       // typename-specifier was just sugar.
07078       return Context.getElaboratedType(ETK_Typename, 
07079                                        QualifierLoc.getNestedNameSpecifier(),
07080                                        Context.getTypeDeclType(Type));
07081     }
07082 
07083     DiagID = diag::err_typename_nested_not_type;
07084     Referenced = Result.getFoundDecl();
07085     break;
07086 
07087   case LookupResult::FoundOverloaded:
07088     DiagID = diag::err_typename_nested_not_type;
07089     Referenced = *Result.begin();
07090     break;
07091 
07092   case LookupResult::Ambiguous:
07093     return QualType();
07094   }
07095 
07096   // If we get here, it's because name lookup did not find a
07097   // type. Emit an appropriate diagnostic and return an error.
07098   SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
07099                         IILoc);
07100   Diag(IILoc, DiagID) << FullRange << Name << Ctx;
07101   if (Referenced)
07102     Diag(Referenced->getLocation(), diag::note_typename_refers_here)
07103       << Name;
07104   return QualType();
07105 }
07106 
07107 namespace {
07108   // See Sema::RebuildTypeInCurrentInstantiation
07109   class CurrentInstantiationRebuilder
07110     : public TreeTransform<CurrentInstantiationRebuilder> {
07111     SourceLocation Loc;
07112     DeclarationName Entity;
07113 
07114   public:
07115     typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
07116 
07117     CurrentInstantiationRebuilder(Sema &SemaRef,
07118                                   SourceLocation Loc,
07119                                   DeclarationName Entity)
07120     : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
07121       Loc(Loc), Entity(Entity) { }
07122 
07123     /// \brief Determine whether the given type \p T has already been
07124     /// transformed.
07125     ///
07126     /// For the purposes of type reconstruction, a type has already been
07127     /// transformed if it is NULL or if it is not dependent.
07128     bool AlreadyTransformed(QualType T) {
07129       return T.isNull() || !T->isDependentType();
07130     }
07131 
07132     /// \brief Returns the location of the entity whose type is being
07133     /// rebuilt.
07134     SourceLocation getBaseLocation() { return Loc; }
07135 
07136     /// \brief Returns the name of the entity whose type is being rebuilt.
07137     DeclarationName getBaseEntity() { return Entity; }
07138 
07139     /// \brief Sets the "base" location and entity when that
07140     /// information is known based on another transformation.
07141     void setBase(SourceLocation Loc, DeclarationName Entity) {
07142       this->Loc = Loc;
07143       this->Entity = Entity;
07144     }
07145       
07146     ExprResult TransformLambdaExpr(LambdaExpr *E) {
07147       // Lambdas never need to be transformed.
07148       return E;
07149     }
07150   };
07151 }
07152 
07153 /// \brief Rebuilds a type within the context of the current instantiation.
07154 ///
07155 /// The type \p T is part of the type of an out-of-line member definition of
07156 /// a class template (or class template partial specialization) that was parsed
07157 /// and constructed before we entered the scope of the class template (or
07158 /// partial specialization thereof). This routine will rebuild that type now
07159 /// that we have entered the declarator's scope, which may produce different
07160 /// canonical types, e.g.,
07161 ///
07162 /// \code
07163 /// template<typename T>
07164 /// struct X {
07165 ///   typedef T* pointer;
07166 ///   pointer data();
07167 /// };
07168 ///
07169 /// template<typename T>
07170 /// typename X<T>::pointer X<T>::data() { ... }
07171 /// \endcode
07172 ///
07173 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
07174 /// since we do not know that we can look into X<T> when we parsed the type.
07175 /// This function will rebuild the type, performing the lookup of "pointer"
07176 /// in X<T> and returning an ElaboratedType whose canonical type is the same
07177 /// as the canonical type of T*, allowing the return types of the out-of-line
07178 /// definition and the declaration to match.
07179 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
07180                                                         SourceLocation Loc,
07181                                                         DeclarationName Name) {
07182   if (!T || !T->getType()->isDependentType())
07183     return T;
07184 
07185   CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
07186   return Rebuilder.TransformType(T);
07187 }
07188 
07189 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
07190   CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
07191                                           DeclarationName());
07192   return Rebuilder.TransformExpr(E);
07193 }
07194 
07195 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
07196   if (SS.isInvalid()) 
07197     return true;
07198 
07199   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
07200   CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
07201                                           DeclarationName());
07202   NestedNameSpecifierLoc Rebuilt 
07203     = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
07204   if (!Rebuilt) 
07205     return true;
07206 
07207   SS.Adopt(Rebuilt);
07208   return false;
07209 }
07210 
07211 /// \brief Rebuild the template parameters now that we know we're in a current
07212 /// instantiation.
07213 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
07214                                                TemplateParameterList *Params) {
07215   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
07216     Decl *Param = Params->getParam(I);
07217     
07218     // There is nothing to rebuild in a type parameter.
07219     if (isa<TemplateTypeParmDecl>(Param))
07220       continue;
07221     
07222     // Rebuild the template parameter list of a template template parameter.
07223     if (TemplateTemplateParmDecl *TTP 
07224         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
07225       if (RebuildTemplateParamsInCurrentInstantiation(
07226             TTP->getTemplateParameters()))
07227         return true;
07228       
07229       continue;
07230     }
07231     
07232     // Rebuild the type of a non-type template parameter.
07233     NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
07234     TypeSourceInfo *NewTSI 
07235       = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(), 
07236                                           NTTP->getLocation(), 
07237                                           NTTP->getDeclName());
07238     if (!NewTSI)
07239       return true;
07240     
07241     if (NewTSI != NTTP->getTypeSourceInfo()) {
07242       NTTP->setTypeSourceInfo(NewTSI);
07243       NTTP->setType(NewTSI->getType());
07244     }
07245   }
07246   
07247   return false;
07248 }
07249 
07250 /// \brief Produces a formatted string that describes the binding of
07251 /// template parameters to template arguments.
07252 std::string
07253 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
07254                                       const TemplateArgumentList &Args) {
07255   return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
07256 }
07257 
07258 std::string
07259 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
07260                                       const TemplateArgument *Args,
07261                                       unsigned NumArgs) {
07262   SmallString<128> Str;
07263   llvm::raw_svector_ostream Out(Str);
07264 
07265   if (!Params || Params->size() == 0 || NumArgs == 0)
07266     return std::string();
07267 
07268   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
07269     if (I >= NumArgs)
07270       break;
07271 
07272     if (I == 0)
07273       Out << "[with ";
07274     else
07275       Out << ", ";
07276 
07277     if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
07278       Out << Id->getName();
07279     } else {
07280       Out << '$' << I;
07281     }
07282 
07283     Out << " = ";
07284     Args[I].print(getPrintingPolicy(), Out);
07285   }
07286 
07287   Out << ']';
07288   return Out.str();
07289 }
07290 
07291 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag) {
07292   if (!FD)
07293     return;
07294   FD->setLateTemplateParsed(Flag);
07295 } 
07296 
07297 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
07298   DeclContext *DC = CurContext;
07299 
07300   while (DC) {
07301     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
07302       const FunctionDecl *FD = RD->isLocalClass();
07303       return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
07304     } else if (DC->isTranslationUnit() || DC->isNamespace())
07305       return false;
07306 
07307     DC = DC->getParent();
07308   }
07309   return false;
07310 }