SemaTemplate.cpp revision 45f965581935791a018df829a14dff53c1dd8f47
14b562cf889bc59e1914dd2c5d9fbd7e7bfa1ad77Argyrios Kyrtzidis//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
24b562cf889bc59e1914dd2c5d9fbd7e7bfa1ad77Argyrios Kyrtzidis//
34b562cf889bc59e1914dd2c5d9fbd7e7bfa1ad77Argyrios Kyrtzidis//                     The LLVM Compiler Infrastructure
44b562cf889bc59e1914dd2c5d9fbd7e7bfa1ad77Argyrios Kyrtzidis//
54b562cf889bc59e1914dd2c5d9fbd7e7bfa1ad77Argyrios Kyrtzidis// This file is distributed under the University of Illinois Open Source
64b562cf889bc59e1914dd2c5d9fbd7e7bfa1ad77Argyrios Kyrtzidis// License. See LICENSE.TXT for details.
74b562cf889bc59e1914dd2c5d9fbd7e7bfa1ad77Argyrios Kyrtzidis//===----------------------------------------------------------------------===/
84b562cf889bc59e1914dd2c5d9fbd7e7bfa1ad77Argyrios Kyrtzidis//
94b562cf889bc59e1914dd2c5d9fbd7e7bfa1ad77Argyrios Kyrtzidis//  This file implements semantic analysis for C++ templates.
104b562cf889bc59e1914dd2c5d9fbd7e7bfa1ad77Argyrios Kyrtzidis//===----------------------------------------------------------------------===/
114b562cf889bc59e1914dd2c5d9fbd7e7bfa1ad77Argyrios Kyrtzidis
124b562cf889bc59e1914dd2c5d9fbd7e7bfa1ad77Argyrios Kyrtzidis#include "Sema.h"
134b562cf889bc59e1914dd2c5d9fbd7e7bfa1ad77Argyrios Kyrtzidis#include "TreeTransform.h"
140853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis#include "clang/AST/ASTContext.h"
150853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis#include "clang/AST/Expr.h"
160853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis#include "clang/AST/ExprCXX.h"
17eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor#include "clang/AST/DeclTemplate.h"
1805a07605322dfef2b017781042043a261c5a89cdSebastian Redl#include "clang/Parse/DeclSpec.h"
19914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas Gregor#include "clang/Basic/LangOptions.h"
200a2c5e256abb4dc031c21fe4dc92c4f3afe9947cJohn McCall#include "llvm/Support/Compiler.h"
216aa52ec6b969faabf3764baf79d89810b8249a7eDouglas Gregor
224ae8f298b1ea51b4c2234f9148e2e4349c9bdd23Douglas Gregorusing namespace clang;
2331b87d8006d4863dd9b17e515ac720941efc38e3Daniel Dunbar
24eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor/// \brief Determine whether the declaration found is acceptable as the name
25389db16c63eec6ecfa9b235155252d8da766e94eArgyrios Kyrtzidis/// of a template and, if so, return that template declaration. Otherwise,
2687c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor/// returns NULL.
2728019772db70d4547be05a042eb950bc910f134fDouglas Gregorstatic NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
280853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis  if (!D)
29a88084b78fd4ca5d3d858c14b02414f8cc399f02Douglas Gregor    return 0;
30cc5888d833caf90ebda37f24da40d2cd06b4d820Douglas Gregor
3103013fa9a0bf1ef4b907f5fec006c8f4000fdd21Michael J. Spencer  if (isa<TemplateDecl>(D))
32788f5a1242c04762f91eaa7565c07b9865846d88Douglas Gregor    return D;
330853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis
34f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
35f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar    // C++ [temp.local]p1:
364db64a461cb3442934afe43c83ed3f17f7c11c1dDouglas Gregor    //   Like normal (non-template) classes, class templates have an
37cc5888d833caf90ebda37f24da40d2cd06b4d820Douglas Gregor    //   injected-class-name (Clause 9). The injected-class-name
384db64a461cb3442934afe43c83ed3f17f7c11c1dDouglas Gregor    //   can be used with or without a template-argument-list. When
394db64a461cb3442934afe43c83ed3f17f7c11c1dDouglas Gregor    //   it is used without a template-argument-list, it is
404db64a461cb3442934afe43c83ed3f17f7c11c1dDouglas Gregor    //   equivalent to the injected-class-name followed by the
414db64a461cb3442934afe43c83ed3f17f7c11c1dDouglas Gregor    //   template-parameters of the class template enclosed in
420853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis    //   <>. When it is used with a template-argument-list, it
430853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis    //   refers to the specified class template specialization,
44521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar    //   which could be the current specialization or another
45f62d43d2afe1960755a1b5813cae1e5983bcac1bDouglas Gregor    //   specialization.
461abc6bca3d7fb0e7b1e40fbcad6cfb5e10594548Douglas Gregor    if (Record->isInjectedClassName()) {
47521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar      Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
48521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar      if (Record->getDescribedClassTemplate())
49d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie        return Record->getDescribedClassTemplate();
50521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar
51521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar      if (ClassTemplateSpecializationDecl *Spec
52521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar            = dyn_cast<ClassTemplateSpecializationDecl>(Record))
53521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar        return Spec->getSpecializedTemplate();
54521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar    }
55521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar
56d808bd2978bd4ac95a92b309b038452b533fd7a0Argyrios Kyrtzidis    return 0;
570853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis  }
58f96b524306ccfa623235d375deee79637bd38f29Steve Naroff
5944c181aec37789f25f6c15543c164416f72e562aDouglas Gregor  OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
6048601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor  if (!Ovl)
6148601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor    return 0;
6248601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor
6348601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor  for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
6448601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor                                              FEnd = Ovl->function_end();
6548601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor       F != FEnd; ++F) {
6648601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor    if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
6748601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor      // We've found a function template. Determine whether there are
683c7f4134603d04b44f997b43c0a9def270f25386Sebastian Redl      // any other function templates we need to bundle together in an
690853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis      // OverloadedFunctionDecl
706aa52ec6b969faabf3764baf79d89810b8249a7eDouglas Gregor      for (++F; F != FEnd; ++F) {
71788f5a1242c04762f91eaa7565c07b9865846d88Douglas Gregor        if (isa<FunctionTemplateDecl>(*F))
72d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie          break;
73d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie      }
74d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie
75d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie      if (F != FEnd) {
76d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie        // Build an overloaded function decl containing only the
77d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie        // function templates in Ovl.
78d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie        OverloadedFunctionDecl *OvlTemplate
79389db16c63eec6ecfa9b235155252d8da766e94eArgyrios Kyrtzidis          = OverloadedFunctionDecl::Create(Context,
80389db16c63eec6ecfa9b235155252d8da766e94eArgyrios Kyrtzidis                                           Ovl->getDeclContext(),
81389db16c63eec6ecfa9b235155252d8da766e94eArgyrios Kyrtzidis                                           Ovl->getDeclName());
82914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas Gregor        OvlTemplate->addOverload(FuncTmpl);
83914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas Gregor        OvlTemplate->addOverload(*F);
84914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas Gregor        for (++F; F != FEnd; ++F) {
85914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas Gregor          if (isa<FunctionTemplateDecl>(*F))
86914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas Gregor            OvlTemplate->addOverload(*F);
87914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas Gregor        }
88914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas Gregor
89914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas Gregor        return OvlTemplate;
90807b06157a1a5c050520fc194d32f16d22d423a8Daniel Dunbar      }
91807b06157a1a5c050520fc194d32f16d22d423a8Daniel Dunbar
924f32786ac45210143654390177105eb749b614e9Ted Kremenek      return FuncTmpl;
93914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas Gregor    }
941aa27307c462baaa9e5fda14ff6797dd39fe8b84Douglas Gregor  }
951aa27307c462baaa9e5fda14ff6797dd39fe8b84Douglas Gregor
961aa27307c462baaa9e5fda14ff6797dd39fe8b84Douglas Gregor  return 0;
971aa27307c462baaa9e5fda14ff6797dd39fe8b84Douglas Gregor}
981aa27307c462baaa9e5fda14ff6797dd39fe8b84Douglas Gregor
991aa27307c462baaa9e5fda14ff6797dd39fe8b84Douglas GregorTemplateNameKind Sema::isTemplateName(Scope *S,
1001aa27307c462baaa9e5fda14ff6797dd39fe8b84Douglas Gregor                                      const IdentifierInfo &II,
1017d1d49d2971b20a97b3c2a301470b9eaaa130137Douglas Gregor                                      SourceLocation IdLoc,
1027d1d49d2971b20a97b3c2a301470b9eaaa130137Douglas Gregor                                      const CXXScopeSpec *SS,
1037d1d49d2971b20a97b3c2a301470b9eaaa130137Douglas Gregor                                      TypeTy *ObjectTypePtr,
1047d1d49d2971b20a97b3c2a301470b9eaaa130137Douglas Gregor                                      bool EnteringContext,
105c7822dbf3c01a2a5f837cff82ba7889ea755dacaDaniel Dunbar                                      TemplateTy &TemplateResult) {
106abc563f554951259bbe0315055cad92ee14d87e4Douglas Gregor  // Determine where to perform name lookup
107abc563f554951259bbe0315055cad92ee14d87e4Douglas Gregor  DeclContext *LookupCtx = 0;
108e47be3e9682e82da15059006f43c7f3c021e4fffDouglas Gregor  bool isDependent = false;
109df95a13ec73d2cdaea79555cb412d767f4963120Douglas Gregor  if (ObjectTypePtr) {
110c7822dbf3c01a2a5f837cff82ba7889ea755dacaDaniel Dunbar    // This nested-name-specifier occurs in a member access expression, e.g.,
111c7822dbf3c01a2a5f837cff82ba7889ea755dacaDaniel Dunbar    // x->B::f, and we are looking into the type of the object.
112467dc88512b4ba4bb16e274ea3771dc1415d31daDouglas Gregor    assert((!SS || !SS->isSet()) &&
113467dc88512b4ba4bb16e274ea3771dc1415d31daDouglas Gregor           "ObjectType and scope specifier cannot coexist");
114df95a13ec73d2cdaea79555cb412d767f4963120Douglas Gregor    QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
115213f18b3d654de7d1c7cf4a329ea9d3db1c50b6aDouglas Gregor    LookupCtx = computeDeclContext(ObjectType);
116213f18b3d654de7d1c7cf4a329ea9d3db1c50b6aDouglas Gregor    isDependent = ObjectType->isDependentType();
11715727ddb11405c45372150b5bfb07dbfa4c9960bArgyrios Kyrtzidis  } else if (SS && SS->isSet()) {
11815727ddb11405c45372150b5bfb07dbfa4c9960bArgyrios Kyrtzidis    // This nested-name-specifier occurs after another nested-name-specifier,
11915727ddb11405c45372150b5bfb07dbfa4c9960bArgyrios Kyrtzidis    // so long into the context associated with the prior nested-name-specifier.
120213f18b3d654de7d1c7cf4a329ea9d3db1c50b6aDouglas Gregor
121f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar    LookupCtx = computeDeclContext(*SS, EnteringContext);
122f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar    isDependent = isDependentScopeSpecifier(*SS);
123f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar  }
124f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar
125f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar  LookupResult Found;
126f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar  bool ObjectTypeSearchedInScope = false;
127f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar  if (LookupCtx) {
128f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar    // Perform "qualified" name lookup into the declaration context we
129332cb9be88fd2d1b294a2fbc299c354e93be673cArgyrios Kyrtzidis    // computed, which is either the type of the base of a member access
130332cb9be88fd2d1b294a2fbc299c354e93be673cArgyrios Kyrtzidis    // expression or the declaration context associated with a prior
131332cb9be88fd2d1b294a2fbc299c354e93be673cArgyrios Kyrtzidis    // nested-name-specifier.
132332cb9be88fd2d1b294a2fbc299c354e93be673cArgyrios Kyrtzidis
133332cb9be88fd2d1b294a2fbc299c354e93be673cArgyrios Kyrtzidis    // The declaration context must be complete.
134332cb9be88fd2d1b294a2fbc299c354e93be673cArgyrios Kyrtzidis    if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
135332cb9be88fd2d1b294a2fbc299c354e93be673cArgyrios Kyrtzidis      return TNK_Non_template;
136332cb9be88fd2d1b294a2fbc299c354e93be673cArgyrios Kyrtzidis
13789d9980bbc2e4a4ac86673e6ec16fb9f5babb63bDouglas Gregor    Found = LookupQualifiedName(LookupCtx, &II, LookupOrdinaryName);
13868d40e2d16b9fadba386853d6bbb60089291fdc5Daniel Dunbar
13968d40e2d16b9fadba386853d6bbb60089291fdc5Daniel Dunbar    if (ObjectTypePtr && Found.getKind() == LookupResult::NotFound) {
14068d40e2d16b9fadba386853d6bbb60089291fdc5Daniel Dunbar      // C++ [basic.lookup.classref]p1:
141f96b524306ccfa623235d375deee79637bd38f29Steve Naroff      //   In a class member access expression (5.2.5), if the . or -> token is
142f96b524306ccfa623235d375deee79637bd38f29Steve Naroff      //   immediately followed by an identifier followed by a <, the
143f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar      //   identifier must be looked up to determine whether the < is the
144f62d43d2afe1960755a1b5813cae1e5983bcac1bDouglas Gregor      //   beginning of a template argument list (14.2) or a less-than operator.
145686775deca8b8685eb90801495880e3abdd844c2Chris Lattner      //   The identifier is first looked up in the class of the object
146f62d43d2afe1960755a1b5813cae1e5983bcac1bDouglas Gregor      //   expression. If the identifier is not found, it is then looked up in
147a88084b78fd4ca5d3d858c14b02414f8cc399f02Douglas Gregor      //   the context of the entire postfix-expression and shall name a class
148a88084b78fd4ca5d3d858c14b02414f8cc399f02Douglas Gregor      //   or function template.
149686775deca8b8685eb90801495880e3abdd844c2Chris Lattner      //
150a88084b78fd4ca5d3d858c14b02414f8cc399f02Douglas Gregor      // FIXME: When we're instantiating a template, do we actually have to
1514cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor      // look in the scope of the template? Seems fishy...
1524cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor      Found = LookupName(S, &II, LookupOrdinaryName);
1534cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor      ObjectTypeSearchedInScope = true;
1544cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor    }
1554cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor  } else if (isDependent) {
1564cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor    // We cannot look into a dependent object type or
1574cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor    return TNK_Non_template;
158eababfbddb74d186f78783a9731a78ad371c9800Douglas Gregor  } else {
159eababfbddb74d186f78783a9731a78ad371c9800Douglas Gregor    // Perform unqualified name lookup in the current scope.
160eababfbddb74d186f78783a9731a78ad371c9800Douglas Gregor    Found = LookupName(S, &II, LookupOrdinaryName);
161eababfbddb74d186f78783a9731a78ad371c9800Douglas Gregor  }
162eababfbddb74d186f78783a9731a78ad371c9800Douglas Gregor
163eababfbddb74d186f78783a9731a78ad371c9800Douglas Gregor  // FIXME: Cope with ambiguous name-lookup results.
164eababfbddb74d186f78783a9731a78ad371c9800Douglas Gregor  assert(!Found.isAmbiguous() &&
165eababfbddb74d186f78783a9731a78ad371c9800Douglas Gregor         "Cannot handle template name-lookup ambiguities");
166eababfbddb74d186f78783a9731a78ad371c9800Douglas Gregor
167eababfbddb74d186f78783a9731a78ad371c9800Douglas Gregor  NamedDecl *Template = isAcceptableTemplateName(Context, Found);
1681872b3153a388b3a548c9f699cbc348128059be9Ted Kremenek  if (!Template)
169ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis    return TNK_Non_template;
170507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis
171507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis  if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
172507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis    // C++ [basic.lookup.classref]p1:
173507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis    //   [...] If the lookup in the class of the object expression finds a
174507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis    //   template, the name is also looked up in the context of the entire
175507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis    //   postfix-expression and [...]
176507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis    //
177507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis    LookupResult FoundOuter = LookupName(S, &II, LookupOrdinaryName);
178507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis    // FIXME: Handle ambiguities in this lookup better
179507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis    NamedDecl *OuterTemplate = isAcceptableTemplateName(Context, FoundOuter);
180507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis
181507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis    if (!OuterTemplate) {
182507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis      //   - if the name is not found, the name found in the class of the
183507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis      //     object expression is used, otherwise
184507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis    } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
185507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis      //   - if the name is found in the context of the entire
186507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis      //     postfix-expression and does not name a class template, the name
187507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis      //     found in the class of the object expression is used, otherwise
188507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis    } else {
189507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis      //   - if the name found is a class template, it must refer to the same
190507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis      //     entity as the one found in the class of the object expression,
191507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis      //     otherwise the program is ill-formed.
192507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis      if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
193507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis        Diag(IdLoc, diag::err_nested_name_member_ref_lookup_ambiguous)
194507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis          << &II;
195507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis        Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
196507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis          << QualType::getFromOpaquePtr(ObjectTypePtr);
197507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis        Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
198ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis
199ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis        // Recover by taking the template that we found in the object
200ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis        // expression's type.
201ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis      }
202ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis    }
203507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis  }
204507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis
205507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis  if (SS && SS->isSet() && !SS->isInvalid()) {
206507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis    NestedNameSpecifier *Qualifier
207ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis      = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
208ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis    if (OverloadedFunctionDecl *Ovl
209ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis          = dyn_cast<OverloadedFunctionDecl>(Template))
210ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis      TemplateResult
211ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis        = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
212ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis                                                            Ovl));
213175c4a9aa61f4449f27b729737e4438684ac6d92Douglas Gregor    else
214175c4a9aa61f4449f27b729737e4438684ac6d92Douglas Gregor      TemplateResult
215507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis        = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
216175c4a9aa61f4449f27b729737e4438684ac6d92Douglas Gregor                                                 cast<TemplateDecl>(Template)));
217f4f6c9db68465b886ec2e596feaa6ecc782395a4Douglas Gregor  } else if (OverloadedFunctionDecl *Ovl
218f4f6c9db68465b886ec2e596feaa6ecc782395a4Douglas Gregor               = dyn_cast<OverloadedFunctionDecl>(Template)) {
219f4f6c9db68465b886ec2e596feaa6ecc782395a4Douglas Gregor    TemplateResult = TemplateTy::make(TemplateName(Ovl));
220f4f6c9db68465b886ec2e596feaa6ecc782395a4Douglas Gregor  } else {
221f4f6c9db68465b886ec2e596feaa6ecc782395a4Douglas Gregor    TemplateResult = TemplateTy::make(
222f4f6c9db68465b886ec2e596feaa6ecc782395a4Douglas Gregor                                  TemplateName(cast<TemplateDecl>(Template)));
223175c4a9aa61f4449f27b729737e4438684ac6d92Douglas Gregor  }
224175c4a9aa61f4449f27b729737e4438684ac6d92Douglas Gregor
225175c4a9aa61f4449f27b729737e4438684ac6d92Douglas Gregor  if (isa<ClassTemplateDecl>(Template) ||
226cc5888d833caf90ebda37f24da40d2cd06b4d820Douglas Gregor      isa<TemplateTemplateParmDecl>(Template))
227cc5888d833caf90ebda37f24da40d2cd06b4d820Douglas Gregor    return TNK_Type_template;
228cc5888d833caf90ebda37f24da40d2cd06b4d820Douglas Gregor
229cc5888d833caf90ebda37f24da40d2cd06b4d820Douglas Gregor  assert((isa<FunctionTemplateDecl>(Template) ||
230cc5888d833caf90ebda37f24da40d2cd06b4d820Douglas Gregor          isa<OverloadedFunctionDecl>(Template)) &&
231cc5888d833caf90ebda37f24da40d2cd06b4d820Douglas Gregor         "Unhandled template kind in Sema::isTemplateName");
232cc5888d833caf90ebda37f24da40d2cd06b4d820Douglas Gregor  return TNK_Function_template;
233cc5888d833caf90ebda37f24da40d2cd06b4d820Douglas Gregor}
23428233428da1ebec20c893d6297ae3191318940ddDouglas Gregor
23528233428da1ebec20c893d6297ae3191318940ddDouglas Gregor/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
23628233428da1ebec20c893d6297ae3191318940ddDouglas Gregor/// that the template parameter 'PrevDecl' is being shadowed by a new
23728233428da1ebec20c893d6297ae3191318940ddDouglas Gregor/// declaration at location Loc. Returns true to indicate that this is
238c0659ec614c428c7d15746fcad15d50a2703751dDouglas Gregor/// an error, and false otherwise.
239671947b18dba342f9aba022ee992babef325a833Douglas Gregorbool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
240671947b18dba342f9aba022ee992babef325a833Douglas Gregor  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
241671947b18dba342f9aba022ee992babef325a833Douglas Gregor
242671947b18dba342f9aba022ee992babef325a833Douglas Gregor  // Microsoft Visual C++ permits template parameters to be shadowed.
243671947b18dba342f9aba022ee992babef325a833Douglas Gregor  if (getLangOptions().Microsoft)
244c0659ec614c428c7d15746fcad15d50a2703751dDouglas Gregor    return false;
245c0659ec614c428c7d15746fcad15d50a2703751dDouglas Gregor
246d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  // C++ [temp.local]p4:
247d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  //   A template-parameter shall not be redeclared within its
248c0659ec614c428c7d15746fcad15d50a2703751dDouglas Gregor  //   scope (including nested scopes).
249c0659ec614c428c7d15746fcad15d50a2703751dDouglas Gregor  Diag(Loc, diag::err_template_param_shadow)
250c0659ec614c428c7d15746fcad15d50a2703751dDouglas Gregor    << cast<NamedDecl>(PrevDecl)->getDeclName();
251c0659ec614c428c7d15746fcad15d50a2703751dDouglas Gregor  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
2523c7f4134603d04b44f997b43c0a9def270f25386Sebastian Redl  return true;
253eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor}
2548538e8d43a3a9bd439c987c0de37bcbf035dd391Sebastian Redl
25589d9980bbc2e4a4ac86673e6ec16fb9f5babb63bDouglas Gregor/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
25687c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor/// the parameter D to reference the templated declaration and return a pointer
25787c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor/// to the template declaration. Otherwise, do nothing to D and return null.
25887c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas GregorTemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
259ba7537febdf1bc1cc617e1f1746f2644feba6274Chandler Carruth  if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
260dca8ee8b7bc86076916a3a80f553f7a4e98c14afDouglas Gregor    D = DeclPtrTy::make(Temp->getTemplatedDecl());
261ba7537febdf1bc1cc617e1f1746f2644feba6274Chandler Carruth    return Temp;
2623e3cd93b2fd9644e970c389e715c13883faf68b6Douglas Gregor  }
2633e3cd93b2fd9644e970c389e715c13883faf68b6Douglas Gregor  return 0;
2643e3cd93b2fd9644e970c389e715c13883faf68b6Douglas Gregor}
2653e3cd93b2fd9644e970c389e715c13883faf68b6Douglas Gregor
266d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie/// ActOnTypeParameter - Called when a C++ template type parameter
2670b53cf834346d78985aaa9e7300445a39c245614Douglas Gregor/// (e.g., "typename T") has been parsed. Typename specifies whether
268e47be3e9682e82da15059006f43c7f3c021e4fffDouglas Gregor/// the keyword "typename" was used to declare the type parameter
269e47be3e9682e82da15059006f43c7f3c021e4fffDouglas Gregor/// (otherwise, "class" was used), and KeyLoc is the location of the
270686775deca8b8685eb90801495880e3abdd844c2Chris Lattner/// "class" or "typename" keyword. ParamName is the name of the
271f62d43d2afe1960755a1b5813cae1e5983bcac1bDouglas Gregor/// parameter (NULL indicates an unnamed template parameter) and
272686775deca8b8685eb90801495880e3abdd844c2Chris Lattner/// ParamName is the location of the parameter name (if any).
273686775deca8b8685eb90801495880e3abdd844c2Chris Lattner/// If the type parameter has a default argument, it will be added
274f62d43d2afe1960755a1b5813cae1e5983bcac1bDouglas Gregor/// later via ActOnTypeParameterDefault.
275332cb9be88fd2d1b294a2fbc299c354e93be673cArgyrios KyrtzidisSema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
276332cb9be88fd2d1b294a2fbc299c354e93be673cArgyrios Kyrtzidis                                         SourceLocation EllipsisLoc,
27787c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor                                         SourceLocation KeyLoc,
27887c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor                                         IdentifierInfo *ParamName,
27987c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor                                         SourceLocation ParamNameLoc,
28087c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor                                         unsigned Depth, unsigned Position) {
28187c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  assert(S->isTemplateParamScope() &&
28287c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor	 "Template type parameter not in template parameter scope!");
28387c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  bool Invalid = false;
28487c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor
28587c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  if (ParamName) {
28687c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
28787c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor    if (PrevDecl && PrevDecl->isTemplateParameter())
28887c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor      Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
28987c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor							   PrevDecl);
29087c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  }
29187c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor
29287c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  SourceLocation Loc = ParamNameLoc;
29387c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  if (!ParamName)
29487c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor    Loc = KeyLoc;
29587c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor
29687c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  TemplateTypeParmDecl *Param
29787c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor    = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
29887c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor                                   Depth, Position, ParamName, Typename,
29987c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor                                   Ellipsis);
30087c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  if (Invalid)
3011827e10051638770ad9ccf3e285caf95f995afd1Douglas Gregor    Param->setInvalidDecl();
30258ddb60f409125eda5436c4a1f070f7fa4744295Douglas Gregor
30358ddb60f409125eda5436c4a1f070f7fa4744295Douglas Gregor  if (ParamName) {
30458ddb60f409125eda5436c4a1f070f7fa4744295Douglas Gregor    // Add the template parameter into the current scope.
3051827e10051638770ad9ccf3e285caf95f995afd1Douglas Gregor    S->AddDecl(DeclPtrTy::make(Param));
3061827e10051638770ad9ccf3e285caf95f995afd1Douglas Gregor    IdResolver.AddDecl(Param);
307f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor  }
308f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor
309f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor  return DeclPtrTy::make(Param);
310f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor}
311f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor
312f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor/// ActOnTypeParameterDefault - Adds a default argument (the type
313f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor/// Default) to the given template type parameter (TypeParam).
314f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregorvoid Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
31587c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor                                     SourceLocation EqualLoc,
31687c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor                                     SourceLocation DefaultLoc,
317f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor                                     TypeTy *DefaultT) {
318f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor  TemplateTypeParmDecl *Parm
319f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor    = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
320f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor  // FIXME: Preserve type source info.
321f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor  QualType Default = GetTypeFromParser(DefaultT);
322f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor
32348601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor  // C++0x [temp.param]p9:
32448601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor  // A default template-argument may be specified for any kind of
32548601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor  // template-parameter that is not a template parameter pack.
32648601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor  if (Parm->isParameterPack()) {
32748601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor    Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
32848601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor    return;
3298fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  }
3308fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor
3318fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  // C++ [temp.param]p14:
3328fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  //   A template-parameter shall not be used in its own default argument.
3338fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  // FIXME: Implement this check! Needs a recursive walk over the types.
3348fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor
3358fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  // Check the template argument itself.
3368fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor  if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
3378fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor    Parm->setInvalidDecl();
3388fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor    return;
33987c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  }
340218937c13ef5b0625a70aad41ca7a92da9278bd2Douglas Gregor
34148601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor  Parm->setDefaultArgument(Default, DefaultLoc, false);
34248601b32321496b07a18fb6631f8563275d8c5fbDouglas Gregor}
3438fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor
3448fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor/// \brief Check that the type of a non-type template parameter is
3458fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor/// well-formed.
3468fa0a80b4482ad94e82c4a19e23de17fd69140b5Douglas Gregor///
347218937c13ef5b0625a70aad41ca7a92da9278bd2Douglas Gregor/// \returns the (possibly-promoted) parameter type if valid;
34887c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor/// otherwise, produces a diagnostic and returns a NULL type.
34987c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas GregorQualType
35087c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas GregorSema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
351f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor  // C++ [temp.param]p4:
352f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor  //
353f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor  // A non-type template-parameter shall have one of the following
354f5586f6b311c98e1022a8fe0609053849b70d323Douglas Gregor  // (optionally cv-qualified) types:
3559b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor  //
3569b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor  //       -- integral or enumeration type,
357727d93ef49e18147149354fadd10e86b13bc4ab0Douglas Gregor  if (T->isIntegralType() || T->isEnumeralType() ||
3589b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor      //   -- pointer to object or pointer to function,
3599b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor      (T->isPointerType() &&
3609b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor       (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
361727d93ef49e18147149354fadd10e86b13bc4ab0Douglas Gregor        T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
3629b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor      //   -- reference to object or reference to function,
3639b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor      T->isReferenceType() ||
364727d93ef49e18147149354fadd10e86b13bc4ab0Douglas Gregor      //   -- pointer to member.
3659b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor      T->isMemberPointerType() ||
3669b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor      // If T is a dependent type, we can't do the check now, so we
3679b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor      // assume that it is well-formed.
368ea94bbc4769697143e717df9b0310f874102b6c1Daniel Dunbar      T->isDependentType())
3699b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor    return T;
3709b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor  // C++ [temp.param]p8:
3719b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor  //
3729b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor  //   A non-type template-parameter of type "array of T" or
373ea94bbc4769697143e717df9b0310f874102b6c1Daniel Dunbar  //   "function returning T" is adjusted to be of type "pointer to
374ea94bbc4769697143e717df9b0310f874102b6c1Daniel Dunbar  //   T" or "pointer to function returning T", respectively.
375ea94bbc4769697143e717df9b0310f874102b6c1Daniel Dunbar  else if (T->isArrayType())
376ea94bbc4769697143e717df9b0310f874102b6c1Daniel Dunbar    // FIXME: Keep the type prior to promotion?
377c4421e966d77a18f815284175b3fcbb46f36fa39Douglas Gregor    return Context.getArrayDecayedType(T);
378c4421e966d77a18f815284175b3fcbb46f36fa39Douglas Gregor  else if (T->isFunctionType())
37987c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor    // FIXME: Keep the type prior to promotion?
38087c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor    return Context.getPointerType(T);
38187c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor
38287c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  Diag(Loc, diag::err_template_nontype_parm_bad_type)
38387c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor    << T;
38431b87d8006d4863dd9b17e515ac720941efc38e3Daniel Dunbar
38531b87d8006d4863dd9b17e515ac720941efc38e3Daniel Dunbar  return QualType();
386bdf6062bc10aa3b73b16402b440b8073310acd06Douglas Gregor}
3873687e9d3a5dbfa9963af02a49a2b139d91310813Douglas Gregor
3888b96253907c47141af0b7b2a44a368748d006a87Douglas Gregor/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
389abc563f554951259bbe0315055cad92ee14d87e4Douglas Gregor/// template parameter (e.g., "int Size" in "template<int Size>
390754f3490c5b0f5d83361f001bc87944f23644abbDouglas Gregor/// class Array") has been parsed. S is the current scope and D is
391175c4a9aa61f4449f27b729737e4438684ac6d92Douglas Gregor/// the parsed declarator.
392f4f6c9db68465b886ec2e596feaa6ecc782395a4Douglas GregorSema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
393df95a13ec73d2cdaea79555cb412d767f4963120Douglas Gregor                                                    unsigned Depth,
394df95a13ec73d2cdaea79555cb412d767f4963120Douglas Gregor                                                    unsigned Position) {
395175c4a9aa61f4449f27b729737e4438684ac6d92Douglas Gregor  DeclaratorInfo *DInfo = 0;
396df95a13ec73d2cdaea79555cb412d767f4963120Douglas Gregor  QualType T = GetTypeForDeclarator(D, S, &DInfo);
39701b6e31a62e2265849f4388b9be6be0a5d13348dDouglas Gregor
398df95a13ec73d2cdaea79555cb412d767f4963120Douglas Gregor  assert(S->isTemplateParamScope() &&
399df95a13ec73d2cdaea79555cb412d767f4963120Douglas Gregor         "Non-type template parameter not in template parameter scope!");
400eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor  bool Invalid = false;
40189d9980bbc2e4a4ac86673e6ec16fb9f5babb63bDouglas Gregor
402a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis  IdentifierInfo *ParamName = D.getIdentifier();
403a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis  if (ParamName) {
404a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
405a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis    if (PrevDecl && PrevDecl->isTemplateParameter())
406a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis      Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
407a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis                                                           PrevDecl);
408a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis  }
409a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis
410a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis  T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
411a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis  if (T.isNull()) {
412a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis    T = Context.IntTy; // Recover with an 'int' type.
413a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis    Invalid = true;
414a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis  }
415a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis
416a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis  NonTypeTemplateParmDecl *Param
417a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis    = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
418a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis                                      Depth, Position, ParamName, T, DInfo);
419a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis  if (Invalid)
420a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis    Param->setInvalidDecl();
4210853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis
422bdf6062bc10aa3b73b16402b440b8073310acd06Douglas Gregor  if (D.getIdentifier()) {
423a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis    // Add the template parameter into the current scope.
424bdf6062bc10aa3b73b16402b440b8073310acd06Douglas Gregor    S->AddDecl(DeclPtrTy::make(Param));
425bdf6062bc10aa3b73b16402b440b8073310acd06Douglas Gregor    IdResolver.AddDecl(Param);
426bdf6062bc10aa3b73b16402b440b8073310acd06Douglas Gregor  }
427bdf6062bc10aa3b73b16402b440b8073310acd06Douglas Gregor  return DeclPtrTy::make(Param);
428bdf6062bc10aa3b73b16402b440b8073310acd06Douglas Gregor}
429a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidis
430bdf6062bc10aa3b73b16402b440b8073310acd06Douglas Gregor/// \brief Adds a default argument to the given non-type template
431bdf6062bc10aa3b73b16402b440b8073310acd06Douglas Gregor/// parameter.
432a696ece1ac449a2b77e7c0a693b55cb10e9e2068Argyrios Kyrtzidisvoid Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
433bdf6062bc10aa3b73b16402b440b8073310acd06Douglas Gregor                                                SourceLocation EqualLoc,
434bdf6062bc10aa3b73b16402b440b8073310acd06Douglas Gregor                                                ExprArg DefaultE) {
435bdf6062bc10aa3b73b16402b440b8073310acd06Douglas Gregor  NonTypeTemplateParmDecl *TemplateParm
436bdf6062bc10aa3b73b16402b440b8073310acd06Douglas Gregor    = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
4370853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis  Expr *Default = static_cast<Expr *>(DefaultE.get());
4380853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis
439c7822dbf3c01a2a5f837cff82ba7889ea755dacaDaniel Dunbar  // C++ [temp.param]p14:
440c7822dbf3c01a2a5f837cff82ba7889ea755dacaDaniel Dunbar  //   A template-parameter shall not be used in its own default argument.
441ea94bbc4769697143e717df9b0310f874102b6c1Daniel Dunbar  // FIXME: Implement this check! Needs a recursive walk over the types.
442ea94bbc4769697143e717df9b0310f874102b6c1Daniel Dunbar
443ea94bbc4769697143e717df9b0310f874102b6c1Daniel Dunbar  // Check the well-formedness of the default template argument.
444d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  TemplateArgument Converted;
445d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
4463687e9d3a5dbfa9963af02a49a2b139d91310813Douglas Gregor                            Converted)) {
447405634b215f19eec7183bd8005e34aa5a02f64a1Douglas Gregor    TemplateParm->setInvalidDecl();
448405634b215f19eec7183bd8005e34aa5a02f64a1Douglas Gregor    return;
4490853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis  }
4504f32786ac45210143654390177105eb749b614e9Ted Kremenek
4514f32786ac45210143654390177105eb749b614e9Ted Kremenek  TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
4521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump}
4534f32786ac45210143654390177105eb749b614e9Ted Kremenek
4544f32786ac45210143654390177105eb749b614e9Ted Kremenek
4550853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis/// ActOnTemplateTemplateParameter - Called when a C++ template template
456abb5afadd11b19568359880faa5d966a4e33551cArgyrios Kyrtzidis/// parameter (e.g. T in template <template <typename> class T> class array)
457abb5afadd11b19568359880faa5d966a4e33551cArgyrios Kyrtzidis/// has been parsed. S is the current scope.
458914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas GregorSema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
459914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas Gregor                                                     SourceLocation TmpLoc,
460914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas Gregor                                                     TemplateParamsTy *Params,
461914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas Gregor                                                     IdentifierInfo *Name,
462914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas Gregor                                                     SourceLocation NameLoc,
463914ed9d30e9abf829a62aa996b083b1e47c19ff6Douglas Gregor                                                     unsigned Depth,
464405634b215f19eec7183bd8005e34aa5a02f64a1Douglas Gregor                                                     unsigned Position)
465405634b215f19eec7183bd8005e34aa5a02f64a1Douglas Gregor{
466f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar  assert(S->isTemplateParamScope() &&
467389db16c63eec6ecfa9b235155252d8da766e94eArgyrios Kyrtzidis         "Template template parameter not in template parameter scope!");
468389db16c63eec6ecfa9b235155252d8da766e94eArgyrios Kyrtzidis
46977accc11f04ed4ff9afd4e27d430144d4714be56Steve Naroff  // Construct the parameter object.
470b85bca2676b433ae555db09de4dd2823ff13b856Zhongxing Xu  TemplateTemplateParmDecl *Param =
471313e26c4e81f0e467490a530548450f4c824a6c4Douglas Gregor    TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
472313e26c4e81f0e467490a530548450f4c824a6c4Douglas Gregor                                     Position, Name,
473313e26c4e81f0e467490a530548450f4c824a6c4Douglas Gregor                                     (TemplateParameterList*)Params);
4741872b3153a388b3a548c9f699cbc348128059be9Ted Kremenek
475313e26c4e81f0e467490a530548450f4c824a6c4Douglas Gregor  // Make sure the parameter is valid.
4767d1d49d2971b20a97b3c2a301470b9eaaa130137Douglas Gregor  // FIXME: Decl object is not currently invalidated anywhere so this doesn't
477f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar  // do anything yet. However, if the template parameter list or (eventual)
47815727ddb11405c45372150b5bfb07dbfa4c9960bArgyrios Kyrtzidis  // default value is ever invalidated, that will propagate here.
47915727ddb11405c45372150b5bfb07dbfa4c9960bArgyrios Kyrtzidis  bool Invalid = false;
48015727ddb11405c45372150b5bfb07dbfa4c9960bArgyrios Kyrtzidis  if (Invalid) {
481f96b524306ccfa623235d375deee79637bd38f29Steve Naroff    Param->setInvalidDecl();
482f96b524306ccfa623235d375deee79637bd38f29Steve Naroff  }
483f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar
484213f18b3d654de7d1c7cf4a329ea9d3db1c50b6aDouglas Gregor  // If the tt-param has a name, then link the identifier into the scope
485686775deca8b8685eb90801495880e3abdd844c2Chris Lattner  // and lookup mechanisms.
486213f18b3d654de7d1c7cf4a329ea9d3db1c50b6aDouglas Gregor  if (Name) {
487eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor    S->AddDecl(DeclPtrTy::make(Param));
488eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor    IdResolver.AddDecl(Param);
489eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor  }
490f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar
491eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor  return DeclPtrTy::make(Param);
492eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor}
493eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor
494f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar/// \brief Adds a default argument to the given template template
495eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor/// parameter.
496eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregorvoid Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
497f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar                                                 SourceLocation EqualLoc,
498eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor                                                 ExprArg DefaultE) {
499eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor  TemplateTemplateParmDecl *TemplateParm
500eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor    = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
501eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor
502eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor  // Since a template-template parameter's default argument is an
503eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor  // id-expression, it must be a DeclRefExpr.
504eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor  DeclRefExpr *Default
505eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor    = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
506eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor
507eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor  // C++ [temp.param]p14:
508eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor  //   A template-parameter shall not be used in its own default argument.
509eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor  // FIXME: Implement this check! Needs a recursive walk over the types.
510eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor
511eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor  // Check the well-formedness of the template argument.
512eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor  if (!isa<TemplateDecl>(Default->getDecl())) {
513eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor    Diag(Default->getSourceRange().getBegin(),
514eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor         diag::err_template_arg_must_be_template)
515eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor      << Default->getSourceRange();
516eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor    TemplateParm->setInvalidDecl();
517eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor    return;
518332cb9be88fd2d1b294a2fbc299c354e93be673cArgyrios Kyrtzidis  }
519332cb9be88fd2d1b294a2fbc299c354e93be673cArgyrios Kyrtzidis  if (CheckTemplateArgument(TemplateParm, Default)) {
520332cb9be88fd2d1b294a2fbc299c354e93be673cArgyrios Kyrtzidis    TemplateParm->setInvalidDecl();
521eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor    return;
522eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor  }
5238538e8d43a3a9bd439c987c0de37bcbf035dd391Sebastian Redl
524eb8837b88c18631c69ac75f64ab1853762063180Douglas Gregor  DefaultE.release();
525f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar  TemplateParm->setDefaultArgument(Default);
526f772d1e2a5688572d07f42896a50ac57a4a41fe8Daniel Dunbar}
5279b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor
5289b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor/// ActOnTemplateParameterList - Builds a TemplateParameterList that
5299b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas Gregor/// contains the template parameters in Params/NumParams.
5309b7db6200d366e4964d63ae1f33c7b9d7b9831cbDouglas GregorSema::TemplateParamsTy *
531507097ec40105ed927cb5a744fad98f5875aacacArgyrios KyrtzidisSema::ActOnTemplateParameterList(unsigned Depth,
532507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis                                 SourceLocation ExportLoc,
533507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis                                 SourceLocation TemplateLoc,
534507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis                                 SourceLocation LAngleLoc,
535507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis                                 DeclPtrTy *Params, unsigned NumParams,
536507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis                                 SourceLocation RAngleLoc) {
537507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis  if (ExportLoc.isValid())
538507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis    Diag(ExportLoc, diag::note_template_export_unsupported);
539507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis
540507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis  return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
541507097ec40105ed927cb5a744fad98f5875aacacArgyrios Kyrtzidis                                       (Decl**)Params, NumParams, RAngleLoc);
542ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis}
543ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis
544ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios KyrtzidisSema::DeclResult
545ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios KyrtzidisSema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
546ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis                         SourceLocation KWLoc, const CXXScopeSpec &SS,
547ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis                         IdentifierInfo *Name, SourceLocation NameLoc,
548ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis                         AttributeList *Attr,
549ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis                         TemplateParameterList *TemplateParams,
550ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis                         AccessSpecifier AS) {
551ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis  assert(TemplateParams && TemplateParams->size() > 0 &&
552ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis         "No template parameters");
553f226ff9fe8c8db6c5b74a61ce649eda1491c3502Argyrios Kyrtzidis  assert(TUK != TUK_Reference && "Can only declare or define class templates");
554f226ff9fe8c8db6c5b74a61ce649eda1491c3502Argyrios Kyrtzidis  bool Invalid = false;
555f226ff9fe8c8db6c5b74a61ce649eda1491c3502Argyrios Kyrtzidis
556f226ff9fe8c8db6c5b74a61ce649eda1491c3502Argyrios Kyrtzidis  // Check that we can declare a template here.
557f226ff9fe8c8db6c5b74a61ce649eda1491c3502Argyrios Kyrtzidis  if (CheckTemplateDeclScope(S, TemplateParams))
558ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis    return true;
559ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis
560ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis  TagDecl::TagKind Kind;
561ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis  switch (TagSpec) {
562ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis  default: assert(0 && "Unknown tag type!");
563ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
564ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
565ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
566ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis  }
567ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis
568ee0f84fc84ed7de7975e102668d8e53a778f7a8cArgyrios Kyrtzidis  // There is no such thing as an unnamed class template.
569788f5a1242c04762f91eaa7565c07b9865846d88Douglas Gregor  if (!Name) {
570a88084b78fd4ca5d3d858c14b02414f8cc399f02Douglas Gregor    Diag(KWLoc, diag::err_template_unnamed_class);
5713e9d32656a8a3a787f64f9beeef66d2d700eb85dArgyrios Kyrtzidis    return true;
5723e9d32656a8a3a787f64f9beeef66d2d700eb85dArgyrios Kyrtzidis  }
5733e9d32656a8a3a787f64f9beeef66d2d700eb85dArgyrios Kyrtzidis
574405634b215f19eec7183bd8005e34aa5a02f64a1Douglas Gregor  // Find any previous declaration with this name.
575405634b215f19eec7183bd8005e34aa5a02f64a1Douglas Gregor  DeclContext *SemanticContext;
5763e9d32656a8a3a787f64f9beeef66d2d700eb85dArgyrios Kyrtzidis  LookupResult Previous;
5773e9d32656a8a3a787f64f9beeef66d2d700eb85dArgyrios Kyrtzidis  if (SS.isNotEmpty() && !SS.isInvalid()) {
5783e9d32656a8a3a787f64f9beeef66d2d700eb85dArgyrios Kyrtzidis    SemanticContext = computeDeclContext(SS, true);
5793e9d32656a8a3a787f64f9beeef66d2d700eb85dArgyrios Kyrtzidis    if (!SemanticContext) {
5803e9d32656a8a3a787f64f9beeef66d2d700eb85dArgyrios Kyrtzidis      // FIXME: Produce a reasonable diagnostic here
5813e9d32656a8a3a787f64f9beeef66d2d700eb85dArgyrios Kyrtzidis      return true;
5823e9d32656a8a3a787f64f9beeef66d2d700eb85dArgyrios Kyrtzidis    }
583405634b215f19eec7183bd8005e34aa5a02f64a1Douglas Gregor
584405634b215f19eec7183bd8005e34aa5a02f64a1Douglas Gregor    Previous = LookupQualifiedName(SemanticContext, Name, LookupOrdinaryName,
585405634b215f19eec7183bd8005e34aa5a02f64a1Douglas Gregor                                   true);
5863e9d32656a8a3a787f64f9beeef66d2d700eb85dArgyrios Kyrtzidis  } else {
5873e9d32656a8a3a787f64f9beeef66d2d700eb85dArgyrios Kyrtzidis    SemanticContext = CurContext;
5883e9d32656a8a3a787f64f9beeef66d2d700eb85dArgyrios Kyrtzidis    Previous = LookupName(S, Name, LookupOrdinaryName, true);
5893e9d32656a8a3a787f64f9beeef66d2d700eb85dArgyrios Kyrtzidis  }
5903e9d32656a8a3a787f64f9beeef66d2d700eb85dArgyrios Kyrtzidis
591a88084b78fd4ca5d3d858c14b02414f8cc399f02Douglas Gregor  assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
592a88084b78fd4ca5d3d858c14b02414f8cc399f02Douglas Gregor  NamedDecl *PrevDecl = 0;
59387c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  if (Previous.begin() != Previous.end())
59487c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor    PrevDecl = *Previous.begin();
59587c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor
59687c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
59787c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor    PrevDecl = 0;
59887c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor
59987c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  // If there is a previous declaration with the same name, check
60087c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  // whether this is a valid redeclaration.
60187c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  ClassTemplateDecl *PrevClassTemplate
60287c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor    = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
60387c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor  if (PrevClassTemplate) {
60487c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor    // Ensure that the template parameter lists are compatible.
60587c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor    if (!TemplateParameterListsAreEqual(TemplateParams,
60687c08a5d6b9e1e44ae6f554df40139d3a6f60b33Douglas Gregor                                   PrevClassTemplate->getTemplateParameters(),
607389db16c63eec6ecfa9b235155252d8da766e94eArgyrios Kyrtzidis                                        /*Complain=*/true))
608686775deca8b8685eb90801495880e3abdd844c2Chris Lattner      return true;
60975dfb65c38d51772df9a00ce2d2feeefd55667adChris Lattner
610389db16c63eec6ecfa9b235155252d8da766e94eArgyrios Kyrtzidis    // C++ [temp.class]p4:
611467dc88512b4ba4bb16e274ea3771dc1415d31daDouglas Gregor    //   In a redeclaration, partial specialization, explicit
612467dc88512b4ba4bb16e274ea3771dc1415d31daDouglas Gregor    //   specialization or explicit instantiation of a class template,
613df95a13ec73d2cdaea79555cb412d767f4963120Douglas Gregor    //   the class-key shall agree in kind with the original class
614b1c86492f9a9bef01a4567408c22f961bbd604feArgyrios Kyrtzidis    //   template declaration (7.1.5.3).
615b1c86492f9a9bef01a4567408c22f961bbd604feArgyrios Kyrtzidis    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
6164db64a461cb3442934afe43c83ed3f17f7c11c1dDouglas Gregor    if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
6174db64a461cb3442934afe43c83ed3f17f7c11c1dDouglas Gregor      Diag(KWLoc, diag::err_use_with_wrong_tag)
618b1c86492f9a9bef01a4567408c22f961bbd604feArgyrios Kyrtzidis        << Name
619b0f4b9a558933b307073f7cd7753602f94354ae9Argyrios Kyrtzidis        << CodeModificationHint::CreateReplacement(KWLoc,
620b0f4b9a558933b307073f7cd7753602f94354ae9Argyrios Kyrtzidis                            PrevRecordDecl->getKindName());
621b0f4b9a558933b307073f7cd7753602f94354ae9Argyrios Kyrtzidis      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
622d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie      Kind = PrevRecordDecl->getTagKind();
623b0f4b9a558933b307073f7cd7753602f94354ae9Argyrios Kyrtzidis    }
6243c7f4134603d04b44f997b43c0a9def270f25386Sebastian Redl
6250853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis    // Check for redefinition of this class template.
6263c7f4134603d04b44f997b43c0a9def270f25386Sebastian Redl    if (TUK == TUK_Definition) {
6270853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis      if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
6285262fda30b876c8aae95f2eb92e349418d6b14bbDaniel Dunbar        Diag(NameLoc, diag::err_redefinition) << Name;
6295262fda30b876c8aae95f2eb92e349418d6b14bbDaniel Dunbar        Diag(Def->getLocation(), diag::note_previous_definition);
63031b87d8006d4863dd9b17e515ac720941efc38e3Daniel Dunbar        // FIXME: Would it make sense to try to "forget" the previous
6313c7f4134603d04b44f997b43c0a9def270f25386Sebastian Redl        // definition, as part of error recovery?
6323c7f4134603d04b44f997b43c0a9def270f25386Sebastian Redl        return true;
633d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie      }
634389db16c63eec6ecfa9b235155252d8da766e94eArgyrios Kyrtzidis    }
6355cf48766d626ff6b223acc9d4b7e415ca8480836Ted Kremenek  } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
6364db64a461cb3442934afe43c83ed3f17f7c11c1dDouglas Gregor    // Maybe we will complain about the shadowed template parameter.
637a88084b78fd4ca5d3d858c14b02414f8cc399f02Douglas Gregor    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
638a88084b78fd4ca5d3d858c14b02414f8cc399f02Douglas Gregor    // Just pretend that we didn't see the previous declaration.
639521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar    PrevDecl = 0;
6404cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor  } else if (PrevDecl) {
6414cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor    // C++ [temp]p5:
6424cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor    //   A class template shall not have the same name as any other
6434cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor    //   template, class, function, object, enumeration, enumerator,
6444cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor    //   namespace, or type in the same scope (3.3), except as specified
6454cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor    //   in (14.5.4).
6464cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
6474cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6484cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor    return true;
6494cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor  }
6504cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor
6514cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor  // Check the template parameter list of this declaration, possibly
6524cd912aa94656697a44c3ebb159f05060300524eDouglas Gregor  // merging in the template parameter list from the previous class
653d808bd2978bd4ac95a92b309b038452b533fd7a0Argyrios Kyrtzidis  // template declaration.
654d808bd2978bd4ac95a92b309b038452b533fd7a0Argyrios Kyrtzidis  if (CheckTemplateParameterList(TemplateParams,
655d808bd2978bd4ac95a92b309b038452b533fd7a0Argyrios Kyrtzidis            PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
656d808bd2978bd4ac95a92b309b038452b533fd7a0Argyrios Kyrtzidis    Invalid = true;
657d808bd2978bd4ac95a92b309b038452b533fd7a0Argyrios Kyrtzidis
658d808bd2978bd4ac95a92b309b038452b533fd7a0Argyrios Kyrtzidis  // FIXME: If we had a scope specifier, we better have a previous template
659d808bd2978bd4ac95a92b309b038452b533fd7a0Argyrios Kyrtzidis  // declaration!
660d808bd2978bd4ac95a92b309b038452b533fd7a0Argyrios Kyrtzidis
661d808bd2978bd4ac95a92b309b038452b533fd7a0Argyrios Kyrtzidis  CXXRecordDecl *NewClass =
662d808bd2978bd4ac95a92b309b038452b533fd7a0Argyrios Kyrtzidis    CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
663d808bd2978bd4ac95a92b309b038452b533fd7a0Argyrios Kyrtzidis                          PrevClassTemplate?
664abb5afadd11b19568359880faa5d966a4e33551cArgyrios Kyrtzidis                            PrevClassTemplate->getTemplatedDecl() : 0,
665abb5afadd11b19568359880faa5d966a4e33551cArgyrios Kyrtzidis                          /*DelayTypeCreation=*/true);
666abb5afadd11b19568359880faa5d966a4e33551cArgyrios Kyrtzidis
667d808bd2978bd4ac95a92b309b038452b533fd7a0Argyrios Kyrtzidis  ClassTemplateDecl *NewTemplate
668d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
669abb5afadd11b19568359880faa5d966a4e33551cArgyrios Kyrtzidis                                DeclarationName(Name), TemplateParams,
670abb5afadd11b19568359880faa5d966a4e33551cArgyrios Kyrtzidis                                NewClass, PrevClassTemplate);
671d808bd2978bd4ac95a92b309b038452b533fd7a0Argyrios Kyrtzidis  NewClass->setDescribedClassTemplate(NewTemplate);
672521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar
673521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar  // Build the type for the class template declaration now.
674521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar  QualType T =
675521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar    Context.getTypeDeclType(NewClass,
676f7acc37450d59ef751df73acb91de73850cc6517Daniel Dunbar                            PrevClassTemplate?
677521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar                              PrevClassTemplate->getTemplatedDecl() : 0);
6785262fda30b876c8aae95f2eb92e349418d6b14bbDaniel Dunbar  assert(T->isDependentType() && "Class template type is not dependent?");
6795262fda30b876c8aae95f2eb92e349418d6b14bbDaniel Dunbar  (void)T;
680521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar
681521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar  // Set the access specifier.
682521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar  SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
683f7acc37450d59ef751df73acb91de73850cc6517Daniel Dunbar
684d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  // Set the lexical context of these templates
685a88084b78fd4ca5d3d858c14b02414f8cc399f02Douglas Gregor  NewClass->setLexicalDeclContext(CurContext);
68644c181aec37789f25f6c15543c164416f72e562aDouglas Gregor  NewTemplate->setLexicalDeclContext(CurContext);
687df95a13ec73d2cdaea79555cb412d767f4963120Douglas Gregor
688467dc88512b4ba4bb16e274ea3771dc1415d31daDouglas Gregor  if (TUK == TUK_Definition)
689dca8ee8b7bc86076916a3a80f553f7a4e98c14afDouglas Gregor    NewClass->startDefinition();
690ba7537febdf1bc1cc617e1f1746f2644feba6274Chandler Carruth
691521bf9c529e653ab28896d027352d3e16e2672d5Daniel Dunbar  if (Attr)
6927b55668db7618334cc40011d3c1e128524d89462Daniel Dunbar    ProcessDeclAttributeList(S, NewClass, Attr);
6937b55668db7618334cc40011d3c1e128524d89462Daniel Dunbar
6947b55668db7618334cc40011d3c1e128524d89462Daniel Dunbar  PushOnScopeChains(NewTemplate, S);
6957b55668db7618334cc40011d3c1e128524d89462Daniel Dunbar
6967b55668db7618334cc40011d3c1e128524d89462Daniel Dunbar  if (Invalid) {
6977b55668db7618334cc40011d3c1e128524d89462Daniel Dunbar    NewTemplate->setInvalidDecl();
6987b55668db7618334cc40011d3c1e128524d89462Daniel Dunbar    NewClass->setInvalidDecl();
6995262fda30b876c8aae95f2eb92e349418d6b14bbDaniel Dunbar  }
7005262fda30b876c8aae95f2eb92e349418d6b14bbDaniel Dunbar  return DeclPtrTy::make(NewTemplate);
7017b55668db7618334cc40011d3c1e128524d89462Daniel Dunbar}
702869824e87940f97b87064db2df2861e82e08a8c6Daniel Dunbar
7037b55668db7618334cc40011d3c1e128524d89462Daniel Dunbar/// \brief Checks the validity of a template parameter list, possibly
7047b55668db7618334cc40011d3c1e128524d89462Daniel Dunbar/// considering the template parameter list from a previous
7057b55668db7618334cc40011d3c1e128524d89462Daniel Dunbar/// declaration.
7067b55668db7618334cc40011d3c1e128524d89462Daniel Dunbar///
7077b55668db7618334cc40011d3c1e128524d89462Daniel Dunbar/// If an "old" template parameter list is provided, it must be
708d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie/// equivalent (per TemplateParameterListsAreEqual) to the "new"
709686775deca8b8685eb90801495880e3abdd844c2Chris Lattner/// template parameter list.
7107b55668db7618334cc40011d3c1e128524d89462Daniel Dunbar///
711e47be3e9682e82da15059006f43c7f3c021e4fffDouglas Gregor/// \param NewParams Template parameter list for a new template
7124db64a461cb3442934afe43c83ed3f17f7c11c1dDouglas Gregor/// declaration. This template parameter list will be updated with any
713a88084b78fd4ca5d3d858c14b02414f8cc399f02Douglas Gregor/// default arguments that are carried through from the previous
714299a4a967b02c9f0d0d94ad8560e3ced893f9116Argyrios Kyrtzidis/// template parameter list.
715df95a13ec73d2cdaea79555cb412d767f4963120Douglas Gregor///
716467dc88512b4ba4bb16e274ea3771dc1415d31daDouglas Gregor/// \param OldParams If provided, template parameter list from a
71799ba202f659e1885fa5ee114f97c97cf6a857491Douglas Gregor/// previous declaration of the same template. Default template
718ba7537febdf1bc1cc617e1f1746f2644feba6274Chandler Carruth/// arguments will be merged from the old template parameter list to
719abc563f554951259bbe0315055cad92ee14d87e4Douglas Gregor/// the new template parameter list.
720abc563f554951259bbe0315055cad92ee14d87e4Douglas Gregor///
721abc563f554951259bbe0315055cad92ee14d87e4Douglas Gregor/// \returns true if an error occurred, false otherwise.
722abc563f554951259bbe0315055cad92ee14d87e4Douglas Gregorbool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
723abc563f554951259bbe0315055cad92ee14d87e4Douglas Gregor                                      TemplateParameterList *OldParams) {
724abc563f554951259bbe0315055cad92ee14d87e4Douglas Gregor  bool Invalid = false;
725abc563f554951259bbe0315055cad92ee14d87e4Douglas Gregor
726abc563f554951259bbe0315055cad92ee14d87e4Douglas Gregor  // C++ [temp.param]p10:
7271abc6bca3d7fb0e7b1e40fbcad6cfb5e10594548Douglas Gregor  //   The set of default template-arguments available for use with a
7281abc6bca3d7fb0e7b1e40fbcad6cfb5e10594548Douglas Gregor  //   template declaration or definition is obtained by merging the
7291abc6bca3d7fb0e7b1e40fbcad6cfb5e10594548Douglas Gregor  //   default arguments from the definition (if in scope) and all
7301abc6bca3d7fb0e7b1e40fbcad6cfb5e10594548Douglas Gregor  //   declarations in scope in the same way default function
731cee235cdf0b8047761ffac598c4c3a32ab7411a2Douglas Gregor  //   arguments are (8.3.6).
732cee235cdf0b8047761ffac598c4c3a32ab7411a2Douglas Gregor  bool SawDefaultArgument = false;
733cee235cdf0b8047761ffac598c4c3a32ab7411a2Douglas Gregor  SourceLocation PreviousDefaultArgLoc;
734cee235cdf0b8047761ffac598c4c3a32ab7411a2Douglas Gregor
735cee235cdf0b8047761ffac598c4c3a32ab7411a2Douglas Gregor  bool SawParameterPack = false;
736cee235cdf0b8047761ffac598c4c3a32ab7411a2Douglas Gregor  SourceLocation ParameterPackLoc;
737cee235cdf0b8047761ffac598c4c3a32ab7411a2Douglas Gregor
738cee235cdf0b8047761ffac598c4c3a32ab7411a2Douglas Gregor  // Dummy initialization to avoid warnings.
739cee235cdf0b8047761ffac598c4c3a32ab7411a2Douglas Gregor  TemplateParameterList::iterator OldParam = NewParams->end();
740cee235cdf0b8047761ffac598c4c3a32ab7411a2Douglas Gregor  if (OldParams)
741cee235cdf0b8047761ffac598c4c3a32ab7411a2Douglas Gregor    OldParam = OldParams->begin();
7421abc6bca3d7fb0e7b1e40fbcad6cfb5e10594548Douglas Gregor
7432283d79155a3e82442fce124ce5fd704ca138801Douglas Gregor  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
7442283d79155a3e82442fce124ce5fd704ca138801Douglas Gregor                                    NewParamEnd = NewParams->end();
745686775deca8b8685eb90801495880e3abdd844c2Chris Lattner       NewParam != NewParamEnd; ++NewParam) {
7461abc6bca3d7fb0e7b1e40fbcad6cfb5e10594548Douglas Gregor    // Variables used to diagnose redundant default arguments
747cee235cdf0b8047761ffac598c4c3a32ab7411a2Douglas Gregor    bool RedundantDefaultArg = false;
7481abc6bca3d7fb0e7b1e40fbcad6cfb5e10594548Douglas Gregor    SourceLocation OldDefaultLoc;
749d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie    SourceLocation NewDefaultLoc;
7501abc6bca3d7fb0e7b1e40fbcad6cfb5e10594548Douglas Gregor
751686775deca8b8685eb90801495880e3abdd844c2Chris Lattner    // Variables used to diagnose missing default arguments
752686775deca8b8685eb90801495880e3abdd844c2Chris Lattner    bool MissingDefaultArg = false;
7537ae2faafd30524ef5f863bb3b8701977888839bbDouglas Gregor
7547ae2faafd30524ef5f863bb3b8701977888839bbDouglas Gregor    // C++0x [temp.param]p11:
7557ae2faafd30524ef5f863bb3b8701977888839bbDouglas Gregor    // If a template parameter of a class template is a template parameter pack,
75639c411fa229b2a6747b92f945d1702ee674d3470Douglas Gregor    // it must be the last template parameter.
757686775deca8b8685eb90801495880e3abdd844c2Chris Lattner    if (SawParameterPack) {
758b0f4b9a558933b307073f7cd7753602f94354ae9Argyrios Kyrtzidis      Diag(ParameterPackLoc,
759b0f4b9a558933b307073f7cd7753602f94354ae9Argyrios Kyrtzidis           diag::err_template_param_pack_must_be_last_template_parameter);
760b0f4b9a558933b307073f7cd7753602f94354ae9Argyrios Kyrtzidis      Invalid = true;
761b0f4b9a558933b307073f7cd7753602f94354ae9Argyrios Kyrtzidis    }
7628cc488fefb2fb04bc8d5398da29f0182f97934cfChris Lattner
7636aa52ec6b969faabf3764baf79d89810b8249a7eDouglas Gregor    // Merge default arguments for template type parameters.
7646aa52ec6b969faabf3764baf79d89810b8249a7eDouglas Gregor    if (TemplateTypeParmDecl *NewTypeParm
7656aa52ec6b969faabf3764baf79d89810b8249a7eDouglas Gregor          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
7666aa52ec6b969faabf3764baf79d89810b8249a7eDouglas Gregor      TemplateTypeParmDecl *OldTypeParm
7676aa52ec6b969faabf3764baf79d89810b8249a7eDouglas Gregor          = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
7686aa52ec6b969faabf3764baf79d89810b8249a7eDouglas Gregor
7696aa52ec6b969faabf3764baf79d89810b8249a7eDouglas Gregor      if (NewTypeParm->isParameterPack()) {
7700853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis        assert(!NewTypeParm->hasDefaultArgument() &&
7710853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis               "Parameter packs can't have a default argument!");
7720853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis        SawParameterPack = true;
7730853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis        ParameterPackLoc = NewTypeParm->getLocation();
7740853a02c3b04d96a3c432b883e403175c954cd81Argyrios Kyrtzidis      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
775          NewTypeParm->hasDefaultArgument()) {
776        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
777        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
778        SawDefaultArgument = true;
779        RedundantDefaultArg = true;
780        PreviousDefaultArgLoc = NewDefaultLoc;
781      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
782        // Merge the default argument from the old declaration to the
783        // new declaration.
784        SawDefaultArgument = true;
785        NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
786                                        OldTypeParm->getDefaultArgumentLoc(),
787                                        true);
788        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
789      } else if (NewTypeParm->hasDefaultArgument()) {
790        SawDefaultArgument = true;
791        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
792      } else if (SawDefaultArgument)
793        MissingDefaultArg = true;
794    } else if (NonTypeTemplateParmDecl *NewNonTypeParm
795               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
796      // Merge default arguments for non-type template parameters
797      NonTypeTemplateParmDecl *OldNonTypeParm
798        = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
799      if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
800          NewNonTypeParm->hasDefaultArgument()) {
801        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
802        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
803        SawDefaultArgument = true;
804        RedundantDefaultArg = true;
805        PreviousDefaultArgLoc = NewDefaultLoc;
806      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
807        // Merge the default argument from the old declaration to the
808        // new declaration.
809        SawDefaultArgument = true;
810        // FIXME: We need to create a new kind of "default argument"
811        // expression that points to a previous template template
812        // parameter.
813        NewNonTypeParm->setDefaultArgument(
814                                        OldNonTypeParm->getDefaultArgument());
815        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
816      } else if (NewNonTypeParm->hasDefaultArgument()) {
817        SawDefaultArgument = true;
818        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
819      } else if (SawDefaultArgument)
820        MissingDefaultArg = true;
821    } else {
822    // Merge default arguments for template template parameters
823      TemplateTemplateParmDecl *NewTemplateParm
824        = cast<TemplateTemplateParmDecl>(*NewParam);
825      TemplateTemplateParmDecl *OldTemplateParm
826        = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
827      if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
828          NewTemplateParm->hasDefaultArgument()) {
829        OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
830        NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
831        SawDefaultArgument = true;
832        RedundantDefaultArg = true;
833        PreviousDefaultArgLoc = NewDefaultLoc;
834      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
835        // Merge the default argument from the old declaration to the
836        // new declaration.
837        SawDefaultArgument = true;
838        // FIXME: We need to create a new kind of "default argument" expression
839        // that points to a previous template template parameter.
840        NewTemplateParm->setDefaultArgument(
841                                        OldTemplateParm->getDefaultArgument());
842        PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
843      } else if (NewTemplateParm->hasDefaultArgument()) {
844        SawDefaultArgument = true;
845        PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
846      } else if (SawDefaultArgument)
847        MissingDefaultArg = true;
848    }
849
850    if (RedundantDefaultArg) {
851      // C++ [temp.param]p12:
852      //   A template-parameter shall not be given default arguments
853      //   by two different declarations in the same scope.
854      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
855      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
856      Invalid = true;
857    } else if (MissingDefaultArg) {
858      // C++ [temp.param]p11:
859      //   If a template-parameter has a default template-argument,
860      //   all subsequent template-parameters shall have a default
861      //   template-argument supplied.
862      Diag((*NewParam)->getLocation(),
863           diag::err_template_param_default_arg_missing);
864      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
865      Invalid = true;
866    }
867
868    // If we have an old template parameter list that we're merging
869    // in, move on to the next parameter.
870    if (OldParams)
871      ++OldParam;
872  }
873
874  return Invalid;
875}
876
877/// \brief Match the given template parameter lists to the given scope
878/// specifier, returning the template parameter list that applies to the
879/// name.
880///
881/// \param DeclStartLoc the start of the declaration that has a scope
882/// specifier or a template parameter list.
883///
884/// \param SS the scope specifier that will be matched to the given template
885/// parameter lists. This scope specifier precedes a qualified name that is
886/// being declared.
887///
888/// \param ParamLists the template parameter lists, from the outermost to the
889/// innermost template parameter lists.
890///
891/// \param NumParamLists the number of template parameter lists in ParamLists.
892///
893/// \returns the template parameter list, if any, that corresponds to the
894/// name that is preceded by the scope specifier @p SS. This template
895/// parameter list may be have template parameters (if we're declaring a
896/// template) or may have no template parameters (if we're declaring a
897/// template specialization), or may be NULL (if we were's declaring isn't
898/// itself a template).
899TemplateParameterList *
900Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
901                                              const CXXScopeSpec &SS,
902                                          TemplateParameterList **ParamLists,
903                                              unsigned NumParamLists) {
904  // Find the template-ids that occur within the nested-name-specifier. These
905  // template-ids will match up with the template parameter lists.
906  llvm::SmallVector<const TemplateSpecializationType *, 4>
907    TemplateIdsInSpecifier;
908  for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
909       NNS; NNS = NNS->getPrefix()) {
910    if (const TemplateSpecializationType *SpecType
911          = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
912      TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
913      if (!Template)
914        continue; // FIXME: should this be an error? probably...
915
916      if (const RecordType *Record = SpecType->getAs<RecordType>()) {
917        ClassTemplateSpecializationDecl *SpecDecl
918          = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
919        // If the nested name specifier refers to an explicit specialization,
920        // we don't need a template<> header.
921        // FIXME: revisit this approach once we cope with specialization
922        // properly.
923        if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
924          continue;
925      }
926
927      TemplateIdsInSpecifier.push_back(SpecType);
928    }
929  }
930
931  // Reverse the list of template-ids in the scope specifier, so that we can
932  // more easily match up the template-ids and the template parameter lists.
933  std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
934
935  SourceLocation FirstTemplateLoc = DeclStartLoc;
936  if (NumParamLists)
937    FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
938
939  // Match the template-ids found in the specifier to the template parameter
940  // lists.
941  unsigned Idx = 0;
942  for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
943       Idx != NumTemplateIds; ++Idx) {
944    QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
945    bool DependentTemplateId = TemplateId->isDependentType();
946    if (Idx >= NumParamLists) {
947      // We have a template-id without a corresponding template parameter
948      // list.
949      if (DependentTemplateId) {
950        // FIXME: the location information here isn't great.
951        Diag(SS.getRange().getBegin(),
952             diag::err_template_spec_needs_template_parameters)
953          << TemplateId
954          << SS.getRange();
955      } else {
956        Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
957          << SS.getRange()
958          << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
959                                                   "template<> ");
960      }
961      return 0;
962    }
963
964    // Check the template parameter list against its corresponding template-id.
965    if (DependentTemplateId) {
966      TemplateDecl *Template
967        = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
968
969      if (ClassTemplateDecl *ClassTemplate
970            = dyn_cast<ClassTemplateDecl>(Template)) {
971        TemplateParameterList *ExpectedTemplateParams = 0;
972        // Is this template-id naming the primary template?
973        if (Context.hasSameType(TemplateId,
974                             ClassTemplate->getInjectedClassNameType(Context)))
975          ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
976        // ... or a partial specialization?
977        else if (ClassTemplatePartialSpecializationDecl *PartialSpec
978                   = ClassTemplate->findPartialSpecialization(TemplateId))
979          ExpectedTemplateParams = PartialSpec->getTemplateParameters();
980
981        if (ExpectedTemplateParams)
982          TemplateParameterListsAreEqual(ParamLists[Idx],
983                                         ExpectedTemplateParams,
984                                         true);
985      }
986    } else if (ParamLists[Idx]->size() > 0)
987      Diag(ParamLists[Idx]->getTemplateLoc(),
988           diag::err_template_param_list_matches_nontemplate)
989        << TemplateId
990        << ParamLists[Idx]->getSourceRange();
991  }
992
993  // If there were at least as many template-ids as there were template
994  // parameter lists, then there are no template parameter lists remaining for
995  // the declaration itself.
996  if (Idx >= NumParamLists)
997    return 0;
998
999  // If there were too many template parameter lists, complain about that now.
1000  if (Idx != NumParamLists - 1) {
1001    while (Idx < NumParamLists - 1) {
1002      Diag(ParamLists[Idx]->getTemplateLoc(),
1003           diag::err_template_spec_extra_headers)
1004        << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1005                       ParamLists[Idx]->getRAngleLoc());
1006      ++Idx;
1007    }
1008  }
1009
1010  // Return the last template parameter list, which corresponds to the
1011  // entity being declared.
1012  return ParamLists[NumParamLists - 1];
1013}
1014
1015/// \brief Translates template arguments as provided by the parser
1016/// into template arguments used by semantic analysis.
1017static void
1018translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
1019                           SourceLocation *TemplateArgLocs,
1020                     llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
1021  TemplateArgs.reserve(TemplateArgsIn.size());
1022
1023  void **Args = TemplateArgsIn.getArgs();
1024  bool *ArgIsType = TemplateArgsIn.getArgIsType();
1025  for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
1026    TemplateArgs.push_back(
1027      ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
1028                                       //FIXME: Preserve type source info.
1029                                       Sema::GetTypeFromParser(Args[Arg]))
1030                    : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
1031  }
1032}
1033
1034QualType Sema::CheckTemplateIdType(TemplateName Name,
1035                                   SourceLocation TemplateLoc,
1036                                   SourceLocation LAngleLoc,
1037                                   const TemplateArgument *TemplateArgs,
1038                                   unsigned NumTemplateArgs,
1039                                   SourceLocation RAngleLoc) {
1040  TemplateDecl *Template = Name.getAsTemplateDecl();
1041  if (!Template) {
1042    // The template name does not resolve to a template, so we just
1043    // build a dependent template-id type.
1044    return Context.getTemplateSpecializationType(Name, TemplateArgs,
1045                                                 NumTemplateArgs);
1046  }
1047
1048  // Check that the template argument list is well-formed for this
1049  // template.
1050  TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1051                                        NumTemplateArgs);
1052  if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
1053                                TemplateArgs, NumTemplateArgs, RAngleLoc,
1054                                false, Converted))
1055    return QualType();
1056
1057  assert((Converted.structuredSize() ==
1058            Template->getTemplateParameters()->size()) &&
1059         "Converted template argument list is too short!");
1060
1061  QualType CanonType;
1062
1063  if (TemplateSpecializationType::anyDependentTemplateArguments(
1064                                                      TemplateArgs,
1065                                                      NumTemplateArgs)) {
1066    // This class template specialization is a dependent
1067    // type. Therefore, its canonical type is another class template
1068    // specialization type that contains all of the converted
1069    // arguments in canonical form. This ensures that, e.g., A<T> and
1070    // A<T, T> have identical types when A is declared as:
1071    //
1072    //   template<typename T, typename U = T> struct A;
1073    TemplateName CanonName = Context.getCanonicalTemplateName(Name);
1074    CanonType = Context.getTemplateSpecializationType(CanonName,
1075                                                   Converted.getFlatArguments(),
1076                                                   Converted.flatSize());
1077
1078    // FIXME: CanonType is not actually the canonical type, and unfortunately
1079    // it is a TemplateTypeSpecializationType that we will never use again.
1080    // In the future, we need to teach getTemplateSpecializationType to only
1081    // build the canonical type and return that to us.
1082    CanonType = Context.getCanonicalType(CanonType);
1083  } else if (ClassTemplateDecl *ClassTemplate
1084               = dyn_cast<ClassTemplateDecl>(Template)) {
1085    // Find the class template specialization declaration that
1086    // corresponds to these arguments.
1087    llvm::FoldingSetNodeID ID;
1088    ClassTemplateSpecializationDecl::Profile(ID,
1089                                             Converted.getFlatArguments(),
1090                                             Converted.flatSize(),
1091                                             Context);
1092    void *InsertPos = 0;
1093    ClassTemplateSpecializationDecl *Decl
1094      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1095    if (!Decl) {
1096      // This is the first time we have referenced this class template
1097      // specialization. Create the canonical declaration and add it to
1098      // the set of specializations.
1099      Decl = ClassTemplateSpecializationDecl::Create(Context,
1100                                    ClassTemplate->getDeclContext(),
1101                                    TemplateLoc,
1102                                    ClassTemplate,
1103                                    Converted, 0);
1104      ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1105      Decl->setLexicalDeclContext(CurContext);
1106    }
1107
1108    CanonType = Context.getTypeDeclType(Decl);
1109  }
1110
1111  // Build the fully-sugared type for this class template
1112  // specialization, which refers back to the class template
1113  // specialization we created or found.
1114  //FIXME: Preserve type source info.
1115  return Context.getTemplateSpecializationType(Name, TemplateArgs,
1116                                               NumTemplateArgs, CanonType);
1117}
1118
1119Action::TypeResult
1120Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1121                          SourceLocation LAngleLoc,
1122                          ASTTemplateArgsPtr TemplateArgsIn,
1123                          SourceLocation *TemplateArgLocs,
1124                          SourceLocation RAngleLoc,
1125                          DeclSpec::TST TagSpec,
1126                          SourceLocation TagLoc) {
1127  TemplateName Template = TemplateD.getAsVal<TemplateName>();
1128
1129  // Translate the parser's template argument list in our AST format.
1130  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1131  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1132
1133  QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
1134                                        TemplateArgs.data(),
1135                                        TemplateArgs.size(),
1136                                        RAngleLoc);
1137  TemplateArgsIn.release();
1138
1139  if (Result.isNull())
1140    return true;
1141
1142  // If we were given a tag specifier, verify it.
1143  if (TagSpec != DeclSpec::TST_unspecified) {
1144    TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
1145
1146    if (const RecordType *T = Result->getAs<RecordType>()) {
1147      RecordDecl *D = T->getDecl();
1148
1149      IdentifierInfo *Id = D->getIdentifier();
1150      assert(Id && "templated class must have an identifier");
1151
1152      if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1153        Diag(TagLoc, diag::err_use_with_wrong_tag)
1154          << Id
1155          << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1156                                                     D->getKindName());
1157      }
1158    }
1159  }
1160
1161  return Result.getAsOpaquePtr();
1162}
1163
1164Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1165                                                 SourceLocation TemplateNameLoc,
1166                                                 SourceLocation LAngleLoc,
1167                                           const TemplateArgument *TemplateArgs,
1168                                                 unsigned NumTemplateArgs,
1169                                                 SourceLocation RAngleLoc) {
1170  // FIXME: Can we do any checking at this point? I guess we could check the
1171  // template arguments that we have against the template name, if the template
1172  // name refers to a single template. That's not a terribly common case,
1173  // though.
1174  return Owned(TemplateIdRefExpr::Create(Context,
1175                                         /*FIXME: New type?*/Context.OverloadTy,
1176                                         /*FIXME: Necessary?*/0,
1177                                         /*FIXME: Necessary?*/SourceRange(),
1178                                         Template, TemplateNameLoc, LAngleLoc,
1179                                         TemplateArgs,
1180                                         NumTemplateArgs, RAngleLoc));
1181}
1182
1183Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1184                                                 SourceLocation TemplateNameLoc,
1185                                                 SourceLocation LAngleLoc,
1186                                              ASTTemplateArgsPtr TemplateArgsIn,
1187                                                SourceLocation *TemplateArgLocs,
1188                                                 SourceLocation RAngleLoc) {
1189  TemplateName Template = TemplateD.getAsVal<TemplateName>();
1190
1191  // Translate the parser's template argument list in our AST format.
1192  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1193  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1194  TemplateArgsIn.release();
1195
1196  return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1197                             TemplateArgs.data(), TemplateArgs.size(),
1198                             RAngleLoc);
1199}
1200
1201Sema::OwningExprResult
1202Sema::ActOnMemberTemplateIdReferenceExpr(Scope *S, ExprArg Base,
1203                                         SourceLocation OpLoc,
1204                                         tok::TokenKind OpKind,
1205                                         const CXXScopeSpec &SS,
1206                                         TemplateTy TemplateD,
1207                                         SourceLocation TemplateNameLoc,
1208                                         SourceLocation LAngleLoc,
1209                                         ASTTemplateArgsPtr TemplateArgsIn,
1210                                         SourceLocation *TemplateArgLocs,
1211                                         SourceLocation RAngleLoc) {
1212  TemplateName Template = TemplateD.getAsVal<TemplateName>();
1213
1214  // FIXME: We're going to end up looking up the template based on its name,
1215  // twice!
1216  DeclarationName Name;
1217  if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
1218    Name = ActualTemplate->getDeclName();
1219  else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
1220    Name = Ovl->getDeclName();
1221  else
1222    assert(false && "Cannot support dependent template names yet");
1223
1224  // Translate the parser's template argument list in our AST format.
1225  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1226  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1227  TemplateArgsIn.release();
1228
1229  // Do we have the save the actual template name? We might need it...
1230  return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, TemplateNameLoc,
1231                                  Name, true, LAngleLoc,
1232                                  TemplateArgs.data(), TemplateArgs.size(),
1233                                  RAngleLoc, DeclPtrTy(), &SS);
1234}
1235
1236/// \brief Form a dependent template name.
1237///
1238/// This action forms a dependent template name given the template
1239/// name and its (presumably dependent) scope specifier. For
1240/// example, given "MetaFun::template apply", the scope specifier \p
1241/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1242/// of the "template" keyword, and "apply" is the \p Name.
1243Sema::TemplateTy
1244Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1245                                 const IdentifierInfo &Name,
1246                                 SourceLocation NameLoc,
1247                                 const CXXScopeSpec &SS,
1248                                 TypeTy *ObjectType) {
1249  if ((ObjectType &&
1250       computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1251      (SS.isSet() && computeDeclContext(SS, false))) {
1252    // C++0x [temp.names]p5:
1253    //   If a name prefixed by the keyword template is not the name of
1254    //   a template, the program is ill-formed. [Note: the keyword
1255    //   template may not be applied to non-template members of class
1256    //   templates. -end note ] [ Note: as is the case with the
1257    //   typename prefix, the template prefix is allowed in cases
1258    //   where it is not strictly necessary; i.e., when the
1259    //   nested-name-specifier or the expression on the left of the ->
1260    //   or . is not dependent on a template-parameter, or the use
1261    //   does not appear in the scope of a template. -end note]
1262    //
1263    // Note: C++03 was more strict here, because it banned the use of
1264    // the "template" keyword prior to a template-name that was not a
1265    // dependent name. C++ DR468 relaxed this requirement (the
1266    // "template" keyword is now permitted). We follow the C++0x
1267    // rules, even in C++03 mode, retroactively applying the DR.
1268    TemplateTy Template;
1269    TemplateNameKind TNK = isTemplateName(0, Name, NameLoc, &SS, ObjectType,
1270                                          false, Template);
1271    if (TNK == TNK_Non_template) {
1272      Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1273        << &Name;
1274      return TemplateTy();
1275    }
1276
1277    return Template;
1278  }
1279
1280  // FIXME: We need to be able to create a dependent template name with just
1281  // an identifier, to handle the x->template f<T> case.
1282  assert(!ObjectType &&
1283      "Cannot handle dependent template names without a nested-name-specifier");
1284
1285  NestedNameSpecifier *Qualifier
1286    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1287  return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1288}
1289
1290bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1291                                     const TemplateArgument &Arg,
1292                                     TemplateArgumentListBuilder &Converted) {
1293  // Check template type parameter.
1294  if (Arg.getKind() != TemplateArgument::Type) {
1295    // C++ [temp.arg.type]p1:
1296    //   A template-argument for a template-parameter which is a
1297    //   type shall be a type-id.
1298
1299    // We have a template type parameter but the template argument
1300    // is not a type.
1301    Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1302    Diag(Param->getLocation(), diag::note_template_param_here);
1303
1304    return true;
1305  }
1306
1307  if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1308    return true;
1309
1310  // Add the converted template type argument.
1311  Converted.Append(
1312                 TemplateArgument(Arg.getLocation(),
1313                                  Context.getCanonicalType(Arg.getAsType())));
1314  return false;
1315}
1316
1317/// \brief Check that the given template argument list is well-formed
1318/// for specializing the given template.
1319bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1320                                     SourceLocation TemplateLoc,
1321                                     SourceLocation LAngleLoc,
1322                                     const TemplateArgument *TemplateArgs,
1323                                     unsigned NumTemplateArgs,
1324                                     SourceLocation RAngleLoc,
1325                                     bool PartialTemplateArgs,
1326                                     TemplateArgumentListBuilder &Converted) {
1327  TemplateParameterList *Params = Template->getTemplateParameters();
1328  unsigned NumParams = Params->size();
1329  unsigned NumArgs = NumTemplateArgs;
1330  bool Invalid = false;
1331
1332  bool HasParameterPack =
1333    NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1334
1335  if ((NumArgs > NumParams && !HasParameterPack) ||
1336      (NumArgs < Params->getMinRequiredArguments() &&
1337       !PartialTemplateArgs)) {
1338    // FIXME: point at either the first arg beyond what we can handle,
1339    // or the '>', depending on whether we have too many or too few
1340    // arguments.
1341    SourceRange Range;
1342    if (NumArgs > NumParams)
1343      Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
1344    Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1345      << (NumArgs > NumParams)
1346      << (isa<ClassTemplateDecl>(Template)? 0 :
1347          isa<FunctionTemplateDecl>(Template)? 1 :
1348          isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1349      << Template << Range;
1350    Diag(Template->getLocation(), diag::note_template_decl_here)
1351      << Params->getSourceRange();
1352    Invalid = true;
1353  }
1354
1355  // C++ [temp.arg]p1:
1356  //   [...] The type and form of each template-argument specified in
1357  //   a template-id shall match the type and form specified for the
1358  //   corresponding parameter declared by the template in its
1359  //   template-parameter-list.
1360  unsigned ArgIdx = 0;
1361  for (TemplateParameterList::iterator Param = Params->begin(),
1362                                       ParamEnd = Params->end();
1363       Param != ParamEnd; ++Param, ++ArgIdx) {
1364    if (ArgIdx > NumArgs && PartialTemplateArgs)
1365      break;
1366
1367    // Decode the template argument
1368    TemplateArgument Arg;
1369    if (ArgIdx >= NumArgs) {
1370      // Retrieve the default template argument from the template
1371      // parameter.
1372      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1373        if (TTP->isParameterPack()) {
1374          // We have an empty argument pack.
1375          Converted.BeginPack();
1376          Converted.EndPack();
1377          break;
1378        }
1379
1380        if (!TTP->hasDefaultArgument())
1381          break;
1382
1383        QualType ArgType = TTP->getDefaultArgument();
1384
1385        // If the argument type is dependent, instantiate it now based
1386        // on the previously-computed template arguments.
1387        if (ArgType->isDependentType()) {
1388          InstantiatingTemplate Inst(*this, TemplateLoc,
1389                                     Template, Converted.getFlatArguments(),
1390                                     Converted.flatSize(),
1391                                     SourceRange(TemplateLoc, RAngleLoc));
1392
1393          TemplateArgumentList TemplateArgs(Context, Converted,
1394                                            /*TakeArgs=*/false);
1395          ArgType = SubstType(ArgType,
1396                              MultiLevelTemplateArgumentList(TemplateArgs),
1397                              TTP->getDefaultArgumentLoc(),
1398                              TTP->getDeclName());
1399        }
1400
1401        if (ArgType.isNull())
1402          return true;
1403
1404        Arg = TemplateArgument(TTP->getLocation(), ArgType);
1405      } else if (NonTypeTemplateParmDecl *NTTP
1406                   = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1407        if (!NTTP->hasDefaultArgument())
1408          break;
1409
1410        InstantiatingTemplate Inst(*this, TemplateLoc,
1411                                   Template, Converted.getFlatArguments(),
1412                                   Converted.flatSize(),
1413                                   SourceRange(TemplateLoc, RAngleLoc));
1414
1415        TemplateArgumentList TemplateArgs(Context, Converted,
1416                                          /*TakeArgs=*/false);
1417
1418        Sema::OwningExprResult E
1419          = SubstExpr(NTTP->getDefaultArgument(),
1420                      MultiLevelTemplateArgumentList(TemplateArgs));
1421        if (E.isInvalid())
1422          return true;
1423
1424        Arg = TemplateArgument(E.takeAs<Expr>());
1425      } else {
1426        TemplateTemplateParmDecl *TempParm
1427          = cast<TemplateTemplateParmDecl>(*Param);
1428
1429        if (!TempParm->hasDefaultArgument())
1430          break;
1431
1432        // FIXME: Subst default argument
1433        Arg = TemplateArgument(TempParm->getDefaultArgument());
1434      }
1435    } else {
1436      // Retrieve the template argument produced by the user.
1437      Arg = TemplateArgs[ArgIdx];
1438    }
1439
1440
1441    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1442      if (TTP->isParameterPack()) {
1443        Converted.BeginPack();
1444        // Check all the remaining arguments (if any).
1445        for (; ArgIdx < NumArgs; ++ArgIdx) {
1446          if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1447            Invalid = true;
1448        }
1449
1450        Converted.EndPack();
1451      } else {
1452        if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1453          Invalid = true;
1454      }
1455    } else if (NonTypeTemplateParmDecl *NTTP
1456                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1457      // Check non-type template parameters.
1458
1459      // Do substitution on the type of the non-type template parameter
1460      // with the template arguments we've seen thus far.
1461      QualType NTTPType = NTTP->getType();
1462      if (NTTPType->isDependentType()) {
1463        // Do substitution on the type of the non-type template parameter.
1464        InstantiatingTemplate Inst(*this, TemplateLoc,
1465                                   Template, Converted.getFlatArguments(),
1466                                   Converted.flatSize(),
1467                                   SourceRange(TemplateLoc, RAngleLoc));
1468
1469        TemplateArgumentList TemplateArgs(Context, Converted,
1470                                          /*TakeArgs=*/false);
1471        NTTPType = SubstType(NTTPType,
1472                             MultiLevelTemplateArgumentList(TemplateArgs),
1473                             NTTP->getLocation(),
1474                             NTTP->getDeclName());
1475        // If that worked, check the non-type template parameter type
1476        // for validity.
1477        if (!NTTPType.isNull())
1478          NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1479                                                       NTTP->getLocation());
1480        if (NTTPType.isNull()) {
1481          Invalid = true;
1482          break;
1483        }
1484      }
1485
1486      switch (Arg.getKind()) {
1487      case TemplateArgument::Null:
1488        assert(false && "Should never see a NULL template argument here");
1489        break;
1490
1491      case TemplateArgument::Expression: {
1492        Expr *E = Arg.getAsExpr();
1493        TemplateArgument Result;
1494        if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1495          Invalid = true;
1496        else
1497          Converted.Append(Result);
1498        break;
1499      }
1500
1501      case TemplateArgument::Declaration:
1502      case TemplateArgument::Integral:
1503        // We've already checked this template argument, so just copy
1504        // it to the list of converted arguments.
1505        Converted.Append(Arg);
1506        break;
1507
1508      case TemplateArgument::Type:
1509        // We have a non-type template parameter but the template
1510        // argument is a type.
1511
1512        // C++ [temp.arg]p2:
1513        //   In a template-argument, an ambiguity between a type-id and
1514        //   an expression is resolved to a type-id, regardless of the
1515        //   form of the corresponding template-parameter.
1516        //
1517        // We warn specifically about this case, since it can be rather
1518        // confusing for users.
1519        if (Arg.getAsType()->isFunctionType())
1520          Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1521            << Arg.getAsType();
1522        else
1523          Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1524        Diag((*Param)->getLocation(), diag::note_template_param_here);
1525        Invalid = true;
1526        break;
1527
1528      case TemplateArgument::Pack:
1529        assert(0 && "FIXME: Implement!");
1530        break;
1531      }
1532    } else {
1533      // Check template template parameters.
1534      TemplateTemplateParmDecl *TempParm
1535        = cast<TemplateTemplateParmDecl>(*Param);
1536
1537      switch (Arg.getKind()) {
1538      case TemplateArgument::Null:
1539        assert(false && "Should never see a NULL template argument here");
1540        break;
1541
1542      case TemplateArgument::Expression: {
1543        Expr *ArgExpr = Arg.getAsExpr();
1544        if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1545            isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1546          if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1547            Invalid = true;
1548
1549          // Add the converted template argument.
1550          Decl *D
1551            = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
1552          Converted.Append(TemplateArgument(Arg.getLocation(), D));
1553          continue;
1554        }
1555      }
1556        // fall through
1557
1558      case TemplateArgument::Type: {
1559        // We have a template template parameter but the template
1560        // argument does not refer to a template.
1561        Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1562        Invalid = true;
1563        break;
1564      }
1565
1566      case TemplateArgument::Declaration:
1567        // We've already checked this template argument, so just copy
1568        // it to the list of converted arguments.
1569        Converted.Append(Arg);
1570        break;
1571
1572      case TemplateArgument::Integral:
1573        assert(false && "Integral argument with template template parameter");
1574        break;
1575
1576      case TemplateArgument::Pack:
1577        assert(0 && "FIXME: Implement!");
1578        break;
1579      }
1580    }
1581  }
1582
1583  return Invalid;
1584}
1585
1586/// \brief Check a template argument against its corresponding
1587/// template type parameter.
1588///
1589/// This routine implements the semantics of C++ [temp.arg.type]. It
1590/// returns true if an error occurred, and false otherwise.
1591bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1592                                 QualType Arg, SourceLocation ArgLoc) {
1593  // C++ [temp.arg.type]p2:
1594  //   A local type, a type with no linkage, an unnamed type or a type
1595  //   compounded from any of these types shall not be used as a
1596  //   template-argument for a template type-parameter.
1597  //
1598  // FIXME: Perform the recursive and no-linkage type checks.
1599  const TagType *Tag = 0;
1600  if (const EnumType *EnumT = Arg->getAsEnumType())
1601    Tag = EnumT;
1602  else if (const RecordType *RecordT = Arg->getAs<RecordType>())
1603    Tag = RecordT;
1604  if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1605    return Diag(ArgLoc, diag::err_template_arg_local_type)
1606      << QualType(Tag, 0);
1607  else if (Tag && !Tag->getDecl()->getDeclName() &&
1608           !Tag->getDecl()->getTypedefForAnonDecl()) {
1609    Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1610    Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1611    return true;
1612  }
1613
1614  return false;
1615}
1616
1617/// \brief Checks whether the given template argument is the address
1618/// of an object or function according to C++ [temp.arg.nontype]p1.
1619bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1620                                                          NamedDecl *&Entity) {
1621  bool Invalid = false;
1622
1623  // See through any implicit casts we added to fix the type.
1624  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1625    Arg = Cast->getSubExpr();
1626
1627  // C++0x allows nullptr, and there's no further checking to be done for that.
1628  if (Arg->getType()->isNullPtrType())
1629    return false;
1630
1631  // C++ [temp.arg.nontype]p1:
1632  //
1633  //   A template-argument for a non-type, non-template
1634  //   template-parameter shall be one of: [...]
1635  //
1636  //     -- the address of an object or function with external
1637  //        linkage, including function templates and function
1638  //        template-ids but excluding non-static class members,
1639  //        expressed as & id-expression where the & is optional if
1640  //        the name refers to a function or array, or if the
1641  //        corresponding template-parameter is a reference; or
1642  DeclRefExpr *DRE = 0;
1643
1644  // Ignore (and complain about) any excess parentheses.
1645  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1646    if (!Invalid) {
1647      Diag(Arg->getSourceRange().getBegin(),
1648           diag::err_template_arg_extra_parens)
1649        << Arg->getSourceRange();
1650      Invalid = true;
1651    }
1652
1653    Arg = Parens->getSubExpr();
1654  }
1655
1656  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1657    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1658      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1659  } else
1660    DRE = dyn_cast<DeclRefExpr>(Arg);
1661
1662  if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1663    return Diag(Arg->getSourceRange().getBegin(),
1664                diag::err_template_arg_not_object_or_func_form)
1665      << Arg->getSourceRange();
1666
1667  // Cannot refer to non-static data members
1668  if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1669    return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1670      << Field << Arg->getSourceRange();
1671
1672  // Cannot refer to non-static member functions
1673  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1674    if (!Method->isStatic())
1675      return Diag(Arg->getSourceRange().getBegin(),
1676                  diag::err_template_arg_method)
1677        << Method << Arg->getSourceRange();
1678
1679  // Functions must have external linkage.
1680  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1681    if (Func->getStorageClass() == FunctionDecl::Static) {
1682      Diag(Arg->getSourceRange().getBegin(),
1683           diag::err_template_arg_function_not_extern)
1684        << Func << Arg->getSourceRange();
1685      Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1686        << true;
1687      return true;
1688    }
1689
1690    // Okay: we've named a function with external linkage.
1691    Entity = Func;
1692    return Invalid;
1693  }
1694
1695  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1696    if (!Var->hasGlobalStorage()) {
1697      Diag(Arg->getSourceRange().getBegin(),
1698           diag::err_template_arg_object_not_extern)
1699        << Var << Arg->getSourceRange();
1700      Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1701        << true;
1702      return true;
1703    }
1704
1705    // Okay: we've named an object with external linkage
1706    Entity = Var;
1707    return Invalid;
1708  }
1709
1710  // We found something else, but we don't know specifically what it is.
1711  Diag(Arg->getSourceRange().getBegin(),
1712       diag::err_template_arg_not_object_or_func)
1713      << Arg->getSourceRange();
1714  Diag(DRE->getDecl()->getLocation(),
1715       diag::note_template_arg_refers_here);
1716  return true;
1717}
1718
1719/// \brief Checks whether the given template argument is a pointer to
1720/// member constant according to C++ [temp.arg.nontype]p1.
1721bool
1722Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
1723  bool Invalid = false;
1724
1725  // See through any implicit casts we added to fix the type.
1726  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1727    Arg = Cast->getSubExpr();
1728
1729  // C++0x allows nullptr, and there's no further checking to be done for that.
1730  if (Arg->getType()->isNullPtrType())
1731    return false;
1732
1733  // C++ [temp.arg.nontype]p1:
1734  //
1735  //   A template-argument for a non-type, non-template
1736  //   template-parameter shall be one of: [...]
1737  //
1738  //     -- a pointer to member expressed as described in 5.3.1.
1739  QualifiedDeclRefExpr *DRE = 0;
1740
1741  // Ignore (and complain about) any excess parentheses.
1742  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1743    if (!Invalid) {
1744      Diag(Arg->getSourceRange().getBegin(),
1745           diag::err_template_arg_extra_parens)
1746        << Arg->getSourceRange();
1747      Invalid = true;
1748    }
1749
1750    Arg = Parens->getSubExpr();
1751  }
1752
1753  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1754    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1755      DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1756
1757  if (!DRE)
1758    return Diag(Arg->getSourceRange().getBegin(),
1759                diag::err_template_arg_not_pointer_to_member_form)
1760      << Arg->getSourceRange();
1761
1762  if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1763    assert((isa<FieldDecl>(DRE->getDecl()) ||
1764            !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1765           "Only non-static member pointers can make it here");
1766
1767    // Okay: this is the address of a non-static member, and therefore
1768    // a member pointer constant.
1769    Member = DRE->getDecl();
1770    return Invalid;
1771  }
1772
1773  // We found something else, but we don't know specifically what it is.
1774  Diag(Arg->getSourceRange().getBegin(),
1775       diag::err_template_arg_not_pointer_to_member_form)
1776      << Arg->getSourceRange();
1777  Diag(DRE->getDecl()->getLocation(),
1778       diag::note_template_arg_refers_here);
1779  return true;
1780}
1781
1782/// \brief Check a template argument against its corresponding
1783/// non-type template parameter.
1784///
1785/// This routine implements the semantics of C++ [temp.arg.nontype].
1786/// It returns true if an error occurred, and false otherwise. \p
1787/// InstantiatedParamType is the type of the non-type template
1788/// parameter after it has been instantiated.
1789///
1790/// If no error was detected, Converted receives the converted template argument.
1791bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
1792                                 QualType InstantiatedParamType, Expr *&Arg,
1793                                 TemplateArgument &Converted) {
1794  SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1795
1796  // If either the parameter has a dependent type or the argument is
1797  // type-dependent, there's nothing we can check now.
1798  // FIXME: Add template argument to Converted!
1799  if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1800    // FIXME: Produce a cloned, canonical expression?
1801    Converted = TemplateArgument(Arg);
1802    return false;
1803  }
1804
1805  // C++ [temp.arg.nontype]p5:
1806  //   The following conversions are performed on each expression used
1807  //   as a non-type template-argument. If a non-type
1808  //   template-argument cannot be converted to the type of the
1809  //   corresponding template-parameter then the program is
1810  //   ill-formed.
1811  //
1812  //     -- for a non-type template-parameter of integral or
1813  //        enumeration type, integral promotions (4.5) and integral
1814  //        conversions (4.7) are applied.
1815  QualType ParamType = InstantiatedParamType;
1816  QualType ArgType = Arg->getType();
1817  if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
1818    // C++ [temp.arg.nontype]p1:
1819    //   A template-argument for a non-type, non-template
1820    //   template-parameter shall be one of:
1821    //
1822    //     -- an integral constant-expression of integral or enumeration
1823    //        type; or
1824    //     -- the name of a non-type template-parameter; or
1825    SourceLocation NonConstantLoc;
1826    llvm::APSInt Value;
1827    if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1828      Diag(Arg->getSourceRange().getBegin(),
1829           diag::err_template_arg_not_integral_or_enumeral)
1830        << ArgType << Arg->getSourceRange();
1831      Diag(Param->getLocation(), diag::note_template_param_here);
1832      return true;
1833    } else if (!Arg->isValueDependent() &&
1834               !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
1835      Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1836        << ArgType << Arg->getSourceRange();
1837      return true;
1838    }
1839
1840    // FIXME: We need some way to more easily get the unqualified form
1841    // of the types without going all the way to the
1842    // canonical type.
1843    if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1844      ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1845    if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1846      ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1847
1848    // Try to convert the argument to the parameter's type.
1849    if (ParamType == ArgType) {
1850      // Okay: no conversion necessary
1851    } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1852               !ParamType->isEnumeralType()) {
1853      // This is an integral promotion or conversion.
1854      ImpCastExprToType(Arg, ParamType);
1855    } else {
1856      // We can't perform this conversion.
1857      Diag(Arg->getSourceRange().getBegin(),
1858           diag::err_template_arg_not_convertible)
1859        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1860      Diag(Param->getLocation(), diag::note_template_param_here);
1861      return true;
1862    }
1863
1864    QualType IntegerType = Context.getCanonicalType(ParamType);
1865    if (const EnumType *Enum = IntegerType->getAsEnumType())
1866      IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
1867
1868    if (!Arg->isValueDependent()) {
1869      // Check that an unsigned parameter does not receive a negative
1870      // value.
1871      if (IntegerType->isUnsignedIntegerType()
1872          && (Value.isSigned() && Value.isNegative())) {
1873        Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1874          << Value.toString(10) << Param->getType()
1875          << Arg->getSourceRange();
1876        Diag(Param->getLocation(), diag::note_template_param_here);
1877        return true;
1878      }
1879
1880      // Check that we don't overflow the template parameter type.
1881      unsigned AllowedBits = Context.getTypeSize(IntegerType);
1882      if (Value.getActiveBits() > AllowedBits) {
1883        Diag(Arg->getSourceRange().getBegin(),
1884             diag::err_template_arg_too_large)
1885          << Value.toString(10) << Param->getType()
1886          << Arg->getSourceRange();
1887        Diag(Param->getLocation(), diag::note_template_param_here);
1888        return true;
1889      }
1890
1891      if (Value.getBitWidth() != AllowedBits)
1892        Value.extOrTrunc(AllowedBits);
1893      Value.setIsSigned(IntegerType->isSignedIntegerType());
1894    }
1895
1896    // Add the value of this argument to the list of converted
1897    // arguments. We use the bitwidth and signedness of the template
1898    // parameter.
1899    if (Arg->isValueDependent()) {
1900      // The argument is value-dependent. Create a new
1901      // TemplateArgument with the converted expression.
1902      Converted = TemplateArgument(Arg);
1903      return false;
1904    }
1905
1906    Converted = TemplateArgument(StartLoc, Value,
1907                                 ParamType->isEnumeralType() ? ParamType
1908                                                             : IntegerType);
1909    return false;
1910  }
1911
1912  // Handle pointer-to-function, reference-to-function, and
1913  // pointer-to-member-function all in (roughly) the same way.
1914  if (// -- For a non-type template-parameter of type pointer to
1915      //    function, only the function-to-pointer conversion (4.3) is
1916      //    applied. If the template-argument represents a set of
1917      //    overloaded functions (or a pointer to such), the matching
1918      //    function is selected from the set (13.4).
1919      // In C++0x, any std::nullptr_t value can be converted.
1920      (ParamType->isPointerType() &&
1921       ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
1922      // -- For a non-type template-parameter of type reference to
1923      //    function, no conversions apply. If the template-argument
1924      //    represents a set of overloaded functions, the matching
1925      //    function is selected from the set (13.4).
1926      (ParamType->isReferenceType() &&
1927       ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
1928      // -- For a non-type template-parameter of type pointer to
1929      //    member function, no conversions apply. If the
1930      //    template-argument represents a set of overloaded member
1931      //    functions, the matching member function is selected from
1932      //    the set (13.4).
1933      // Again, C++0x allows a std::nullptr_t value.
1934      (ParamType->isMemberPointerType() &&
1935       ParamType->getAs<MemberPointerType>()->getPointeeType()
1936         ->isFunctionType())) {
1937    if (Context.hasSameUnqualifiedType(ArgType,
1938                                       ParamType.getNonReferenceType())) {
1939      // We don't have to do anything: the types already match.
1940    } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1941                 ParamType->isMemberPointerType())) {
1942      ArgType = ParamType;
1943      ImpCastExprToType(Arg, ParamType);
1944    } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
1945      ArgType = Context.getPointerType(ArgType);
1946      ImpCastExprToType(Arg, ArgType);
1947    } else if (FunctionDecl *Fn
1948                 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
1949      if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1950        return true;
1951
1952      FixOverloadedFunctionReference(Arg, Fn);
1953      ArgType = Arg->getType();
1954      if (ArgType->isFunctionType() && ParamType->isPointerType()) {
1955        ArgType = Context.getPointerType(Arg->getType());
1956        ImpCastExprToType(Arg, ArgType);
1957      }
1958    }
1959
1960    if (!Context.hasSameUnqualifiedType(ArgType,
1961                                        ParamType.getNonReferenceType())) {
1962      // We can't perform this conversion.
1963      Diag(Arg->getSourceRange().getBegin(),
1964           diag::err_template_arg_not_convertible)
1965        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1966      Diag(Param->getLocation(), diag::note_template_param_here);
1967      return true;
1968    }
1969
1970    if (ParamType->isMemberPointerType()) {
1971      NamedDecl *Member = 0;
1972      if (CheckTemplateArgumentPointerToMember(Arg, Member))
1973        return true;
1974
1975      if (Member)
1976        Member = cast<NamedDecl>(Member->getCanonicalDecl());
1977      Converted = TemplateArgument(StartLoc, Member);
1978      return false;
1979    }
1980
1981    NamedDecl *Entity = 0;
1982    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1983      return true;
1984
1985    if (Entity)
1986      Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
1987    Converted = TemplateArgument(StartLoc, Entity);
1988    return false;
1989  }
1990
1991  if (ParamType->isPointerType()) {
1992    //   -- for a non-type template-parameter of type pointer to
1993    //      object, qualification conversions (4.4) and the
1994    //      array-to-pointer conversion (4.2) are applied.
1995    // C++0x also allows a value of std::nullptr_t.
1996    assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
1997           "Only object pointers allowed here");
1998
1999    if (ArgType->isNullPtrType()) {
2000      ArgType = ParamType;
2001      ImpCastExprToType(Arg, ParamType);
2002    } else if (ArgType->isArrayType()) {
2003      ArgType = Context.getArrayDecayedType(ArgType);
2004      ImpCastExprToType(Arg, ArgType);
2005    }
2006
2007    if (IsQualificationConversion(ArgType, ParamType)) {
2008      ArgType = ParamType;
2009      ImpCastExprToType(Arg, ParamType);
2010    }
2011
2012    if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2013      // We can't perform this conversion.
2014      Diag(Arg->getSourceRange().getBegin(),
2015           diag::err_template_arg_not_convertible)
2016        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2017      Diag(Param->getLocation(), diag::note_template_param_here);
2018      return true;
2019    }
2020
2021    NamedDecl *Entity = 0;
2022    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2023      return true;
2024
2025    if (Entity)
2026      Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2027    Converted = TemplateArgument(StartLoc, Entity);
2028    return false;
2029  }
2030
2031  if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
2032    //   -- For a non-type template-parameter of type reference to
2033    //      object, no conversions apply. The type referred to by the
2034    //      reference may be more cv-qualified than the (otherwise
2035    //      identical) type of the template-argument. The
2036    //      template-parameter is bound directly to the
2037    //      template-argument, which must be an lvalue.
2038    assert(ParamRefType->getPointeeType()->isObjectType() &&
2039           "Only object references allowed here");
2040
2041    if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
2042      Diag(Arg->getSourceRange().getBegin(),
2043           diag::err_template_arg_no_ref_bind)
2044        << InstantiatedParamType << Arg->getType()
2045        << Arg->getSourceRange();
2046      Diag(Param->getLocation(), diag::note_template_param_here);
2047      return true;
2048    }
2049
2050    unsigned ParamQuals
2051      = Context.getCanonicalType(ParamType).getCVRQualifiers();
2052    unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
2053
2054    if ((ParamQuals | ArgQuals) != ParamQuals) {
2055      Diag(Arg->getSourceRange().getBegin(),
2056           diag::err_template_arg_ref_bind_ignores_quals)
2057        << InstantiatedParamType << Arg->getType()
2058        << Arg->getSourceRange();
2059      Diag(Param->getLocation(), diag::note_template_param_here);
2060      return true;
2061    }
2062
2063    NamedDecl *Entity = 0;
2064    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2065      return true;
2066
2067    Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2068    Converted = TemplateArgument(StartLoc, Entity);
2069    return false;
2070  }
2071
2072  //     -- For a non-type template-parameter of type pointer to data
2073  //        member, qualification conversions (4.4) are applied.
2074  // C++0x allows std::nullptr_t values.
2075  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2076
2077  if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
2078    // Types match exactly: nothing more to do here.
2079  } else if (ArgType->isNullPtrType()) {
2080    ImpCastExprToType(Arg, ParamType);
2081  } else if (IsQualificationConversion(ArgType, ParamType)) {
2082    ImpCastExprToType(Arg, ParamType);
2083  } else {
2084    // We can't perform this conversion.
2085    Diag(Arg->getSourceRange().getBegin(),
2086         diag::err_template_arg_not_convertible)
2087      << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2088    Diag(Param->getLocation(), diag::note_template_param_here);
2089    return true;
2090  }
2091
2092  NamedDecl *Member = 0;
2093  if (CheckTemplateArgumentPointerToMember(Arg, Member))
2094    return true;
2095
2096  if (Member)
2097    Member = cast<NamedDecl>(Member->getCanonicalDecl());
2098  Converted = TemplateArgument(StartLoc, Member);
2099  return false;
2100}
2101
2102/// \brief Check a template argument against its corresponding
2103/// template template parameter.
2104///
2105/// This routine implements the semantics of C++ [temp.arg.template].
2106/// It returns true if an error occurred, and false otherwise.
2107bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2108                                 DeclRefExpr *Arg) {
2109  assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2110  TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2111
2112  // C++ [temp.arg.template]p1:
2113  //   A template-argument for a template template-parameter shall be
2114  //   the name of a class template, expressed as id-expression. Only
2115  //   primary class templates are considered when matching the
2116  //   template template argument with the corresponding parameter;
2117  //   partial specializations are not considered even if their
2118  //   parameter lists match that of the template template parameter.
2119  //
2120  // Note that we also allow template template parameters here, which
2121  // will happen when we are dealing with, e.g., class template
2122  // partial specializations.
2123  if (!isa<ClassTemplateDecl>(Template) &&
2124      !isa<TemplateTemplateParmDecl>(Template)) {
2125    assert(isa<FunctionTemplateDecl>(Template) &&
2126           "Only function templates are possible here");
2127    Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2128    Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
2129      << Template;
2130  }
2131
2132  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2133                                         Param->getTemplateParameters(),
2134                                         true, true,
2135                                         Arg->getSourceRange().getBegin());
2136}
2137
2138/// \brief Determine whether the given template parameter lists are
2139/// equivalent.
2140///
2141/// \param New  The new template parameter list, typically written in the
2142/// source code as part of a new template declaration.
2143///
2144/// \param Old  The old template parameter list, typically found via
2145/// name lookup of the template declared with this template parameter
2146/// list.
2147///
2148/// \param Complain  If true, this routine will produce a diagnostic if
2149/// the template parameter lists are not equivalent.
2150///
2151/// \param IsTemplateTemplateParm  If true, this routine is being
2152/// called to compare the template parameter lists of a template
2153/// template parameter.
2154///
2155/// \param TemplateArgLoc If this source location is valid, then we
2156/// are actually checking the template parameter list of a template
2157/// argument (New) against the template parameter list of its
2158/// corresponding template template parameter (Old). We produce
2159/// slightly different diagnostics in this scenario.
2160///
2161/// \returns True if the template parameter lists are equal, false
2162/// otherwise.
2163bool
2164Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2165                                     TemplateParameterList *Old,
2166                                     bool Complain,
2167                                     bool IsTemplateTemplateParm,
2168                                     SourceLocation TemplateArgLoc) {
2169  if (Old->size() != New->size()) {
2170    if (Complain) {
2171      unsigned NextDiag = diag::err_template_param_list_different_arity;
2172      if (TemplateArgLoc.isValid()) {
2173        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2174        NextDiag = diag::note_template_param_list_different_arity;
2175      }
2176      Diag(New->getTemplateLoc(), NextDiag)
2177          << (New->size() > Old->size())
2178          << IsTemplateTemplateParm
2179          << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
2180      Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2181        << IsTemplateTemplateParm
2182        << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2183    }
2184
2185    return false;
2186  }
2187
2188  for (TemplateParameterList::iterator OldParm = Old->begin(),
2189         OldParmEnd = Old->end(), NewParm = New->begin();
2190       OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2191    if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
2192      if (Complain) {
2193        unsigned NextDiag = diag::err_template_param_different_kind;
2194        if (TemplateArgLoc.isValid()) {
2195          Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2196          NextDiag = diag::note_template_param_different_kind;
2197        }
2198        Diag((*NewParm)->getLocation(), NextDiag)
2199        << IsTemplateTemplateParm;
2200        Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2201        << IsTemplateTemplateParm;
2202      }
2203      return false;
2204    }
2205
2206    if (isa<TemplateTypeParmDecl>(*OldParm)) {
2207      // Okay; all template type parameters are equivalent (since we
2208      // know we're at the same index).
2209#if 0
2210      // FIXME: Enable this code in debug mode *after* we properly go through
2211      // and "instantiate" the template parameter lists of template template
2212      // parameters. It's only after this instantiation that (1) any dependent
2213      // types within the template parameter list of the template template
2214      // parameter can be checked, and (2) the template type parameter depths
2215      // will match up.
2216      QualType OldParmType
2217        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
2218      QualType NewParmType
2219        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2220      assert(Context.getCanonicalType(OldParmType) ==
2221             Context.getCanonicalType(NewParmType) &&
2222             "type parameter mismatch?");
2223#endif
2224    } else if (NonTypeTemplateParmDecl *OldNTTP
2225                 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2226      // The types of non-type template parameters must agree.
2227      NonTypeTemplateParmDecl *NewNTTP
2228        = cast<NonTypeTemplateParmDecl>(*NewParm);
2229      if (Context.getCanonicalType(OldNTTP->getType()) !=
2230            Context.getCanonicalType(NewNTTP->getType())) {
2231        if (Complain) {
2232          unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2233          if (TemplateArgLoc.isValid()) {
2234            Diag(TemplateArgLoc,
2235                 diag::err_template_arg_template_params_mismatch);
2236            NextDiag = diag::note_template_nontype_parm_different_type;
2237          }
2238          Diag(NewNTTP->getLocation(), NextDiag)
2239            << NewNTTP->getType()
2240            << IsTemplateTemplateParm;
2241          Diag(OldNTTP->getLocation(),
2242               diag::note_template_nontype_parm_prev_declaration)
2243            << OldNTTP->getType();
2244        }
2245        return false;
2246      }
2247    } else {
2248      // The template parameter lists of template template
2249      // parameters must agree.
2250      // FIXME: Could we perform a faster "type" comparison here?
2251      assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2252             "Only template template parameters handled here");
2253      TemplateTemplateParmDecl *OldTTP
2254        = cast<TemplateTemplateParmDecl>(*OldParm);
2255      TemplateTemplateParmDecl *NewTTP
2256        = cast<TemplateTemplateParmDecl>(*NewParm);
2257      if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2258                                          OldTTP->getTemplateParameters(),
2259                                          Complain,
2260                                          /*IsTemplateTemplateParm=*/true,
2261                                          TemplateArgLoc))
2262        return false;
2263    }
2264  }
2265
2266  return true;
2267}
2268
2269/// \brief Check whether a template can be declared within this scope.
2270///
2271/// If the template declaration is valid in this scope, returns
2272/// false. Otherwise, issues a diagnostic and returns true.
2273bool
2274Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
2275  // Find the nearest enclosing declaration scope.
2276  while ((S->getFlags() & Scope::DeclScope) == 0 ||
2277         (S->getFlags() & Scope::TemplateParamScope) != 0)
2278    S = S->getParent();
2279
2280  // C++ [temp]p2:
2281  //   A template-declaration can appear only as a namespace scope or
2282  //   class scope declaration.
2283  DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
2284  if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2285      cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2286    return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
2287             << TemplateParams->getSourceRange();
2288
2289  while (Ctx && isa<LinkageSpecDecl>(Ctx))
2290    Ctx = Ctx->getParent();
2291
2292  if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2293    return false;
2294
2295  return Diag(TemplateParams->getTemplateLoc(),
2296              diag::err_template_outside_namespace_or_class_scope)
2297    << TemplateParams->getSourceRange();
2298}
2299
2300/// \brief Check whether a class template specialization or explicit
2301/// instantiation in the current context is well-formed.
2302///
2303/// This routine determines whether a class template specialization or
2304/// explicit instantiation can be declared in the current context
2305/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2306/// appropriate diagnostics if there was an error. It returns true if
2307// there was an error that we cannot recover from, and false otherwise.
2308bool
2309Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2310                                   ClassTemplateSpecializationDecl *PrevDecl,
2311                                            SourceLocation TemplateNameLoc,
2312                                            SourceRange ScopeSpecifierRange,
2313                                            bool PartialSpecialization,
2314                                            bool ExplicitInstantiation) {
2315  // C++ [temp.expl.spec]p2:
2316  //   An explicit specialization shall be declared in the namespace
2317  //   of which the template is a member, or, for member templates, in
2318  //   the namespace of which the enclosing class or enclosing class
2319  //   template is a member. An explicit specialization of a member
2320  //   function, member class or static data member of a class
2321  //   template shall be declared in the namespace of which the class
2322  //   template is a member. Such a declaration may also be a
2323  //   definition. If the declaration is not a definition, the
2324  //   specialization may be defined later in the name- space in which
2325  //   the explicit specialization was declared, or in a namespace
2326  //   that encloses the one in which the explicit specialization was
2327  //   declared.
2328  if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2329    int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
2330    Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
2331      << Kind << ClassTemplate;
2332    return true;
2333  }
2334
2335  DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2336  DeclContext *TemplateContext
2337    = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
2338  if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2339      !ExplicitInstantiation) {
2340    // There is no prior declaration of this entity, so this
2341    // specialization must be in the same context as the template
2342    // itself.
2343    if (DC != TemplateContext) {
2344      if (isa<TranslationUnitDecl>(TemplateContext))
2345        Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
2346          << PartialSpecialization
2347          << ClassTemplate << ScopeSpecifierRange;
2348      else if (isa<NamespaceDecl>(TemplateContext))
2349        Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
2350          << PartialSpecialization << ClassTemplate
2351          << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2352
2353      Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2354    }
2355
2356    return false;
2357  }
2358
2359  // We have a previous declaration of this entity. Make sure that
2360  // this redeclaration (or definition) occurs in an enclosing namespace.
2361  if (!CurContext->Encloses(TemplateContext)) {
2362    // FIXME:  In C++98,  we  would like  to  turn these  errors into  warnings,
2363    // dependent on a -Wc++0x flag.
2364    bool SuppressedDiag = false;
2365    int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
2366    if (isa<TranslationUnitDecl>(TemplateContext)) {
2367      if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2368        Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
2369          << Kind << ClassTemplate << ScopeSpecifierRange;
2370      else
2371        SuppressedDiag = true;
2372    } else if (isa<NamespaceDecl>(TemplateContext)) {
2373      if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2374        Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
2375          << Kind << ClassTemplate
2376          << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2377      else
2378        SuppressedDiag = true;
2379    }
2380
2381    if (!SuppressedDiag)
2382      Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2383  }
2384
2385  return false;
2386}
2387
2388/// \brief Check the non-type template arguments of a class template
2389/// partial specialization according to C++ [temp.class.spec]p9.
2390///
2391/// \param TemplateParams the template parameters of the primary class
2392/// template.
2393///
2394/// \param TemplateArg the template arguments of the class template
2395/// partial specialization.
2396///
2397/// \param MirrorsPrimaryTemplate will be set true if the class
2398/// template partial specialization arguments are identical to the
2399/// implicit template arguments of the primary template. This is not
2400/// necessarily an error (C++0x), and it is left to the caller to diagnose
2401/// this condition when it is an error.
2402///
2403/// \returns true if there was an error, false otherwise.
2404bool Sema::CheckClassTemplatePartialSpecializationArgs(
2405                                        TemplateParameterList *TemplateParams,
2406                             const TemplateArgumentListBuilder &TemplateArgs,
2407                                        bool &MirrorsPrimaryTemplate) {
2408  // FIXME: the interface to this function will have to change to
2409  // accommodate variadic templates.
2410  MirrorsPrimaryTemplate = true;
2411
2412  const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
2413
2414  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2415    // Determine whether the template argument list of the partial
2416    // specialization is identical to the implicit argument list of
2417    // the primary template. The caller may need to diagnostic this as
2418    // an error per C++ [temp.class.spec]p9b3.
2419    if (MirrorsPrimaryTemplate) {
2420      if (TemplateTypeParmDecl *TTP
2421            = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2422        if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
2423              Context.getCanonicalType(ArgList[I].getAsType()))
2424          MirrorsPrimaryTemplate = false;
2425      } else if (TemplateTemplateParmDecl *TTP
2426                   = dyn_cast<TemplateTemplateParmDecl>(
2427                                                 TemplateParams->getParam(I))) {
2428        // FIXME: We should settle on either Declaration storage or
2429        // Expression storage for template template parameters.
2430        TemplateTemplateParmDecl *ArgDecl
2431          = dyn_cast_or_null<TemplateTemplateParmDecl>(
2432                                                  ArgList[I].getAsDecl());
2433        if (!ArgDecl)
2434          if (DeclRefExpr *DRE
2435                = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
2436            ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2437
2438        if (!ArgDecl ||
2439            ArgDecl->getIndex() != TTP->getIndex() ||
2440            ArgDecl->getDepth() != TTP->getDepth())
2441          MirrorsPrimaryTemplate = false;
2442      }
2443    }
2444
2445    NonTypeTemplateParmDecl *Param
2446      = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
2447    if (!Param) {
2448      continue;
2449    }
2450
2451    Expr *ArgExpr = ArgList[I].getAsExpr();
2452    if (!ArgExpr) {
2453      MirrorsPrimaryTemplate = false;
2454      continue;
2455    }
2456
2457    // C++ [temp.class.spec]p8:
2458    //   A non-type argument is non-specialized if it is the name of a
2459    //   non-type parameter. All other non-type arguments are
2460    //   specialized.
2461    //
2462    // Below, we check the two conditions that only apply to
2463    // specialized non-type arguments, so skip any non-specialized
2464    // arguments.
2465    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
2466      if (NonTypeTemplateParmDecl *NTTP
2467            = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2468        if (MirrorsPrimaryTemplate &&
2469            (Param->getIndex() != NTTP->getIndex() ||
2470             Param->getDepth() != NTTP->getDepth()))
2471          MirrorsPrimaryTemplate = false;
2472
2473        continue;
2474      }
2475
2476    // C++ [temp.class.spec]p9:
2477    //   Within the argument list of a class template partial
2478    //   specialization, the following restrictions apply:
2479    //     -- A partially specialized non-type argument expression
2480    //        shall not involve a template parameter of the partial
2481    //        specialization except when the argument expression is a
2482    //        simple identifier.
2483    if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2484      Diag(ArgExpr->getLocStart(),
2485           diag::err_dependent_non_type_arg_in_partial_spec)
2486        << ArgExpr->getSourceRange();
2487      return true;
2488    }
2489
2490    //     -- The type of a template parameter corresponding to a
2491    //        specialized non-type argument shall not be dependent on a
2492    //        parameter of the specialization.
2493    if (Param->getType()->isDependentType()) {
2494      Diag(ArgExpr->getLocStart(),
2495           diag::err_dependent_typed_non_type_arg_in_partial_spec)
2496        << Param->getType()
2497        << ArgExpr->getSourceRange();
2498      Diag(Param->getLocation(), diag::note_template_param_here);
2499      return true;
2500    }
2501
2502    MirrorsPrimaryTemplate = false;
2503  }
2504
2505  return false;
2506}
2507
2508Sema::DeclResult
2509Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2510                                       TagUseKind TUK,
2511                                       SourceLocation KWLoc,
2512                                       const CXXScopeSpec &SS,
2513                                       TemplateTy TemplateD,
2514                                       SourceLocation TemplateNameLoc,
2515                                       SourceLocation LAngleLoc,
2516                                       ASTTemplateArgsPtr TemplateArgsIn,
2517                                       SourceLocation *TemplateArgLocs,
2518                                       SourceLocation RAngleLoc,
2519                                       AttributeList *Attr,
2520                               MultiTemplateParamsArg TemplateParameterLists) {
2521  assert(TUK == TUK_Declaration || TUK == TUK_Definition);
2522
2523  // Find the class template we're specializing
2524  TemplateName Name = TemplateD.getAsVal<TemplateName>();
2525  ClassTemplateDecl *ClassTemplate
2526    = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2527
2528  bool isPartialSpecialization = false;
2529
2530  // Check the validity of the template headers that introduce this
2531  // template.
2532  TemplateParameterList *TemplateParams
2533    = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2534                        (TemplateParameterList**)TemplateParameterLists.get(),
2535                                              TemplateParameterLists.size());
2536  if (TemplateParams && TemplateParams->size() > 0) {
2537    isPartialSpecialization = true;
2538
2539    // C++ [temp.class.spec]p10:
2540    //   The template parameter list of a specialization shall not
2541    //   contain default template argument values.
2542    for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2543      Decl *Param = TemplateParams->getParam(I);
2544      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2545        if (TTP->hasDefaultArgument()) {
2546          Diag(TTP->getDefaultArgumentLoc(),
2547               diag::err_default_arg_in_partial_spec);
2548          TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2549        }
2550      } else if (NonTypeTemplateParmDecl *NTTP
2551                   = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2552        if (Expr *DefArg = NTTP->getDefaultArgument()) {
2553          Diag(NTTP->getDefaultArgumentLoc(),
2554               diag::err_default_arg_in_partial_spec)
2555            << DefArg->getSourceRange();
2556          NTTP->setDefaultArgument(0);
2557          DefArg->Destroy(Context);
2558        }
2559      } else {
2560        TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2561        if (Expr *DefArg = TTP->getDefaultArgument()) {
2562          Diag(TTP->getDefaultArgumentLoc(),
2563               diag::err_default_arg_in_partial_spec)
2564            << DefArg->getSourceRange();
2565          TTP->setDefaultArgument(0);
2566          DefArg->Destroy(Context);
2567        }
2568      }
2569    }
2570  } else if (!TemplateParams)
2571    Diag(KWLoc, diag::err_template_spec_needs_header)
2572      << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
2573
2574  // Check that the specialization uses the same tag kind as the
2575  // original template.
2576  TagDecl::TagKind Kind;
2577  switch (TagSpec) {
2578  default: assert(0 && "Unknown tag type!");
2579  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2580  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
2581  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
2582  }
2583  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2584                                    Kind, KWLoc,
2585                                    *ClassTemplate->getIdentifier())) {
2586    Diag(KWLoc, diag::err_use_with_wrong_tag)
2587      << ClassTemplate
2588      << CodeModificationHint::CreateReplacement(KWLoc,
2589                            ClassTemplate->getTemplatedDecl()->getKindName());
2590    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2591         diag::note_previous_use);
2592    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2593  }
2594
2595  // Translate the parser's template argument list in our AST format.
2596  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2597  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2598
2599  // Check that the template argument list is well-formed for this
2600  // template.
2601  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2602                                        TemplateArgs.size());
2603  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
2604                                TemplateArgs.data(), TemplateArgs.size(),
2605                                RAngleLoc, false, Converted))
2606    return true;
2607
2608  assert((Converted.structuredSize() ==
2609            ClassTemplate->getTemplateParameters()->size()) &&
2610         "Converted template argument list is too short!");
2611
2612  // Find the class template (partial) specialization declaration that
2613  // corresponds to these arguments.
2614  llvm::FoldingSetNodeID ID;
2615  if (isPartialSpecialization) {
2616    bool MirrorsPrimaryTemplate;
2617    if (CheckClassTemplatePartialSpecializationArgs(
2618                                         ClassTemplate->getTemplateParameters(),
2619                                         Converted, MirrorsPrimaryTemplate))
2620      return true;
2621
2622    if (MirrorsPrimaryTemplate) {
2623      // C++ [temp.class.spec]p9b3:
2624      //
2625      //   -- The argument list of the specialization shall not be identical
2626      //      to the implicit argument list of the primary template.
2627      Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2628        << (TUK == TUK_Definition)
2629        << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2630                                                           RAngleLoc));
2631      return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
2632                                ClassTemplate->getIdentifier(),
2633                                TemplateNameLoc,
2634                                Attr,
2635                                TemplateParams,
2636                                AS_none);
2637    }
2638
2639    // FIXME: Template parameter list matters, too
2640    ClassTemplatePartialSpecializationDecl::Profile(ID,
2641                                                   Converted.getFlatArguments(),
2642                                                   Converted.flatSize(),
2643                                                    Context);
2644  } else
2645    ClassTemplateSpecializationDecl::Profile(ID,
2646                                             Converted.getFlatArguments(),
2647                                             Converted.flatSize(),
2648                                             Context);
2649  void *InsertPos = 0;
2650  ClassTemplateSpecializationDecl *PrevDecl = 0;
2651
2652  if (isPartialSpecialization)
2653    PrevDecl
2654      = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2655                                                                    InsertPos);
2656  else
2657    PrevDecl
2658      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2659
2660  ClassTemplateSpecializationDecl *Specialization = 0;
2661
2662  // Check whether we can declare a class template specialization in
2663  // the current scope.
2664  if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2665                                            TemplateNameLoc,
2666                                            SS.getRange(),
2667                                            isPartialSpecialization,
2668                                            /*ExplicitInstantiation=*/false))
2669    return true;
2670
2671  // The canonical type
2672  QualType CanonType;
2673  if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2674    // Since the only prior class template specialization with these
2675    // arguments was referenced but not declared, reuse that
2676    // declaration node as our own, updating its source location to
2677    // reflect our new declaration.
2678    Specialization = PrevDecl;
2679    Specialization->setLocation(TemplateNameLoc);
2680    PrevDecl = 0;
2681    CanonType = Context.getTypeDeclType(Specialization);
2682  } else if (isPartialSpecialization) {
2683    // Build the canonical type that describes the converted template
2684    // arguments of the class template partial specialization.
2685    CanonType = Context.getTemplateSpecializationType(
2686                                                  TemplateName(ClassTemplate),
2687                                                  Converted.getFlatArguments(),
2688                                                  Converted.flatSize());
2689
2690    // Create a new class template partial specialization declaration node.
2691    TemplateParameterList *TemplateParams
2692      = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2693    ClassTemplatePartialSpecializationDecl *PrevPartial
2694      = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2695    ClassTemplatePartialSpecializationDecl *Partial
2696      = ClassTemplatePartialSpecializationDecl::Create(Context,
2697                                             ClassTemplate->getDeclContext(),
2698                                                       TemplateNameLoc,
2699                                                       TemplateParams,
2700                                                       ClassTemplate,
2701                                                       Converted,
2702                                                       PrevPartial);
2703
2704    if (PrevPartial) {
2705      ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2706      ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2707    } else {
2708      ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2709    }
2710    Specialization = Partial;
2711
2712    // Check that all of the template parameters of the class template
2713    // partial specialization are deducible from the template
2714    // arguments. If not, this class template partial specialization
2715    // will never be used.
2716    llvm::SmallVector<bool, 8> DeducibleParams;
2717    DeducibleParams.resize(TemplateParams->size());
2718    MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2719    unsigned NumNonDeducible = 0;
2720    for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2721      if (!DeducibleParams[I])
2722        ++NumNonDeducible;
2723
2724    if (NumNonDeducible) {
2725      Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2726        << (NumNonDeducible > 1)
2727        << SourceRange(TemplateNameLoc, RAngleLoc);
2728      for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2729        if (!DeducibleParams[I]) {
2730          NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2731          if (Param->getDeclName())
2732            Diag(Param->getLocation(),
2733                 diag::note_partial_spec_unused_parameter)
2734              << Param->getDeclName();
2735          else
2736            Diag(Param->getLocation(),
2737                 diag::note_partial_spec_unused_parameter)
2738              << std::string("<anonymous>");
2739        }
2740      }
2741    }
2742  } else {
2743    // Create a new class template specialization declaration node for
2744    // this explicit specialization.
2745    Specialization
2746      = ClassTemplateSpecializationDecl::Create(Context,
2747                                             ClassTemplate->getDeclContext(),
2748                                                TemplateNameLoc,
2749                                                ClassTemplate,
2750                                                Converted,
2751                                                PrevDecl);
2752
2753    if (PrevDecl) {
2754      ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2755      ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2756    } else {
2757      ClassTemplate->getSpecializations().InsertNode(Specialization,
2758                                                     InsertPos);
2759    }
2760
2761    CanonType = Context.getTypeDeclType(Specialization);
2762  }
2763
2764  // Note that this is an explicit specialization.
2765  Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2766
2767  // Check that this isn't a redefinition of this specialization.
2768  if (TUK == TUK_Definition) {
2769    if (RecordDecl *Def = Specialization->getDefinition(Context)) {
2770      // FIXME: Should also handle explicit specialization after implicit
2771      // instantiation with a special diagnostic.
2772      SourceRange Range(TemplateNameLoc, RAngleLoc);
2773      Diag(TemplateNameLoc, diag::err_redefinition)
2774        << Context.getTypeDeclType(Specialization) << Range;
2775      Diag(Def->getLocation(), diag::note_previous_definition);
2776      Specialization->setInvalidDecl();
2777      return true;
2778    }
2779  }
2780
2781  // Build the fully-sugared type for this class template
2782  // specialization as the user wrote in the specialization
2783  // itself. This means that we'll pretty-print the type retrieved
2784  // from the specialization's declaration the way that the user
2785  // actually wrote the specialization, rather than formatting the
2786  // name based on the "canonical" representation used to store the
2787  // template arguments in the specialization.
2788  QualType WrittenTy
2789    = Context.getTemplateSpecializationType(Name,
2790                                            TemplateArgs.data(),
2791                                            TemplateArgs.size(),
2792                                            CanonType);
2793  Specialization->setTypeAsWritten(WrittenTy);
2794  TemplateArgsIn.release();
2795
2796  // C++ [temp.expl.spec]p9:
2797  //   A template explicit specialization is in the scope of the
2798  //   namespace in which the template was defined.
2799  //
2800  // We actually implement this paragraph where we set the semantic
2801  // context (in the creation of the ClassTemplateSpecializationDecl),
2802  // but we also maintain the lexical context where the actual
2803  // definition occurs.
2804  Specialization->setLexicalDeclContext(CurContext);
2805
2806  // We may be starting the definition of this specialization.
2807  if (TUK == TUK_Definition)
2808    Specialization->startDefinition();
2809
2810  // Add the specialization into its lexical context, so that it can
2811  // be seen when iterating through the list of declarations in that
2812  // context. However, specializations are not found by name lookup.
2813  CurContext->addDecl(Specialization);
2814  return DeclPtrTy::make(Specialization);
2815}
2816
2817Sema::DeclPtrTy
2818Sema::ActOnTemplateDeclarator(Scope *S,
2819                              MultiTemplateParamsArg TemplateParameterLists,
2820                              Declarator &D) {
2821  return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2822}
2823
2824Sema::DeclPtrTy
2825Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2826                               MultiTemplateParamsArg TemplateParameterLists,
2827                                      Declarator &D) {
2828  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2829  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2830         "Not a function declarator!");
2831  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2832
2833  if (FTI.hasPrototype) {
2834    // FIXME: Diagnose arguments without names in C.
2835  }
2836
2837  Scope *ParentScope = FnBodyScope->getParent();
2838
2839  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2840                                  move(TemplateParameterLists),
2841                                  /*IsFunctionDefinition=*/true);
2842  if (FunctionTemplateDecl *FunctionTemplate
2843        = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
2844    return ActOnStartOfFunctionDef(FnBodyScope,
2845                      DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
2846  if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2847    return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
2848  return DeclPtrTy();
2849}
2850
2851// Explicit instantiation of a class template specialization
2852// FIXME: Implement extern template semantics
2853Sema::DeclResult
2854Sema::ActOnExplicitInstantiation(Scope *S,
2855                                 SourceLocation ExternLoc,
2856                                 SourceLocation TemplateLoc,
2857                                 unsigned TagSpec,
2858                                 SourceLocation KWLoc,
2859                                 const CXXScopeSpec &SS,
2860                                 TemplateTy TemplateD,
2861                                 SourceLocation TemplateNameLoc,
2862                                 SourceLocation LAngleLoc,
2863                                 ASTTemplateArgsPtr TemplateArgsIn,
2864                                 SourceLocation *TemplateArgLocs,
2865                                 SourceLocation RAngleLoc,
2866                                 AttributeList *Attr) {
2867  // Find the class template we're specializing
2868  TemplateName Name = TemplateD.getAsVal<TemplateName>();
2869  ClassTemplateDecl *ClassTemplate
2870    = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2871
2872  // Check that the specialization uses the same tag kind as the
2873  // original template.
2874  TagDecl::TagKind Kind;
2875  switch (TagSpec) {
2876  default: assert(0 && "Unknown tag type!");
2877  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2878  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
2879  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
2880  }
2881  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2882                                    Kind, KWLoc,
2883                                    *ClassTemplate->getIdentifier())) {
2884    Diag(KWLoc, diag::err_use_with_wrong_tag)
2885      << ClassTemplate
2886      << CodeModificationHint::CreateReplacement(KWLoc,
2887                            ClassTemplate->getTemplatedDecl()->getKindName());
2888    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2889         diag::note_previous_use);
2890    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2891  }
2892
2893  // C++0x [temp.explicit]p2:
2894  //   [...] An explicit instantiation shall appear in an enclosing
2895  //   namespace of its template. [...]
2896  //
2897  // This is C++ DR 275.
2898  if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2899                                            TemplateNameLoc,
2900                                            SS.getRange(),
2901                                            /*PartialSpecialization=*/false,
2902                                            /*ExplicitInstantiation=*/true))
2903    return true;
2904
2905  // Translate the parser's template argument list in our AST format.
2906  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2907  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2908
2909  // Check that the template argument list is well-formed for this
2910  // template.
2911  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2912                                        TemplateArgs.size());
2913  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
2914                                TemplateArgs.data(), TemplateArgs.size(),
2915                                RAngleLoc, false, Converted))
2916    return true;
2917
2918  assert((Converted.structuredSize() ==
2919            ClassTemplate->getTemplateParameters()->size()) &&
2920         "Converted template argument list is too short!");
2921
2922  // Find the class template specialization declaration that
2923  // corresponds to these arguments.
2924  llvm::FoldingSetNodeID ID;
2925  ClassTemplateSpecializationDecl::Profile(ID,
2926                                           Converted.getFlatArguments(),
2927                                           Converted.flatSize(),
2928                                           Context);
2929  void *InsertPos = 0;
2930  ClassTemplateSpecializationDecl *PrevDecl
2931    = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2932
2933  ClassTemplateSpecializationDecl *Specialization = 0;
2934
2935  bool SpecializationRequiresInstantiation = true;
2936  if (PrevDecl) {
2937    if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
2938      // This particular specialization has already been declared or
2939      // instantiated. We cannot explicitly instantiate it.
2940      Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2941        << Context.getTypeDeclType(PrevDecl);
2942      Diag(PrevDecl->getLocation(),
2943           diag::note_previous_explicit_instantiation);
2944      return DeclPtrTy::make(PrevDecl);
2945    }
2946
2947    if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
2948      // C++ DR 259, C++0x [temp.explicit]p4:
2949      //   For a given set of template parameters, if an explicit
2950      //   instantiation of a template appears after a declaration of
2951      //   an explicit specialization for that template, the explicit
2952      //   instantiation has no effect.
2953      if (!getLangOptions().CPlusPlus0x) {
2954        Diag(TemplateNameLoc,
2955             diag::ext_explicit_instantiation_after_specialization)
2956          << Context.getTypeDeclType(PrevDecl);
2957        Diag(PrevDecl->getLocation(),
2958             diag::note_previous_template_specialization);
2959      }
2960
2961      // Create a new class template specialization declaration node
2962      // for this explicit specialization. This node is only used to
2963      // record the existence of this explicit instantiation for
2964      // accurate reproduction of the source code; we don't actually
2965      // use it for anything, since it is semantically irrelevant.
2966      Specialization
2967        = ClassTemplateSpecializationDecl::Create(Context,
2968                                             ClassTemplate->getDeclContext(),
2969                                                  TemplateNameLoc,
2970                                                  ClassTemplate,
2971                                                  Converted, 0);
2972      Specialization->setLexicalDeclContext(CurContext);
2973      CurContext->addDecl(Specialization);
2974      return DeclPtrTy::make(Specialization);
2975    }
2976
2977    // If we have already (implicitly) instantiated this
2978    // specialization, there is less work to do.
2979    if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2980      SpecializationRequiresInstantiation = false;
2981
2982    // Since the only prior class template specialization with these
2983    // arguments was referenced but not declared, reuse that
2984    // declaration node as our own, updating its source location to
2985    // reflect our new declaration.
2986    Specialization = PrevDecl;
2987    Specialization->setLocation(TemplateNameLoc);
2988    PrevDecl = 0;
2989  } else {
2990    // Create a new class template specialization declaration node for
2991    // this explicit specialization.
2992    Specialization
2993      = ClassTemplateSpecializationDecl::Create(Context,
2994                                             ClassTemplate->getDeclContext(),
2995                                                TemplateNameLoc,
2996                                                ClassTemplate,
2997                                                Converted, 0);
2998
2999    ClassTemplate->getSpecializations().InsertNode(Specialization,
3000                                                   InsertPos);
3001  }
3002
3003  // Build the fully-sugared type for this explicit instantiation as
3004  // the user wrote in the explicit instantiation itself. This means
3005  // that we'll pretty-print the type retrieved from the
3006  // specialization's declaration the way that the user actually wrote
3007  // the explicit instantiation, rather than formatting the name based
3008  // on the "canonical" representation used to store the template
3009  // arguments in the specialization.
3010  QualType WrittenTy
3011    = Context.getTemplateSpecializationType(Name,
3012                                            TemplateArgs.data(),
3013                                            TemplateArgs.size(),
3014                                  Context.getTypeDeclType(Specialization));
3015  Specialization->setTypeAsWritten(WrittenTy);
3016  TemplateArgsIn.release();
3017
3018  // Add the explicit instantiation into its lexical context. However,
3019  // since explicit instantiations are never found by name lookup, we
3020  // just put it into the declaration context directly.
3021  Specialization->setLexicalDeclContext(CurContext);
3022  CurContext->addDecl(Specialization);
3023
3024  // C++ [temp.explicit]p3:
3025  //   A definition of a class template or class member template
3026  //   shall be in scope at the point of the explicit instantiation of
3027  //   the class template or class member template.
3028  //
3029  // This check comes when we actually try to perform the
3030  // instantiation.
3031  if (SpecializationRequiresInstantiation)
3032    InstantiateClassTemplateSpecialization(Specialization, true);
3033  else // Instantiate the members of this class template specialization.
3034    InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
3035
3036  return DeclPtrTy::make(Specialization);
3037}
3038
3039// Explicit instantiation of a member class of a class template.
3040// FIXME: Implement extern template semantics.
3041Sema::DeclResult
3042Sema::ActOnExplicitInstantiation(Scope *S,
3043                                 SourceLocation ExternLoc,
3044                                 SourceLocation TemplateLoc,
3045                                 unsigned TagSpec,
3046                                 SourceLocation KWLoc,
3047                                 const CXXScopeSpec &SS,
3048                                 IdentifierInfo *Name,
3049                                 SourceLocation NameLoc,
3050                                 AttributeList *Attr) {
3051
3052  bool Owned = false;
3053  DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
3054                            KWLoc, SS, Name, NameLoc, Attr, AS_none,
3055                            MultiTemplateParamsArg(*this, 0, 0), Owned);
3056  if (!TagD)
3057    return true;
3058
3059  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3060  if (Tag->isEnum()) {
3061    Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3062      << Context.getTypeDeclType(Tag);
3063    return true;
3064  }
3065
3066  if (Tag->isInvalidDecl())
3067    return true;
3068
3069  CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3070  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3071  if (!Pattern) {
3072    Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3073      << Context.getTypeDeclType(Record);
3074    Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3075    return true;
3076  }
3077
3078  // C++0x [temp.explicit]p2:
3079  //   [...] An explicit instantiation shall appear in an enclosing
3080  //   namespace of its template. [...]
3081  //
3082  // This is C++ DR 275.
3083  if (getLangOptions().CPlusPlus0x) {
3084    // FIXME: In C++98, we would like to turn these errors into warnings,
3085    // dependent on a -Wc++0x flag.
3086    DeclContext *PatternContext
3087      = Pattern->getDeclContext()->getEnclosingNamespaceContext();
3088    if (!CurContext->Encloses(PatternContext)) {
3089      Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
3090        << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
3091      Diag(Pattern->getLocation(), diag::note_previous_declaration);
3092    }
3093  }
3094
3095  if (!Record->getDefinition(Context)) {
3096    // If the class has a definition, instantiate it (and all of its
3097    // members, recursively).
3098    Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
3099    if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
3100                                    getTemplateInstantiationArgs(Record),
3101                                    /*ExplicitInstantiation=*/true))
3102      return true;
3103  } else // Instantiate all of the members of the class.
3104    InstantiateClassMembers(TemplateLoc, Record,
3105                            getTemplateInstantiationArgs(Record));
3106
3107  // FIXME: We don't have any representation for explicit instantiations of
3108  // member classes. Such a representation is not needed for compilation, but it
3109  // should be available for clients that want to see all of the declarations in
3110  // the source code.
3111  return TagD;
3112}
3113
3114Sema::TypeResult
3115Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3116                        const IdentifierInfo &II, SourceLocation IdLoc) {
3117  NestedNameSpecifier *NNS
3118    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3119  if (!NNS)
3120    return true;
3121
3122  QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
3123  if (T.isNull())
3124    return true;
3125  return T.getAsOpaquePtr();
3126}
3127
3128Sema::TypeResult
3129Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3130                        SourceLocation TemplateLoc, TypeTy *Ty) {
3131  QualType T = GetTypeFromParser(Ty);
3132  NestedNameSpecifier *NNS
3133    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3134  const TemplateSpecializationType *TemplateId
3135    = T->getAsTemplateSpecializationType();
3136  assert(TemplateId && "Expected a template specialization type");
3137
3138  if (computeDeclContext(SS, false)) {
3139    // If we can compute a declaration context, then the "typename"
3140    // keyword was superfluous. Just build a QualifiedNameType to keep
3141    // track of the nested-name-specifier.
3142
3143    // FIXME: Note that the QualifiedNameType had the "typename" keyword!
3144    return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
3145  }
3146
3147  return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
3148}
3149
3150/// \brief Build the type that describes a C++ typename specifier,
3151/// e.g., "typename T::type".
3152QualType
3153Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
3154                        SourceRange Range) {
3155  CXXRecordDecl *CurrentInstantiation = 0;
3156  if (NNS->isDependent()) {
3157    CurrentInstantiation = getCurrentInstantiationOf(NNS);
3158
3159    // If the nested-name-specifier does not refer to the current
3160    // instantiation, then build a typename type.
3161    if (!CurrentInstantiation)
3162      return Context.getTypenameType(NNS, &II);
3163
3164    // The nested-name-specifier refers to the current instantiation, so the
3165    // "typename" keyword itself is superfluous. In C++03, the program is
3166    // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
3167    // extraneous "typename" keywords, and we retroactively apply this DR to
3168    // C++03 code.
3169  }
3170
3171  DeclContext *Ctx = 0;
3172
3173  if (CurrentInstantiation)
3174    Ctx = CurrentInstantiation;
3175  else {
3176    CXXScopeSpec SS;
3177    SS.setScopeRep(NNS);
3178    SS.setRange(Range);
3179    if (RequireCompleteDeclContext(SS))
3180      return QualType();
3181
3182    Ctx = computeDeclContext(SS);
3183  }
3184  assert(Ctx && "No declaration context?");
3185
3186  DeclarationName Name(&II);
3187  LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
3188                                            false);
3189  unsigned DiagID = 0;
3190  Decl *Referenced = 0;
3191  switch (Result.getKind()) {
3192  case LookupResult::NotFound:
3193    if (Ctx->isTranslationUnit())
3194      DiagID = diag::err_typename_nested_not_found_global;
3195    else
3196      DiagID = diag::err_typename_nested_not_found;
3197    break;
3198
3199  case LookupResult::Found:
3200    if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3201      // We found a type. Build a QualifiedNameType, since the
3202      // typename-specifier was just sugar. FIXME: Tell
3203      // QualifiedNameType that it has a "typename" prefix.
3204      return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3205    }
3206
3207    DiagID = diag::err_typename_nested_not_type;
3208    Referenced = Result.getAsDecl();
3209    break;
3210
3211  case LookupResult::FoundOverloaded:
3212    DiagID = diag::err_typename_nested_not_type;
3213    Referenced = *Result.begin();
3214    break;
3215
3216  case LookupResult::AmbiguousBaseSubobjectTypes:
3217  case LookupResult::AmbiguousBaseSubobjects:
3218  case LookupResult::AmbiguousReference:
3219    DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3220    return QualType();
3221  }
3222
3223  // If we get here, it's because name lookup did not find a
3224  // type. Emit an appropriate diagnostic and return an error.
3225  if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3226    Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3227  else
3228    Diag(Range.getEnd(), DiagID) << Range << Name;
3229  if (Referenced)
3230    Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3231      << Name;
3232  return QualType();
3233}
3234
3235namespace {
3236  // See Sema::RebuildTypeInCurrentInstantiation
3237  class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3238    : public TreeTransform<CurrentInstantiationRebuilder>
3239  {
3240    SourceLocation Loc;
3241    DeclarationName Entity;
3242
3243  public:
3244    CurrentInstantiationRebuilder(Sema &SemaRef,
3245                                  SourceLocation Loc,
3246                                  DeclarationName Entity)
3247    : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
3248      Loc(Loc), Entity(Entity) { }
3249
3250    /// \brief Determine whether the given type \p T has already been
3251    /// transformed.
3252    ///
3253    /// For the purposes of type reconstruction, a type has already been
3254    /// transformed if it is NULL or if it is not dependent.
3255    bool AlreadyTransformed(QualType T) {
3256      return T.isNull() || !T->isDependentType();
3257    }
3258
3259    /// \brief Returns the location of the entity whose type is being
3260    /// rebuilt.
3261    SourceLocation getBaseLocation() { return Loc; }
3262
3263    /// \brief Returns the name of the entity whose type is being rebuilt.
3264    DeclarationName getBaseEntity() { return Entity; }
3265
3266    /// \brief Transforms an expression by returning the expression itself
3267    /// (an identity function).
3268    ///
3269    /// FIXME: This is completely unsafe; we will need to actually clone the
3270    /// expressions.
3271    Sema::OwningExprResult TransformExpr(Expr *E) {
3272      return getSema().Owned(E);
3273    }
3274
3275    /// \brief Transforms a typename type by determining whether the type now
3276    /// refers to a member of the current instantiation, and then
3277    /// type-checking and building a QualifiedNameType (when possible).
3278    QualType TransformTypenameType(const TypenameType *T);
3279  };
3280}
3281
3282QualType
3283CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3284  NestedNameSpecifier *NNS
3285    = TransformNestedNameSpecifier(T->getQualifier(),
3286                              /*FIXME:*/SourceRange(getBaseLocation()));
3287  if (!NNS)
3288    return QualType();
3289
3290  // If the nested-name-specifier did not change, and we cannot compute the
3291  // context corresponding to the nested-name-specifier, then this
3292  // typename type will not change; exit early.
3293  CXXScopeSpec SS;
3294  SS.setRange(SourceRange(getBaseLocation()));
3295  SS.setScopeRep(NNS);
3296  if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3297    return QualType(T, 0);
3298
3299  // Rebuild the typename type, which will probably turn into a
3300  // QualifiedNameType.
3301  if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
3302    QualType NewTemplateId
3303      = TransformType(QualType(TemplateId, 0));
3304    if (NewTemplateId.isNull())
3305      return QualType();
3306
3307    if (NNS == T->getQualifier() &&
3308        NewTemplateId == QualType(TemplateId, 0))
3309      return QualType(T, 0);
3310
3311    return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3312  }
3313
3314  return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3315}
3316
3317/// \brief Rebuilds a type within the context of the current instantiation.
3318///
3319/// The type \p T is part of the type of an out-of-line member definition of
3320/// a class template (or class template partial specialization) that was parsed
3321/// and constructed before we entered the scope of the class template (or
3322/// partial specialization thereof). This routine will rebuild that type now
3323/// that we have entered the declarator's scope, which may produce different
3324/// canonical types, e.g.,
3325///
3326/// \code
3327/// template<typename T>
3328/// struct X {
3329///   typedef T* pointer;
3330///   pointer data();
3331/// };
3332///
3333/// template<typename T>
3334/// typename X<T>::pointer X<T>::data() { ... }
3335/// \endcode
3336///
3337/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3338/// since we do not know that we can look into X<T> when we parsed the type.
3339/// This function will rebuild the type, performing the lookup of "pointer"
3340/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3341/// as the canonical type of T*, allowing the return types of the out-of-line
3342/// definition and the declaration to match.
3343QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3344                                                 DeclarationName Name) {
3345  if (T.isNull() || !T->isDependentType())
3346    return T;
3347
3348  CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3349  return Rebuilder.TransformType(T);
3350}
3351