SemaTemplate.cpp revision fb25052736439d72a557cddd41dfb927bcb3d3e5
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4//                     The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
8//===----------------------------------------------------------------------===/
9
10//
11//  This file implements semantic analysis for C++ templates.
12//===----------------------------------------------------------------------===/
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
24/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
29TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
30                                      TemplateTy &TemplateResult,
31                                      const CXXScopeSpec *SS) {
32  NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
33
34  TemplateNameKind TNK = TNK_Non_template;
35  TemplateDecl *Template = 0;
36
37  if (IIDecl) {
38    if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
39      if (isa<FunctionTemplateDecl>(IIDecl))
40        TNK = TNK_Function_template;
41      else if (isa<ClassTemplateDecl>(IIDecl) ||
42               isa<TemplateTemplateParmDecl>(IIDecl))
43        TNK = TNK_Type_template;
44      else
45        assert(false && "Unknown template declaration kind");
46    } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
47      // C++ [temp.local]p1:
48      //   Like normal (non-template) classes, class templates have an
49      //   injected-class-name (Clause 9). The injected-class-name
50      //   can be used with or without a template-argument-list. When
51      //   it is used without a template-argument-list, it is
52      //   equivalent to the injected-class-name followed by the
53      //   template-parameters of the class template enclosed in
54      //   <>. When it is used with a template-argument-list, it
55      //   refers to the specified class template specialization,
56      //   which could be the current specialization or another
57      //   specialization.
58      if (Record->isInjectedClassName()) {
59        Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
60        if ((Template = Record->getDescribedClassTemplate()))
61          TNK = TNK_Type_template;
62        else if (ClassTemplateSpecializationDecl *Spec
63                   = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
64          Template = Spec->getSpecializedTemplate();
65          TNK = TNK_Type_template;
66        }
67      }
68    }
69
70    // FIXME: What follows is a gross hack.
71    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
72      if (FD->getType()->isDependentType()) {
73        TemplateResult = TemplateTy::make(FD);
74        return TNK_Function_template;
75      }
76    } else if (OverloadedFunctionDecl *Ovl
77                 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
78      for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
79                                                  FEnd = Ovl->function_end();
80           F != FEnd; ++F) {
81        if ((*F)->getType()->isDependentType()) {
82          TemplateResult = TemplateTy::make(Ovl);
83          return TNK_Function_template;
84        }
85      }
86    }
87
88    if (TNK != TNK_Non_template) {
89      if (SS && SS->isSet() && !SS->isInvalid()) {
90        NestedNameSpecifier *Qualifier
91          = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
92        TemplateResult
93          = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
94                                                              false,
95                                                              Template));
96      } else
97        TemplateResult = TemplateTy::make(TemplateName(Template));
98    }
99  }
100  return TNK;
101}
102
103/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
104/// that the template parameter 'PrevDecl' is being shadowed by a new
105/// declaration at location Loc. Returns true to indicate that this is
106/// an error, and false otherwise.
107bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
108  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
109
110  // Microsoft Visual C++ permits template parameters to be shadowed.
111  if (getLangOptions().Microsoft)
112    return false;
113
114  // C++ [temp.local]p4:
115  //   A template-parameter shall not be redeclared within its
116  //   scope (including nested scopes).
117  Diag(Loc, diag::err_template_param_shadow)
118    << cast<NamedDecl>(PrevDecl)->getDeclName();
119  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
120  return true;
121}
122
123/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
124/// the parameter D to reference the templated declaration and return a pointer
125/// to the template declaration. Otherwise, do nothing to D and return null.
126TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
127  if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
128    D = DeclPtrTy::make(Temp->getTemplatedDecl());
129    return Temp;
130  }
131  return 0;
132}
133
134/// ActOnTypeParameter - Called when a C++ template type parameter
135/// (e.g., "typename T") has been parsed. Typename specifies whether
136/// the keyword "typename" was used to declare the type parameter
137/// (otherwise, "class" was used), and KeyLoc is the location of the
138/// "class" or "typename" keyword. ParamName is the name of the
139/// parameter (NULL indicates an unnamed template parameter) and
140/// ParamName is the location of the parameter name (if any).
141/// If the type parameter has a default argument, it will be added
142/// later via ActOnTypeParameterDefault.
143Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
144                                         SourceLocation EllipsisLoc,
145                                         SourceLocation KeyLoc,
146                                         IdentifierInfo *ParamName,
147                                         SourceLocation ParamNameLoc,
148                                         unsigned Depth, unsigned Position) {
149  assert(S->isTemplateParamScope() &&
150	 "Template type parameter not in template parameter scope!");
151  bool Invalid = false;
152
153  if (ParamName) {
154    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
155    if (PrevDecl && PrevDecl->isTemplateParameter())
156      Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
157							   PrevDecl);
158  }
159
160  SourceLocation Loc = ParamNameLoc;
161  if (!ParamName)
162    Loc = KeyLoc;
163
164  TemplateTypeParmDecl *Param
165    = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
166                                   Depth, Position, ParamName, Typename,
167                                   Ellipsis);
168  if (Invalid)
169    Param->setInvalidDecl();
170
171  if (ParamName) {
172    // Add the template parameter into the current scope.
173    S->AddDecl(DeclPtrTy::make(Param));
174    IdResolver.AddDecl(Param);
175  }
176
177  return DeclPtrTy::make(Param);
178}
179
180/// ActOnTypeParameterDefault - Adds a default argument (the type
181/// Default) to the given template type parameter (TypeParam).
182void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
183                                     SourceLocation EqualLoc,
184                                     SourceLocation DefaultLoc,
185                                     TypeTy *DefaultT) {
186  TemplateTypeParmDecl *Parm
187    = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
188  QualType Default = QualType::getFromOpaquePtr(DefaultT);
189
190  // C++0x [temp.param]p9:
191  // A default template-argument may be specified for any kind of
192  // template-parameter that is not a template parameter pack.
193  if (Parm->isParameterPack()) {
194    Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
195    return;
196  }
197
198  // C++ [temp.param]p14:
199  //   A template-parameter shall not be used in its own default argument.
200  // FIXME: Implement this check! Needs a recursive walk over the types.
201
202  // Check the template argument itself.
203  if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
204    Parm->setInvalidDecl();
205    return;
206  }
207
208  Parm->setDefaultArgument(Default, DefaultLoc, false);
209}
210
211/// \brief Check that the type of a non-type template parameter is
212/// well-formed.
213///
214/// \returns the (possibly-promoted) parameter type if valid;
215/// otherwise, produces a diagnostic and returns a NULL type.
216QualType
217Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
218  // C++ [temp.param]p4:
219  //
220  // A non-type template-parameter shall have one of the following
221  // (optionally cv-qualified) types:
222  //
223  //       -- integral or enumeration type,
224  if (T->isIntegralType() || T->isEnumeralType() ||
225      //   -- pointer to object or pointer to function,
226      (T->isPointerType() &&
227       (T->getAsPointerType()->getPointeeType()->isObjectType() ||
228        T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
229      //   -- reference to object or reference to function,
230      T->isReferenceType() ||
231      //   -- pointer to member.
232      T->isMemberPointerType() ||
233      // If T is a dependent type, we can't do the check now, so we
234      // assume that it is well-formed.
235      T->isDependentType())
236    return T;
237  // C++ [temp.param]p8:
238  //
239  //   A non-type template-parameter of type "array of T" or
240  //   "function returning T" is adjusted to be of type "pointer to
241  //   T" or "pointer to function returning T", respectively.
242  else if (T->isArrayType())
243    // FIXME: Keep the type prior to promotion?
244    return Context.getArrayDecayedType(T);
245  else if (T->isFunctionType())
246    // FIXME: Keep the type prior to promotion?
247    return Context.getPointerType(T);
248
249  Diag(Loc, diag::err_template_nontype_parm_bad_type)
250    << T;
251
252  return QualType();
253}
254
255/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
256/// template parameter (e.g., "int Size" in "template<int Size>
257/// class Array") has been parsed. S is the current scope and D is
258/// the parsed declarator.
259Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
260                                                    unsigned Depth,
261                                                    unsigned Position) {
262  QualType T = GetTypeForDeclarator(D, S);
263
264  assert(S->isTemplateParamScope() &&
265         "Non-type template parameter not in template parameter scope!");
266  bool Invalid = false;
267
268  IdentifierInfo *ParamName = D.getIdentifier();
269  if (ParamName) {
270    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
271    if (PrevDecl && PrevDecl->isTemplateParameter())
272      Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
273                                                           PrevDecl);
274  }
275
276  T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
277  if (T.isNull()) {
278    T = Context.IntTy; // Recover with an 'int' type.
279    Invalid = true;
280  }
281
282  NonTypeTemplateParmDecl *Param
283    = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
284                                      Depth, Position, ParamName, T);
285  if (Invalid)
286    Param->setInvalidDecl();
287
288  if (D.getIdentifier()) {
289    // Add the template parameter into the current scope.
290    S->AddDecl(DeclPtrTy::make(Param));
291    IdResolver.AddDecl(Param);
292  }
293  return DeclPtrTy::make(Param);
294}
295
296/// \brief Adds a default argument to the given non-type template
297/// parameter.
298void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
299                                                SourceLocation EqualLoc,
300                                                ExprArg DefaultE) {
301  NonTypeTemplateParmDecl *TemplateParm
302    = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
303  Expr *Default = static_cast<Expr *>(DefaultE.get());
304
305  // C++ [temp.param]p14:
306  //   A template-parameter shall not be used in its own default argument.
307  // FIXME: Implement this check! Needs a recursive walk over the types.
308
309  // Check the well-formedness of the default template argument.
310  TemplateArgument Converted;
311  if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
312                            Converted)) {
313    TemplateParm->setInvalidDecl();
314    return;
315  }
316
317  TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
318}
319
320
321/// ActOnTemplateTemplateParameter - Called when a C++ template template
322/// parameter (e.g. T in template <template <typename> class T> class array)
323/// has been parsed. S is the current scope.
324Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
325                                                     SourceLocation TmpLoc,
326                                                     TemplateParamsTy *Params,
327                                                     IdentifierInfo *Name,
328                                                     SourceLocation NameLoc,
329                                                     unsigned Depth,
330                                                     unsigned Position)
331{
332  assert(S->isTemplateParamScope() &&
333         "Template template parameter not in template parameter scope!");
334
335  // Construct the parameter object.
336  TemplateTemplateParmDecl *Param =
337    TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
338                                     Position, Name,
339                                     (TemplateParameterList*)Params);
340
341  // Make sure the parameter is valid.
342  // FIXME: Decl object is not currently invalidated anywhere so this doesn't
343  // do anything yet. However, if the template parameter list or (eventual)
344  // default value is ever invalidated, that will propagate here.
345  bool Invalid = false;
346  if (Invalid) {
347    Param->setInvalidDecl();
348  }
349
350  // If the tt-param has a name, then link the identifier into the scope
351  // and lookup mechanisms.
352  if (Name) {
353    S->AddDecl(DeclPtrTy::make(Param));
354    IdResolver.AddDecl(Param);
355  }
356
357  return DeclPtrTy::make(Param);
358}
359
360/// \brief Adds a default argument to the given template template
361/// parameter.
362void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
363                                                 SourceLocation EqualLoc,
364                                                 ExprArg DefaultE) {
365  TemplateTemplateParmDecl *TemplateParm
366    = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
367
368  // Since a template-template parameter's default argument is an
369  // id-expression, it must be a DeclRefExpr.
370  DeclRefExpr *Default
371    = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
372
373  // C++ [temp.param]p14:
374  //   A template-parameter shall not be used in its own default argument.
375  // FIXME: Implement this check! Needs a recursive walk over the types.
376
377  // Check the well-formedness of the template argument.
378  if (!isa<TemplateDecl>(Default->getDecl())) {
379    Diag(Default->getSourceRange().getBegin(),
380         diag::err_template_arg_must_be_template)
381      << Default->getSourceRange();
382    TemplateParm->setInvalidDecl();
383    return;
384  }
385  if (CheckTemplateArgument(TemplateParm, Default)) {
386    TemplateParm->setInvalidDecl();
387    return;
388  }
389
390  DefaultE.release();
391  TemplateParm->setDefaultArgument(Default);
392}
393
394/// ActOnTemplateParameterList - Builds a TemplateParameterList that
395/// contains the template parameters in Params/NumParams.
396Sema::TemplateParamsTy *
397Sema::ActOnTemplateParameterList(unsigned Depth,
398                                 SourceLocation ExportLoc,
399                                 SourceLocation TemplateLoc,
400                                 SourceLocation LAngleLoc,
401                                 DeclPtrTy *Params, unsigned NumParams,
402                                 SourceLocation RAngleLoc) {
403  if (ExportLoc.isValid())
404    Diag(ExportLoc, diag::note_template_export_unsupported);
405
406  return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
407                                       (Decl**)Params, NumParams, RAngleLoc);
408}
409
410Sema::DeclResult
411Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
412                         SourceLocation KWLoc, const CXXScopeSpec &SS,
413                         IdentifierInfo *Name, SourceLocation NameLoc,
414                         AttributeList *Attr,
415                         MultiTemplateParamsArg TemplateParameterLists,
416                         AccessSpecifier AS) {
417  assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
418  assert(TK != TK_Reference && "Can only declare or define class templates");
419  bool Invalid = false;
420
421  // Check that we can declare a template here.
422  if (CheckTemplateDeclScope(S, TemplateParameterLists))
423    return true;
424
425  TagDecl::TagKind Kind;
426  switch (TagSpec) {
427  default: assert(0 && "Unknown tag type!");
428  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
429  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
430  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
431  }
432
433  // There is no such thing as an unnamed class template.
434  if (!Name) {
435    Diag(KWLoc, diag::err_template_unnamed_class);
436    return true;
437  }
438
439  // Find any previous declaration with this name.
440  LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
441                                           true);
442  assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
443  NamedDecl *PrevDecl = 0;
444  if (Previous.begin() != Previous.end())
445    PrevDecl = *Previous.begin();
446
447  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
448    PrevDecl = 0;
449
450  DeclContext *SemanticContext = CurContext;
451  if (SS.isNotEmpty() && !SS.isInvalid()) {
452    SemanticContext = computeDeclContext(SS);
453
454    // FIXME: need to match up several levels of template parameter lists here.
455  }
456
457  // FIXME: member templates!
458  TemplateParameterList *TemplateParams
459    = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
460
461  // If there is a previous declaration with the same name, check
462  // whether this is a valid redeclaration.
463  ClassTemplateDecl *PrevClassTemplate
464    = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
465  if (PrevClassTemplate) {
466    // Ensure that the template parameter lists are compatible.
467    if (!TemplateParameterListsAreEqual(TemplateParams,
468                                   PrevClassTemplate->getTemplateParameters(),
469                                        /*Complain=*/true))
470      return true;
471
472    // C++ [temp.class]p4:
473    //   In a redeclaration, partial specialization, explicit
474    //   specialization or explicit instantiation of a class template,
475    //   the class-key shall agree in kind with the original class
476    //   template declaration (7.1.5.3).
477    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
478    if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
479      Diag(KWLoc, diag::err_use_with_wrong_tag)
480        << Name
481        << CodeModificationHint::CreateReplacement(KWLoc,
482                            PrevRecordDecl->getKindName());
483      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
484      Kind = PrevRecordDecl->getTagKind();
485    }
486
487    // Check for redefinition of this class template.
488    if (TK == TK_Definition) {
489      if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
490        Diag(NameLoc, diag::err_redefinition) << Name;
491        Diag(Def->getLocation(), diag::note_previous_definition);
492        // FIXME: Would it make sense to try to "forget" the previous
493        // definition, as part of error recovery?
494        return true;
495      }
496    }
497  } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
498    // Maybe we will complain about the shadowed template parameter.
499    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
500    // Just pretend that we didn't see the previous declaration.
501    PrevDecl = 0;
502  } else if (PrevDecl) {
503    // C++ [temp]p5:
504    //   A class template shall not have the same name as any other
505    //   template, class, function, object, enumeration, enumerator,
506    //   namespace, or type in the same scope (3.3), except as specified
507    //   in (14.5.4).
508    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
509    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
510    return true;
511  }
512
513  // Check the template parameter list of this declaration, possibly
514  // merging in the template parameter list from the previous class
515  // template declaration.
516  if (CheckTemplateParameterList(TemplateParams,
517            PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
518    Invalid = true;
519
520  // FIXME: If we had a scope specifier, we better have a previous template
521  // declaration!
522
523  CXXRecordDecl *NewClass =
524    CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
525                          PrevClassTemplate?
526                            PrevClassTemplate->getTemplatedDecl() : 0,
527                          /*DelayTypeCreation=*/true);
528
529  ClassTemplateDecl *NewTemplate
530    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
531                                DeclarationName(Name), TemplateParams,
532                                NewClass, PrevClassTemplate);
533  NewClass->setDescribedClassTemplate(NewTemplate);
534
535  // Build the type for the class template declaration now.
536  QualType T =
537    Context.getTypeDeclType(NewClass,
538                            PrevClassTemplate?
539                              PrevClassTemplate->getTemplatedDecl() : 0);
540  assert(T->isDependentType() && "Class template type is not dependent?");
541  (void)T;
542
543  // Set the access specifier.
544  SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
545
546  // Set the lexical context of these templates
547  NewClass->setLexicalDeclContext(CurContext);
548  NewTemplate->setLexicalDeclContext(CurContext);
549
550  if (TK == TK_Definition)
551    NewClass->startDefinition();
552
553  if (Attr)
554    ProcessDeclAttributeList(S, NewClass, Attr);
555
556  PushOnScopeChains(NewTemplate, S);
557
558  if (Invalid) {
559    NewTemplate->setInvalidDecl();
560    NewClass->setInvalidDecl();
561  }
562  return DeclPtrTy::make(NewTemplate);
563}
564
565/// \brief Checks the validity of a template parameter list, possibly
566/// considering the template parameter list from a previous
567/// declaration.
568///
569/// If an "old" template parameter list is provided, it must be
570/// equivalent (per TemplateParameterListsAreEqual) to the "new"
571/// template parameter list.
572///
573/// \param NewParams Template parameter list for a new template
574/// declaration. This template parameter list will be updated with any
575/// default arguments that are carried through from the previous
576/// template parameter list.
577///
578/// \param OldParams If provided, template parameter list from a
579/// previous declaration of the same template. Default template
580/// arguments will be merged from the old template parameter list to
581/// the new template parameter list.
582///
583/// \returns true if an error occurred, false otherwise.
584bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
585                                      TemplateParameterList *OldParams) {
586  bool Invalid = false;
587
588  // C++ [temp.param]p10:
589  //   The set of default template-arguments available for use with a
590  //   template declaration or definition is obtained by merging the
591  //   default arguments from the definition (if in scope) and all
592  //   declarations in scope in the same way default function
593  //   arguments are (8.3.6).
594  bool SawDefaultArgument = false;
595  SourceLocation PreviousDefaultArgLoc;
596
597  bool SawParameterPack = false;
598  SourceLocation ParameterPackLoc;
599
600  // Dummy initialization to avoid warnings.
601  TemplateParameterList::iterator OldParam = NewParams->end();
602  if (OldParams)
603    OldParam = OldParams->begin();
604
605  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
606                                    NewParamEnd = NewParams->end();
607       NewParam != NewParamEnd; ++NewParam) {
608    // Variables used to diagnose redundant default arguments
609    bool RedundantDefaultArg = false;
610    SourceLocation OldDefaultLoc;
611    SourceLocation NewDefaultLoc;
612
613    // Variables used to diagnose missing default arguments
614    bool MissingDefaultArg = false;
615
616    // C++0x [temp.param]p11:
617    // If a template parameter of a class template is a template parameter pack,
618    // it must be the last template parameter.
619    if (SawParameterPack) {
620      Diag(ParameterPackLoc,
621           diag::err_template_param_pack_must_be_last_template_parameter);
622      Invalid = true;
623    }
624
625    // Merge default arguments for template type parameters.
626    if (TemplateTypeParmDecl *NewTypeParm
627          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
628      TemplateTypeParmDecl *OldTypeParm
629          = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
630
631      if (NewTypeParm->isParameterPack()) {
632        assert(!NewTypeParm->hasDefaultArgument() &&
633               "Parameter packs can't have a default argument!");
634        SawParameterPack = true;
635        ParameterPackLoc = NewTypeParm->getLocation();
636      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
637          NewTypeParm->hasDefaultArgument()) {
638        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
639        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
640        SawDefaultArgument = true;
641        RedundantDefaultArg = true;
642        PreviousDefaultArgLoc = NewDefaultLoc;
643      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
644        // Merge the default argument from the old declaration to the
645        // new declaration.
646        SawDefaultArgument = true;
647        NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
648                                        OldTypeParm->getDefaultArgumentLoc(),
649                                        true);
650        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
651      } else if (NewTypeParm->hasDefaultArgument()) {
652        SawDefaultArgument = true;
653        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
654      } else if (SawDefaultArgument)
655        MissingDefaultArg = true;
656    }
657    // Merge default arguments for non-type template parameters
658    else if (NonTypeTemplateParmDecl *NewNonTypeParm
659               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
660      NonTypeTemplateParmDecl *OldNonTypeParm
661        = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
662      if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
663          NewNonTypeParm->hasDefaultArgument()) {
664        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
665        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
666        SawDefaultArgument = true;
667        RedundantDefaultArg = true;
668        PreviousDefaultArgLoc = NewDefaultLoc;
669      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
670        // Merge the default argument from the old declaration to the
671        // new declaration.
672        SawDefaultArgument = true;
673        // FIXME: We need to create a new kind of "default argument"
674        // expression that points to a previous template template
675        // parameter.
676        NewNonTypeParm->setDefaultArgument(
677                                        OldNonTypeParm->getDefaultArgument());
678        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
679      } else if (NewNonTypeParm->hasDefaultArgument()) {
680        SawDefaultArgument = true;
681        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
682      } else if (SawDefaultArgument)
683        MissingDefaultArg = true;
684    }
685    // Merge default arguments for template template parameters
686    else {
687      TemplateTemplateParmDecl *NewTemplateParm
688        = cast<TemplateTemplateParmDecl>(*NewParam);
689      TemplateTemplateParmDecl *OldTemplateParm
690        = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
691      if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
692          NewTemplateParm->hasDefaultArgument()) {
693        OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
694        NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
695        SawDefaultArgument = true;
696        RedundantDefaultArg = true;
697        PreviousDefaultArgLoc = NewDefaultLoc;
698      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
699        // Merge the default argument from the old declaration to the
700        // new declaration.
701        SawDefaultArgument = true;
702        // FIXME: We need to create a new kind of "default argument" expression
703        // that points to a previous template template parameter.
704        NewTemplateParm->setDefaultArgument(
705                                        OldTemplateParm->getDefaultArgument());
706        PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
707      } else if (NewTemplateParm->hasDefaultArgument()) {
708        SawDefaultArgument = true;
709        PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
710      } else if (SawDefaultArgument)
711        MissingDefaultArg = true;
712    }
713
714    if (RedundantDefaultArg) {
715      // C++ [temp.param]p12:
716      //   A template-parameter shall not be given default arguments
717      //   by two different declarations in the same scope.
718      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
719      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
720      Invalid = true;
721    } else if (MissingDefaultArg) {
722      // C++ [temp.param]p11:
723      //   If a template-parameter has a default template-argument,
724      //   all subsequent template-parameters shall have a default
725      //   template-argument supplied.
726      Diag((*NewParam)->getLocation(),
727           diag::err_template_param_default_arg_missing);
728      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
729      Invalid = true;
730    }
731
732    // If we have an old template parameter list that we're merging
733    // in, move on to the next parameter.
734    if (OldParams)
735      ++OldParam;
736  }
737
738  return Invalid;
739}
740
741/// \brief Translates template arguments as provided by the parser
742/// into template arguments used by semantic analysis.
743static void
744translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
745                           SourceLocation *TemplateArgLocs,
746                     llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
747  TemplateArgs.reserve(TemplateArgsIn.size());
748
749  void **Args = TemplateArgsIn.getArgs();
750  bool *ArgIsType = TemplateArgsIn.getArgIsType();
751  for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
752    TemplateArgs.push_back(
753      ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
754                                       QualType::getFromOpaquePtr(Args[Arg]))
755                    : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
756  }
757}
758
759/// \brief Build a canonical version of a template argument list.
760///
761/// This function builds a canonical version of the given template
762/// argument list, where each of the template arguments has been
763/// converted into its canonical form. This routine is typically used
764/// to canonicalize a template argument list when the template name
765/// itself is dependent. When the template name refers to an actual
766/// template declaration, Sema::CheckTemplateArgumentList should be
767/// used to check and canonicalize the template arguments.
768///
769/// \param TemplateArgs The incoming template arguments.
770///
771/// \param NumTemplateArgs The number of template arguments in \p
772/// TemplateArgs.
773///
774/// \param Canonical A vector to be filled with the canonical versions
775/// of the template arguments.
776///
777/// \param Context The ASTContext in which the template arguments live.
778static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
779                                          unsigned NumTemplateArgs,
780                            llvm::SmallVectorImpl<TemplateArgument> &Canonical,
781                                          ASTContext &Context) {
782  Canonical.reserve(NumTemplateArgs);
783  for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
784    switch (TemplateArgs[Idx].getKind()) {
785    case TemplateArgument::Null:
786      assert(false && "Should never see a NULL template argument here");
787      break;
788
789    case TemplateArgument::Expression:
790      // FIXME: Build canonical expression (!)
791      Canonical.push_back(TemplateArgs[Idx]);
792      break;
793
794    case TemplateArgument::Declaration:
795      Canonical.push_back(
796                 TemplateArgument(SourceLocation(),
797                    Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
798      break;
799
800    case TemplateArgument::Integral:
801      Canonical.push_back(TemplateArgument(SourceLocation(),
802                                           *TemplateArgs[Idx].getAsIntegral(),
803                                        TemplateArgs[Idx].getIntegralType()));
804      break;
805
806    case TemplateArgument::Type: {
807      QualType CanonType
808        = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
809      Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
810      break;
811    }
812
813    case TemplateArgument::Pack:
814      assert(0 && "FIXME: Implement!");
815      break;
816    }
817  }
818}
819
820QualType Sema::CheckTemplateIdType(TemplateName Name,
821                                   SourceLocation TemplateLoc,
822                                   SourceLocation LAngleLoc,
823                                   const TemplateArgument *TemplateArgs,
824                                   unsigned NumTemplateArgs,
825                                   SourceLocation RAngleLoc) {
826  TemplateDecl *Template = Name.getAsTemplateDecl();
827  if (!Template) {
828    // The template name does not resolve to a template, so we just
829    // build a dependent template-id type.
830
831    // Canonicalize the template arguments to build the canonical
832    // template-id type.
833    llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
834    CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
835                                  CanonicalTemplateArgs, Context);
836
837    TemplateName CanonName = Context.getCanonicalTemplateName(Name);
838    QualType CanonType
839      = Context.getTemplateSpecializationType(CanonName,
840                                              &CanonicalTemplateArgs[0],
841                                              CanonicalTemplateArgs.size());
842
843    // Build the dependent template-id type.
844    return Context.getTemplateSpecializationType(Name, TemplateArgs,
845                                                 NumTemplateArgs, CanonType);
846  }
847
848  // Check that the template argument list is well-formed for this
849  // template.
850  TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
851                                        NumTemplateArgs);
852  if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
853                                TemplateArgs, NumTemplateArgs, RAngleLoc,
854                                Converted))
855    return QualType();
856
857  assert((Converted.structuredSize() ==
858            Template->getTemplateParameters()->size()) &&
859         "Converted template argument list is too short!");
860
861  QualType CanonType;
862
863  if (TemplateSpecializationType::anyDependentTemplateArguments(
864                                                      TemplateArgs,
865                                                      NumTemplateArgs)) {
866    // This class template specialization is a dependent
867    // type. Therefore, its canonical type is another class template
868    // specialization type that contains all of the converted
869    // arguments in canonical form. This ensures that, e.g., A<T> and
870    // A<T, T> have identical types when A is declared as:
871    //
872    //   template<typename T, typename U = T> struct A;
873    TemplateName CanonName = Context.getCanonicalTemplateName(Name);
874    CanonType = Context.getTemplateSpecializationType(CanonName,
875                                                   Converted.getFlatArguments(),
876                                                   Converted.flatSize());
877  } else if (ClassTemplateDecl *ClassTemplate
878               = dyn_cast<ClassTemplateDecl>(Template)) {
879    // Find the class template specialization declaration that
880    // corresponds to these arguments.
881    llvm::FoldingSetNodeID ID;
882    ClassTemplateSpecializationDecl::Profile(ID,
883                                             Converted.getFlatArguments(),
884                                             Converted.flatSize());
885    void *InsertPos = 0;
886    ClassTemplateSpecializationDecl *Decl
887      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
888    if (!Decl) {
889      // This is the first time we have referenced this class template
890      // specialization. Create the canonical declaration and add it to
891      // the set of specializations.
892      Decl = ClassTemplateSpecializationDecl::Create(Context,
893                                    ClassTemplate->getDeclContext(),
894                                    TemplateLoc,
895                                    ClassTemplate,
896                                    Converted, 0);
897      ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
898      Decl->setLexicalDeclContext(CurContext);
899    }
900
901    CanonType = Context.getTypeDeclType(Decl);
902  }
903
904  // Build the fully-sugared type for this class template
905  // specialization, which refers back to the class template
906  // specialization we created or found.
907  return Context.getTemplateSpecializationType(Name, TemplateArgs,
908                                               NumTemplateArgs, CanonType);
909}
910
911Action::TypeResult
912Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
913                          SourceLocation LAngleLoc,
914                          ASTTemplateArgsPtr TemplateArgsIn,
915                          SourceLocation *TemplateArgLocs,
916                          SourceLocation RAngleLoc) {
917  TemplateName Template = TemplateD.getAsVal<TemplateName>();
918
919  // Translate the parser's template argument list in our AST format.
920  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
921  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
922
923  QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
924                                        TemplateArgs.data(),
925                                        TemplateArgs.size(),
926                                        RAngleLoc);
927  TemplateArgsIn.release();
928
929  if (Result.isNull())
930    return true;
931
932  return Result.getAsOpaquePtr();
933}
934
935/// \brief Form a dependent template name.
936///
937/// This action forms a dependent template name given the template
938/// name and its (presumably dependent) scope specifier. For
939/// example, given "MetaFun::template apply", the scope specifier \p
940/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
941/// of the "template" keyword, and "apply" is the \p Name.
942Sema::TemplateTy
943Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
944                                 const IdentifierInfo &Name,
945                                 SourceLocation NameLoc,
946                                 const CXXScopeSpec &SS) {
947  if (!SS.isSet() || SS.isInvalid())
948    return TemplateTy();
949
950  NestedNameSpecifier *Qualifier
951    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
952
953  // FIXME: member of the current instantiation
954
955  if (!Qualifier->isDependent()) {
956    // C++0x [temp.names]p5:
957    //   If a name prefixed by the keyword template is not the name of
958    //   a template, the program is ill-formed. [Note: the keyword
959    //   template may not be applied to non-template members of class
960    //   templates. -end note ] [ Note: as is the case with the
961    //   typename prefix, the template prefix is allowed in cases
962    //   where it is not strictly necessary; i.e., when the
963    //   nested-name-specifier or the expression on the left of the ->
964    //   or . is not dependent on a template-parameter, or the use
965    //   does not appear in the scope of a template. -end note]
966    //
967    // Note: C++03 was more strict here, because it banned the use of
968    // the "template" keyword prior to a template-name that was not a
969    // dependent name. C++ DR468 relaxed this requirement (the
970    // "template" keyword is now permitted). We follow the C++0x
971    // rules, even in C++03 mode, retroactively applying the DR.
972    TemplateTy Template;
973    TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
974    if (TNK == TNK_Non_template) {
975      Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
976        << &Name;
977      return TemplateTy();
978    }
979
980    return Template;
981  }
982
983  return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
984}
985
986bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
987                                     const TemplateArgument &Arg,
988                                     TemplateArgumentListBuilder &Converted) {
989  // Check template type parameter.
990  if (Arg.getKind() != TemplateArgument::Type) {
991    // C++ [temp.arg.type]p1:
992    //   A template-argument for a template-parameter which is a
993    //   type shall be a type-id.
994
995    // We have a template type parameter but the template argument
996    // is not a type.
997    Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
998    Diag(Param->getLocation(), diag::note_template_param_here);
999
1000    return true;
1001  }
1002
1003  if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1004    return true;
1005
1006  // Add the converted template type argument.
1007  Converted.Append(
1008                 TemplateArgument(Arg.getLocation(),
1009                                  Context.getCanonicalType(Arg.getAsType())));
1010  return false;
1011}
1012
1013/// \brief Check that the given template argument list is well-formed
1014/// for specializing the given template.
1015bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1016                                     SourceLocation TemplateLoc,
1017                                     SourceLocation LAngleLoc,
1018                                     const TemplateArgument *TemplateArgs,
1019                                     unsigned NumTemplateArgs,
1020                                     SourceLocation RAngleLoc,
1021                                     TemplateArgumentListBuilder &Converted) {
1022  TemplateParameterList *Params = Template->getTemplateParameters();
1023  unsigned NumParams = Params->size();
1024  unsigned NumArgs = NumTemplateArgs;
1025  bool Invalid = false;
1026
1027  bool HasParameterPack =
1028    NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1029
1030  if ((NumArgs > NumParams && !HasParameterPack) ||
1031      NumArgs < Params->getMinRequiredArguments()) {
1032    // FIXME: point at either the first arg beyond what we can handle,
1033    // or the '>', depending on whether we have too many or too few
1034    // arguments.
1035    SourceRange Range;
1036    if (NumArgs > NumParams)
1037      Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
1038    Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1039      << (NumArgs > NumParams)
1040      << (isa<ClassTemplateDecl>(Template)? 0 :
1041          isa<FunctionTemplateDecl>(Template)? 1 :
1042          isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1043      << Template << Range;
1044    Diag(Template->getLocation(), diag::note_template_decl_here)
1045      << Params->getSourceRange();
1046    Invalid = true;
1047  }
1048
1049  // C++ [temp.arg]p1:
1050  //   [...] The type and form of each template-argument specified in
1051  //   a template-id shall match the type and form specified for the
1052  //   corresponding parameter declared by the template in its
1053  //   template-parameter-list.
1054  unsigned ArgIdx = 0;
1055  for (TemplateParameterList::iterator Param = Params->begin(),
1056                                       ParamEnd = Params->end();
1057       Param != ParamEnd; ++Param, ++ArgIdx) {
1058    // Decode the template argument
1059    TemplateArgument Arg;
1060    if (ArgIdx >= NumArgs) {
1061      // Retrieve the default template argument from the template
1062      // parameter.
1063      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1064        if (TTP->isParameterPack()) {
1065          // We have an empty argument pack.
1066          Converted.BeginPack();
1067          Converted.EndPack();
1068          break;
1069        }
1070
1071        if (!TTP->hasDefaultArgument())
1072          break;
1073
1074        QualType ArgType = TTP->getDefaultArgument();
1075
1076        // If the argument type is dependent, instantiate it now based
1077        // on the previously-computed template arguments.
1078        if (ArgType->isDependentType()) {
1079          InstantiatingTemplate Inst(*this, TemplateLoc,
1080                                     Template, Converted.getFlatArguments(),
1081                                     Converted.flatSize(),
1082                                     SourceRange(TemplateLoc, RAngleLoc));
1083
1084          TemplateArgumentList TemplateArgs(Context, Converted,
1085                                            /*TakeArgs=*/false);
1086          ArgType = InstantiateType(ArgType, TemplateArgs,
1087                                    TTP->getDefaultArgumentLoc(),
1088                                    TTP->getDeclName());
1089        }
1090
1091        if (ArgType.isNull())
1092          return true;
1093
1094        Arg = TemplateArgument(TTP->getLocation(), ArgType);
1095      } else if (NonTypeTemplateParmDecl *NTTP
1096                   = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1097        if (!NTTP->hasDefaultArgument())
1098          break;
1099
1100        InstantiatingTemplate Inst(*this, TemplateLoc,
1101                                   Template, Converted.getFlatArguments(),
1102                                   Converted.flatSize(),
1103                                   SourceRange(TemplateLoc, RAngleLoc));
1104
1105        TemplateArgumentList TemplateArgs(Context, Converted,
1106                                          /*TakeArgs=*/false);
1107
1108        Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1109                                                   TemplateArgs);
1110        if (E.isInvalid())
1111          return true;
1112
1113        Arg = TemplateArgument(E.takeAs<Expr>());
1114      } else {
1115        TemplateTemplateParmDecl *TempParm
1116          = cast<TemplateTemplateParmDecl>(*Param);
1117
1118        if (!TempParm->hasDefaultArgument())
1119          break;
1120
1121        // FIXME: Instantiate default argument
1122        Arg = TemplateArgument(TempParm->getDefaultArgument());
1123      }
1124    } else {
1125      // Retrieve the template argument produced by the user.
1126      Arg = TemplateArgs[ArgIdx];
1127    }
1128
1129
1130    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1131      if (TTP->isParameterPack()) {
1132        Converted.BeginPack();
1133        // Check all the remaining arguments (if any).
1134        for (; ArgIdx < NumArgs; ++ArgIdx) {
1135          if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1136            Invalid = true;
1137        }
1138
1139        Converted.EndPack();
1140      } else {
1141        if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1142          Invalid = true;
1143      }
1144    } else if (NonTypeTemplateParmDecl *NTTP
1145                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1146      // Check non-type template parameters.
1147
1148      // Instantiate the type of the non-type template parameter with
1149      // the template arguments we've seen thus far.
1150      QualType NTTPType = NTTP->getType();
1151      if (NTTPType->isDependentType()) {
1152        // Instantiate the type of the non-type template parameter.
1153        InstantiatingTemplate Inst(*this, TemplateLoc,
1154                                   Template, Converted.getFlatArguments(),
1155                                   Converted.flatSize(),
1156                                   SourceRange(TemplateLoc, RAngleLoc));
1157
1158        TemplateArgumentList TemplateArgs(Context, Converted,
1159                                          /*TakeArgs=*/false);
1160        NTTPType = InstantiateType(NTTPType, TemplateArgs,
1161                                   NTTP->getLocation(),
1162                                   NTTP->getDeclName());
1163        // If that worked, check the non-type template parameter type
1164        // for validity.
1165        if (!NTTPType.isNull())
1166          NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1167                                                       NTTP->getLocation());
1168        if (NTTPType.isNull()) {
1169          Invalid = true;
1170          break;
1171        }
1172      }
1173
1174      switch (Arg.getKind()) {
1175      case TemplateArgument::Null:
1176        assert(false && "Should never see a NULL template argument here");
1177        break;
1178
1179      case TemplateArgument::Expression: {
1180        Expr *E = Arg.getAsExpr();
1181        TemplateArgument Result;
1182        if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1183          Invalid = true;
1184        else
1185          Converted.Append(Result);
1186        break;
1187      }
1188
1189      case TemplateArgument::Declaration:
1190      case TemplateArgument::Integral:
1191        // We've already checked this template argument, so just copy
1192        // it to the list of converted arguments.
1193        Converted.Append(Arg);
1194        break;
1195
1196      case TemplateArgument::Type:
1197        // We have a non-type template parameter but the template
1198        // argument is a type.
1199
1200        // C++ [temp.arg]p2:
1201        //   In a template-argument, an ambiguity between a type-id and
1202        //   an expression is resolved to a type-id, regardless of the
1203        //   form of the corresponding template-parameter.
1204        //
1205        // We warn specifically about this case, since it can be rather
1206        // confusing for users.
1207        if (Arg.getAsType()->isFunctionType())
1208          Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1209            << Arg.getAsType();
1210        else
1211          Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1212        Diag((*Param)->getLocation(), diag::note_template_param_here);
1213        Invalid = true;
1214        break;
1215
1216      case TemplateArgument::Pack:
1217        assert(0 && "FIXME: Implement!");
1218        break;
1219      }
1220    } else {
1221      // Check template template parameters.
1222      TemplateTemplateParmDecl *TempParm
1223        = cast<TemplateTemplateParmDecl>(*Param);
1224
1225      switch (Arg.getKind()) {
1226      case TemplateArgument::Null:
1227        assert(false && "Should never see a NULL template argument here");
1228        break;
1229
1230      case TemplateArgument::Expression: {
1231        Expr *ArgExpr = Arg.getAsExpr();
1232        if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1233            isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1234          if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1235            Invalid = true;
1236
1237          // Add the converted template argument.
1238          Decl *D
1239            = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1240          Converted.Append(TemplateArgument(Arg.getLocation(), D));
1241          continue;
1242        }
1243      }
1244        // fall through
1245
1246      case TemplateArgument::Type: {
1247        // We have a template template parameter but the template
1248        // argument does not refer to a template.
1249        Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1250        Invalid = true;
1251        break;
1252      }
1253
1254      case TemplateArgument::Declaration:
1255        // We've already checked this template argument, so just copy
1256        // it to the list of converted arguments.
1257        Converted.Append(Arg);
1258        break;
1259
1260      case TemplateArgument::Integral:
1261        assert(false && "Integral argument with template template parameter");
1262        break;
1263
1264      case TemplateArgument::Pack:
1265        assert(0 && "FIXME: Implement!");
1266        break;
1267      }
1268    }
1269  }
1270
1271  return Invalid;
1272}
1273
1274/// \brief Check a template argument against its corresponding
1275/// template type parameter.
1276///
1277/// This routine implements the semantics of C++ [temp.arg.type]. It
1278/// returns true if an error occurred, and false otherwise.
1279bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1280                                 QualType Arg, SourceLocation ArgLoc) {
1281  // C++ [temp.arg.type]p2:
1282  //   A local type, a type with no linkage, an unnamed type or a type
1283  //   compounded from any of these types shall not be used as a
1284  //   template-argument for a template type-parameter.
1285  //
1286  // FIXME: Perform the recursive and no-linkage type checks.
1287  const TagType *Tag = 0;
1288  if (const EnumType *EnumT = Arg->getAsEnumType())
1289    Tag = EnumT;
1290  else if (const RecordType *RecordT = Arg->getAsRecordType())
1291    Tag = RecordT;
1292  if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1293    return Diag(ArgLoc, diag::err_template_arg_local_type)
1294      << QualType(Tag, 0);
1295  else if (Tag && !Tag->getDecl()->getDeclName() &&
1296           !Tag->getDecl()->getTypedefForAnonDecl()) {
1297    Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1298    Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1299    return true;
1300  }
1301
1302  return false;
1303}
1304
1305/// \brief Checks whether the given template argument is the address
1306/// of an object or function according to C++ [temp.arg.nontype]p1.
1307bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1308                                                          NamedDecl *&Entity) {
1309  bool Invalid = false;
1310
1311  // See through any implicit casts we added to fix the type.
1312  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1313    Arg = Cast->getSubExpr();
1314
1315  // C++0x allows nullptr, and there's no further checking to be done for that.
1316  if (Arg->getType()->isNullPtrType())
1317    return false;
1318
1319  // C++ [temp.arg.nontype]p1:
1320  //
1321  //   A template-argument for a non-type, non-template
1322  //   template-parameter shall be one of: [...]
1323  //
1324  //     -- the address of an object or function with external
1325  //        linkage, including function templates and function
1326  //        template-ids but excluding non-static class members,
1327  //        expressed as & id-expression where the & is optional if
1328  //        the name refers to a function or array, or if the
1329  //        corresponding template-parameter is a reference; or
1330  DeclRefExpr *DRE = 0;
1331
1332  // Ignore (and complain about) any excess parentheses.
1333  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1334    if (!Invalid) {
1335      Diag(Arg->getSourceRange().getBegin(),
1336           diag::err_template_arg_extra_parens)
1337        << Arg->getSourceRange();
1338      Invalid = true;
1339    }
1340
1341    Arg = Parens->getSubExpr();
1342  }
1343
1344  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1345    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1346      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1347  } else
1348    DRE = dyn_cast<DeclRefExpr>(Arg);
1349
1350  if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1351    return Diag(Arg->getSourceRange().getBegin(),
1352                diag::err_template_arg_not_object_or_func_form)
1353      << Arg->getSourceRange();
1354
1355  // Cannot refer to non-static data members
1356  if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1357    return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1358      << Field << Arg->getSourceRange();
1359
1360  // Cannot refer to non-static member functions
1361  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1362    if (!Method->isStatic())
1363      return Diag(Arg->getSourceRange().getBegin(),
1364                  diag::err_template_arg_method)
1365        << Method << Arg->getSourceRange();
1366
1367  // Functions must have external linkage.
1368  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1369    if (Func->getStorageClass() == FunctionDecl::Static) {
1370      Diag(Arg->getSourceRange().getBegin(),
1371           diag::err_template_arg_function_not_extern)
1372        << Func << Arg->getSourceRange();
1373      Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1374        << true;
1375      return true;
1376    }
1377
1378    // Okay: we've named a function with external linkage.
1379    Entity = Func;
1380    return Invalid;
1381  }
1382
1383  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1384    if (!Var->hasGlobalStorage()) {
1385      Diag(Arg->getSourceRange().getBegin(),
1386           diag::err_template_arg_object_not_extern)
1387        << Var << Arg->getSourceRange();
1388      Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1389        << true;
1390      return true;
1391    }
1392
1393    // Okay: we've named an object with external linkage
1394    Entity = Var;
1395    return Invalid;
1396  }
1397
1398  // We found something else, but we don't know specifically what it is.
1399  Diag(Arg->getSourceRange().getBegin(),
1400       diag::err_template_arg_not_object_or_func)
1401      << Arg->getSourceRange();
1402  Diag(DRE->getDecl()->getLocation(),
1403       diag::note_template_arg_refers_here);
1404  return true;
1405}
1406
1407/// \brief Checks whether the given template argument is a pointer to
1408/// member constant according to C++ [temp.arg.nontype]p1.
1409bool
1410Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
1411  bool Invalid = false;
1412
1413  // See through any implicit casts we added to fix the type.
1414  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1415    Arg = Cast->getSubExpr();
1416
1417  // C++0x allows nullptr, and there's no further checking to be done for that.
1418  if (Arg->getType()->isNullPtrType())
1419    return false;
1420
1421  // C++ [temp.arg.nontype]p1:
1422  //
1423  //   A template-argument for a non-type, non-template
1424  //   template-parameter shall be one of: [...]
1425  //
1426  //     -- a pointer to member expressed as described in 5.3.1.
1427  QualifiedDeclRefExpr *DRE = 0;
1428
1429  // Ignore (and complain about) any excess parentheses.
1430  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1431    if (!Invalid) {
1432      Diag(Arg->getSourceRange().getBegin(),
1433           diag::err_template_arg_extra_parens)
1434        << Arg->getSourceRange();
1435      Invalid = true;
1436    }
1437
1438    Arg = Parens->getSubExpr();
1439  }
1440
1441  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1442    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1443      DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1444
1445  if (!DRE)
1446    return Diag(Arg->getSourceRange().getBegin(),
1447                diag::err_template_arg_not_pointer_to_member_form)
1448      << Arg->getSourceRange();
1449
1450  if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1451    assert((isa<FieldDecl>(DRE->getDecl()) ||
1452            !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1453           "Only non-static member pointers can make it here");
1454
1455    // Okay: this is the address of a non-static member, and therefore
1456    // a member pointer constant.
1457    Member = DRE->getDecl();
1458    return Invalid;
1459  }
1460
1461  // We found something else, but we don't know specifically what it is.
1462  Diag(Arg->getSourceRange().getBegin(),
1463       diag::err_template_arg_not_pointer_to_member_form)
1464      << Arg->getSourceRange();
1465  Diag(DRE->getDecl()->getLocation(),
1466       diag::note_template_arg_refers_here);
1467  return true;
1468}
1469
1470/// \brief Check a template argument against its corresponding
1471/// non-type template parameter.
1472///
1473/// This routine implements the semantics of C++ [temp.arg.nontype].
1474/// It returns true if an error occurred, and false otherwise. \p
1475/// InstantiatedParamType is the type of the non-type template
1476/// parameter after it has been instantiated.
1477///
1478/// If no error was detected, Converted receives the converted template argument.
1479bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
1480                                 QualType InstantiatedParamType, Expr *&Arg,
1481                                 TemplateArgument &Converted) {
1482  SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1483
1484  // If either the parameter has a dependent type or the argument is
1485  // type-dependent, there's nothing we can check now.
1486  // FIXME: Add template argument to Converted!
1487  if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1488    // FIXME: Produce a cloned, canonical expression?
1489    Converted = TemplateArgument(Arg);
1490    return false;
1491  }
1492
1493  // C++ [temp.arg.nontype]p5:
1494  //   The following conversions are performed on each expression used
1495  //   as a non-type template-argument. If a non-type
1496  //   template-argument cannot be converted to the type of the
1497  //   corresponding template-parameter then the program is
1498  //   ill-formed.
1499  //
1500  //     -- for a non-type template-parameter of integral or
1501  //        enumeration type, integral promotions (4.5) and integral
1502  //        conversions (4.7) are applied.
1503  QualType ParamType = InstantiatedParamType;
1504  QualType ArgType = Arg->getType();
1505  if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
1506    // C++ [temp.arg.nontype]p1:
1507    //   A template-argument for a non-type, non-template
1508    //   template-parameter shall be one of:
1509    //
1510    //     -- an integral constant-expression of integral or enumeration
1511    //        type; or
1512    //     -- the name of a non-type template-parameter; or
1513    SourceLocation NonConstantLoc;
1514    llvm::APSInt Value;
1515    if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1516      Diag(Arg->getSourceRange().getBegin(),
1517           diag::err_template_arg_not_integral_or_enumeral)
1518        << ArgType << Arg->getSourceRange();
1519      Diag(Param->getLocation(), diag::note_template_param_here);
1520      return true;
1521    } else if (!Arg->isValueDependent() &&
1522               !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
1523      Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1524        << ArgType << Arg->getSourceRange();
1525      return true;
1526    }
1527
1528    // FIXME: We need some way to more easily get the unqualified form
1529    // of the types without going all the way to the
1530    // canonical type.
1531    if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1532      ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1533    if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1534      ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1535
1536    // Try to convert the argument to the parameter's type.
1537    if (ParamType == ArgType) {
1538      // Okay: no conversion necessary
1539    } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1540               !ParamType->isEnumeralType()) {
1541      // This is an integral promotion or conversion.
1542      ImpCastExprToType(Arg, ParamType);
1543    } else {
1544      // We can't perform this conversion.
1545      Diag(Arg->getSourceRange().getBegin(),
1546           diag::err_template_arg_not_convertible)
1547        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1548      Diag(Param->getLocation(), diag::note_template_param_here);
1549      return true;
1550    }
1551
1552    QualType IntegerType = Context.getCanonicalType(ParamType);
1553    if (const EnumType *Enum = IntegerType->getAsEnumType())
1554      IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
1555
1556    if (!Arg->isValueDependent()) {
1557      // Check that an unsigned parameter does not receive a negative
1558      // value.
1559      if (IntegerType->isUnsignedIntegerType()
1560          && (Value.isSigned() && Value.isNegative())) {
1561        Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1562          << Value.toString(10) << Param->getType()
1563          << Arg->getSourceRange();
1564        Diag(Param->getLocation(), diag::note_template_param_here);
1565        return true;
1566      }
1567
1568      // Check that we don't overflow the template parameter type.
1569      unsigned AllowedBits = Context.getTypeSize(IntegerType);
1570      if (Value.getActiveBits() > AllowedBits) {
1571        Diag(Arg->getSourceRange().getBegin(),
1572             diag::err_template_arg_too_large)
1573          << Value.toString(10) << Param->getType()
1574          << Arg->getSourceRange();
1575        Diag(Param->getLocation(), diag::note_template_param_here);
1576        return true;
1577      }
1578
1579      if (Value.getBitWidth() != AllowedBits)
1580        Value.extOrTrunc(AllowedBits);
1581      Value.setIsSigned(IntegerType->isSignedIntegerType());
1582    }
1583
1584    // Add the value of this argument to the list of converted
1585    // arguments. We use the bitwidth and signedness of the template
1586    // parameter.
1587    if (Arg->isValueDependent()) {
1588      // The argument is value-dependent. Create a new
1589      // TemplateArgument with the converted expression.
1590      Converted = TemplateArgument(Arg);
1591      return false;
1592    }
1593
1594    Converted = TemplateArgument(StartLoc, Value,
1595                                 ParamType->isEnumeralType() ? ParamType
1596                                                             : IntegerType);
1597    return false;
1598  }
1599
1600  // Handle pointer-to-function, reference-to-function, and
1601  // pointer-to-member-function all in (roughly) the same way.
1602  if (// -- For a non-type template-parameter of type pointer to
1603      //    function, only the function-to-pointer conversion (4.3) is
1604      //    applied. If the template-argument represents a set of
1605      //    overloaded functions (or a pointer to such), the matching
1606      //    function is selected from the set (13.4).
1607      // In C++0x, any std::nullptr_t value can be converted.
1608      (ParamType->isPointerType() &&
1609       ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1610      // -- For a non-type template-parameter of type reference to
1611      //    function, no conversions apply. If the template-argument
1612      //    represents a set of overloaded functions, the matching
1613      //    function is selected from the set (13.4).
1614      (ParamType->isReferenceType() &&
1615       ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1616      // -- For a non-type template-parameter of type pointer to
1617      //    member function, no conversions apply. If the
1618      //    template-argument represents a set of overloaded member
1619      //    functions, the matching member function is selected from
1620      //    the set (13.4).
1621      // Again, C++0x allows a std::nullptr_t value.
1622      (ParamType->isMemberPointerType() &&
1623       ParamType->getAsMemberPointerType()->getPointeeType()
1624         ->isFunctionType())) {
1625    if (Context.hasSameUnqualifiedType(ArgType,
1626                                       ParamType.getNonReferenceType())) {
1627      // We don't have to do anything: the types already match.
1628    } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1629                 ParamType->isMemberPointerType())) {
1630      ArgType = ParamType;
1631      ImpCastExprToType(Arg, ParamType);
1632    } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
1633      ArgType = Context.getPointerType(ArgType);
1634      ImpCastExprToType(Arg, ArgType);
1635    } else if (FunctionDecl *Fn
1636                 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
1637      if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1638        return true;
1639
1640      FixOverloadedFunctionReference(Arg, Fn);
1641      ArgType = Arg->getType();
1642      if (ArgType->isFunctionType() && ParamType->isPointerType()) {
1643        ArgType = Context.getPointerType(Arg->getType());
1644        ImpCastExprToType(Arg, ArgType);
1645      }
1646    }
1647
1648    if (!Context.hasSameUnqualifiedType(ArgType,
1649                                        ParamType.getNonReferenceType())) {
1650      // We can't perform this conversion.
1651      Diag(Arg->getSourceRange().getBegin(),
1652           diag::err_template_arg_not_convertible)
1653        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1654      Diag(Param->getLocation(), diag::note_template_param_here);
1655      return true;
1656    }
1657
1658    if (ParamType->isMemberPointerType()) {
1659      NamedDecl *Member = 0;
1660      if (CheckTemplateArgumentPointerToMember(Arg, Member))
1661        return true;
1662
1663      Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1664      Converted = TemplateArgument(StartLoc, Member);
1665      return false;
1666    }
1667
1668    NamedDecl *Entity = 0;
1669    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1670      return true;
1671
1672    Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1673    Converted = TemplateArgument(StartLoc, Entity);
1674    return false;
1675  }
1676
1677  if (ParamType->isPointerType()) {
1678    //   -- for a non-type template-parameter of type pointer to
1679    //      object, qualification conversions (4.4) and the
1680    //      array-to-pointer conversion (4.2) are applied.
1681    // C++0x also allows a value of std::nullptr_t.
1682    assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
1683           "Only object pointers allowed here");
1684
1685    if (ArgType->isNullPtrType()) {
1686      ArgType = ParamType;
1687      ImpCastExprToType(Arg, ParamType);
1688    } else if (ArgType->isArrayType()) {
1689      ArgType = Context.getArrayDecayedType(ArgType);
1690      ImpCastExprToType(Arg, ArgType);
1691    }
1692
1693    if (IsQualificationConversion(ArgType, ParamType)) {
1694      ArgType = ParamType;
1695      ImpCastExprToType(Arg, ParamType);
1696    }
1697
1698    if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
1699      // We can't perform this conversion.
1700      Diag(Arg->getSourceRange().getBegin(),
1701           diag::err_template_arg_not_convertible)
1702        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1703      Diag(Param->getLocation(), diag::note_template_param_here);
1704      return true;
1705    }
1706
1707    NamedDecl *Entity = 0;
1708    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1709      return true;
1710
1711    Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1712    Converted = TemplateArgument(StartLoc, Entity);
1713    return false;
1714  }
1715
1716  if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1717    //   -- For a non-type template-parameter of type reference to
1718    //      object, no conversions apply. The type referred to by the
1719    //      reference may be more cv-qualified than the (otherwise
1720    //      identical) type of the template-argument. The
1721    //      template-parameter is bound directly to the
1722    //      template-argument, which must be an lvalue.
1723    assert(ParamRefType->getPointeeType()->isObjectType() &&
1724           "Only object references allowed here");
1725
1726    if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
1727      Diag(Arg->getSourceRange().getBegin(),
1728           diag::err_template_arg_no_ref_bind)
1729        << InstantiatedParamType << Arg->getType()
1730        << Arg->getSourceRange();
1731      Diag(Param->getLocation(), diag::note_template_param_here);
1732      return true;
1733    }
1734
1735    unsigned ParamQuals
1736      = Context.getCanonicalType(ParamType).getCVRQualifiers();
1737    unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1738
1739    if ((ParamQuals | ArgQuals) != ParamQuals) {
1740      Diag(Arg->getSourceRange().getBegin(),
1741           diag::err_template_arg_ref_bind_ignores_quals)
1742        << InstantiatedParamType << Arg->getType()
1743        << Arg->getSourceRange();
1744      Diag(Param->getLocation(), diag::note_template_param_here);
1745      return true;
1746    }
1747
1748    NamedDecl *Entity = 0;
1749    if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1750      return true;
1751
1752    Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1753    Converted = TemplateArgument(StartLoc, Entity);
1754    return false;
1755  }
1756
1757  //     -- For a non-type template-parameter of type pointer to data
1758  //        member, qualification conversions (4.4) are applied.
1759  // C++0x allows std::nullptr_t values.
1760  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1761
1762  if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
1763    // Types match exactly: nothing more to do here.
1764  } else if (ArgType->isNullPtrType()) {
1765    ImpCastExprToType(Arg, ParamType);
1766  } else if (IsQualificationConversion(ArgType, ParamType)) {
1767    ImpCastExprToType(Arg, ParamType);
1768  } else {
1769    // We can't perform this conversion.
1770    Diag(Arg->getSourceRange().getBegin(),
1771         diag::err_template_arg_not_convertible)
1772      << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
1773    Diag(Param->getLocation(), diag::note_template_param_here);
1774    return true;
1775  }
1776
1777  NamedDecl *Member = 0;
1778  if (CheckTemplateArgumentPointerToMember(Arg, Member))
1779    return true;
1780
1781  Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1782  Converted = TemplateArgument(StartLoc, Member);
1783  return false;
1784}
1785
1786/// \brief Check a template argument against its corresponding
1787/// template template parameter.
1788///
1789/// This routine implements the semantics of C++ [temp.arg.template].
1790/// It returns true if an error occurred, and false otherwise.
1791bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1792                                 DeclRefExpr *Arg) {
1793  assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1794  TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1795
1796  // C++ [temp.arg.template]p1:
1797  //   A template-argument for a template template-parameter shall be
1798  //   the name of a class template, expressed as id-expression. Only
1799  //   primary class templates are considered when matching the
1800  //   template template argument with the corresponding parameter;
1801  //   partial specializations are not considered even if their
1802  //   parameter lists match that of the template template parameter.
1803  //
1804  // Note that we also allow template template parameters here, which
1805  // will happen when we are dealing with, e.g., class template
1806  // partial specializations.
1807  if (!isa<ClassTemplateDecl>(Template) &&
1808      !isa<TemplateTemplateParmDecl>(Template)) {
1809    assert(isa<FunctionTemplateDecl>(Template) &&
1810           "Only function templates are possible here");
1811    Diag(Arg->getSourceRange().getBegin(),
1812         diag::note_template_arg_refers_here_func)
1813      << Template;
1814  }
1815
1816  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1817                                         Param->getTemplateParameters(),
1818                                         true, true,
1819                                         Arg->getSourceRange().getBegin());
1820}
1821
1822/// \brief Determine whether the given template parameter lists are
1823/// equivalent.
1824///
1825/// \param New  The new template parameter list, typically written in the
1826/// source code as part of a new template declaration.
1827///
1828/// \param Old  The old template parameter list, typically found via
1829/// name lookup of the template declared with this template parameter
1830/// list.
1831///
1832/// \param Complain  If true, this routine will produce a diagnostic if
1833/// the template parameter lists are not equivalent.
1834///
1835/// \param IsTemplateTemplateParm  If true, this routine is being
1836/// called to compare the template parameter lists of a template
1837/// template parameter.
1838///
1839/// \param TemplateArgLoc If this source location is valid, then we
1840/// are actually checking the template parameter list of a template
1841/// argument (New) against the template parameter list of its
1842/// corresponding template template parameter (Old). We produce
1843/// slightly different diagnostics in this scenario.
1844///
1845/// \returns True if the template parameter lists are equal, false
1846/// otherwise.
1847bool
1848Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1849                                     TemplateParameterList *Old,
1850                                     bool Complain,
1851                                     bool IsTemplateTemplateParm,
1852                                     SourceLocation TemplateArgLoc) {
1853  if (Old->size() != New->size()) {
1854    if (Complain) {
1855      unsigned NextDiag = diag::err_template_param_list_different_arity;
1856      if (TemplateArgLoc.isValid()) {
1857        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1858        NextDiag = diag::note_template_param_list_different_arity;
1859      }
1860      Diag(New->getTemplateLoc(), NextDiag)
1861          << (New->size() > Old->size())
1862          << IsTemplateTemplateParm
1863          << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
1864      Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1865        << IsTemplateTemplateParm
1866        << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1867    }
1868
1869    return false;
1870  }
1871
1872  for (TemplateParameterList::iterator OldParm = Old->begin(),
1873         OldParmEnd = Old->end(), NewParm = New->begin();
1874       OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1875    if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
1876      unsigned NextDiag = diag::err_template_param_different_kind;
1877      if (TemplateArgLoc.isValid()) {
1878        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1879        NextDiag = diag::note_template_param_different_kind;
1880      }
1881      Diag((*NewParm)->getLocation(), NextDiag)
1882        << IsTemplateTemplateParm;
1883      Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1884        << IsTemplateTemplateParm;
1885      return false;
1886    }
1887
1888    if (isa<TemplateTypeParmDecl>(*OldParm)) {
1889      // Okay; all template type parameters are equivalent (since we
1890      // know we're at the same index).
1891#if 0
1892      // FIXME: Enable this code in debug mode *after* we properly go through
1893      // and "instantiate" the template parameter lists of template template
1894      // parameters. It's only after this instantiation that (1) any dependent
1895      // types within the template parameter list of the template template
1896      // parameter can be checked, and (2) the template type parameter depths
1897      // will match up.
1898      QualType OldParmType
1899        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1900      QualType NewParmType
1901        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1902      assert(Context.getCanonicalType(OldParmType) ==
1903             Context.getCanonicalType(NewParmType) &&
1904             "type parameter mismatch?");
1905#endif
1906    } else if (NonTypeTemplateParmDecl *OldNTTP
1907                 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1908      // The types of non-type template parameters must agree.
1909      NonTypeTemplateParmDecl *NewNTTP
1910        = cast<NonTypeTemplateParmDecl>(*NewParm);
1911      if (Context.getCanonicalType(OldNTTP->getType()) !=
1912            Context.getCanonicalType(NewNTTP->getType())) {
1913        if (Complain) {
1914          unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1915          if (TemplateArgLoc.isValid()) {
1916            Diag(TemplateArgLoc,
1917                 diag::err_template_arg_template_params_mismatch);
1918            NextDiag = diag::note_template_nontype_parm_different_type;
1919          }
1920          Diag(NewNTTP->getLocation(), NextDiag)
1921            << NewNTTP->getType()
1922            << IsTemplateTemplateParm;
1923          Diag(OldNTTP->getLocation(),
1924               diag::note_template_nontype_parm_prev_declaration)
1925            << OldNTTP->getType();
1926        }
1927        return false;
1928      }
1929    } else {
1930      // The template parameter lists of template template
1931      // parameters must agree.
1932      // FIXME: Could we perform a faster "type" comparison here?
1933      assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1934             "Only template template parameters handled here");
1935      TemplateTemplateParmDecl *OldTTP
1936        = cast<TemplateTemplateParmDecl>(*OldParm);
1937      TemplateTemplateParmDecl *NewTTP
1938        = cast<TemplateTemplateParmDecl>(*NewParm);
1939      if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1940                                          OldTTP->getTemplateParameters(),
1941                                          Complain,
1942                                          /*IsTemplateTemplateParm=*/true,
1943                                          TemplateArgLoc))
1944        return false;
1945    }
1946  }
1947
1948  return true;
1949}
1950
1951/// \brief Check whether a template can be declared within this scope.
1952///
1953/// If the template declaration is valid in this scope, returns
1954/// false. Otherwise, issues a diagnostic and returns true.
1955bool
1956Sema::CheckTemplateDeclScope(Scope *S,
1957                             MultiTemplateParamsArg &TemplateParameterLists) {
1958  assert(TemplateParameterLists.size() > 0 && "Not a template");
1959
1960  // Find the nearest enclosing declaration scope.
1961  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1962         (S->getFlags() & Scope::TemplateParamScope) != 0)
1963    S = S->getParent();
1964
1965  TemplateParameterList *TemplateParams =
1966    static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1967  SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1968  SourceRange TemplateRange
1969    = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1970
1971  // C++ [temp]p2:
1972  //   A template-declaration can appear only as a namespace scope or
1973  //   class scope declaration.
1974  DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1975  while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1976    if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1977      return Diag(TemplateLoc, diag::err_template_linkage)
1978        << TemplateRange;
1979
1980    Ctx = Ctx->getParent();
1981  }
1982
1983  if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1984    return false;
1985
1986  return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1987    << TemplateRange;
1988}
1989
1990/// \brief Check whether a class template specialization or explicit
1991/// instantiation in the current context is well-formed.
1992///
1993/// This routine determines whether a class template specialization or
1994/// explicit instantiation can be declared in the current context
1995/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1996/// appropriate diagnostics if there was an error. It returns true if
1997// there was an error that we cannot recover from, and false otherwise.
1998bool
1999Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2000                                   ClassTemplateSpecializationDecl *PrevDecl,
2001                                            SourceLocation TemplateNameLoc,
2002                                            SourceRange ScopeSpecifierRange,
2003                                            bool PartialSpecialization,
2004                                            bool ExplicitInstantiation) {
2005  // C++ [temp.expl.spec]p2:
2006  //   An explicit specialization shall be declared in the namespace
2007  //   of which the template is a member, or, for member templates, in
2008  //   the namespace of which the enclosing class or enclosing class
2009  //   template is a member. An explicit specialization of a member
2010  //   function, member class or static data member of a class
2011  //   template shall be declared in the namespace of which the class
2012  //   template is a member. Such a declaration may also be a
2013  //   definition. If the declaration is not a definition, the
2014  //   specialization may be defined later in the name- space in which
2015  //   the explicit specialization was declared, or in a namespace
2016  //   that encloses the one in which the explicit specialization was
2017  //   declared.
2018  if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2019    int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
2020    Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
2021      << Kind << ClassTemplate;
2022    return true;
2023  }
2024
2025  DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2026  DeclContext *TemplateContext
2027    = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
2028  if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2029      !ExplicitInstantiation) {
2030    // There is no prior declaration of this entity, so this
2031    // specialization must be in the same context as the template
2032    // itself.
2033    if (DC != TemplateContext) {
2034      if (isa<TranslationUnitDecl>(TemplateContext))
2035        Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
2036          << PartialSpecialization
2037          << ClassTemplate << ScopeSpecifierRange;
2038      else if (isa<NamespaceDecl>(TemplateContext))
2039        Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
2040          << PartialSpecialization << ClassTemplate
2041          << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2042
2043      Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2044    }
2045
2046    return false;
2047  }
2048
2049  // We have a previous declaration of this entity. Make sure that
2050  // this redeclaration (or definition) occurs in an enclosing namespace.
2051  if (!CurContext->Encloses(TemplateContext)) {
2052    // FIXME:  In C++98,  we  would like  to  turn these  errors into  warnings,
2053    // dependent on a -Wc++0x flag.
2054    bool SuppressedDiag = false;
2055    int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
2056    if (isa<TranslationUnitDecl>(TemplateContext)) {
2057      if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2058        Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
2059          << Kind << ClassTemplate << ScopeSpecifierRange;
2060      else
2061        SuppressedDiag = true;
2062    } else if (isa<NamespaceDecl>(TemplateContext)) {
2063      if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2064        Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
2065          << Kind << ClassTemplate
2066          << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2067      else
2068        SuppressedDiag = true;
2069    }
2070
2071    if (!SuppressedDiag)
2072      Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2073  }
2074
2075  return false;
2076}
2077
2078/// \brief Check the non-type template arguments of a class template
2079/// partial specialization according to C++ [temp.class.spec]p9.
2080///
2081/// \param TemplateParams the template parameters of the primary class
2082/// template.
2083///
2084/// \param TemplateArg the template arguments of the class template
2085/// partial specialization.
2086///
2087/// \param MirrorsPrimaryTemplate will be set true if the class
2088/// template partial specialization arguments are identical to the
2089/// implicit template arguments of the primary template. This is not
2090/// necessarily an error (C++0x), and it is left to the caller to diagnose
2091/// this condition when it is an error.
2092///
2093/// \returns true if there was an error, false otherwise.
2094bool Sema::CheckClassTemplatePartialSpecializationArgs(
2095                                        TemplateParameterList *TemplateParams,
2096                             const TemplateArgumentListBuilder &TemplateArgs,
2097                                        bool &MirrorsPrimaryTemplate) {
2098  // FIXME: the interface to this function will have to change to
2099  // accommodate variadic templates.
2100  MirrorsPrimaryTemplate = true;
2101
2102  const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
2103
2104  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2105    // Determine whether the template argument list of the partial
2106    // specialization is identical to the implicit argument list of
2107    // the primary template. The caller may need to diagnostic this as
2108    // an error per C++ [temp.class.spec]p9b3.
2109    if (MirrorsPrimaryTemplate) {
2110      if (TemplateTypeParmDecl *TTP
2111            = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2112        if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
2113              Context.getCanonicalType(ArgList[I].getAsType()))
2114          MirrorsPrimaryTemplate = false;
2115      } else if (TemplateTemplateParmDecl *TTP
2116                   = dyn_cast<TemplateTemplateParmDecl>(
2117                                                 TemplateParams->getParam(I))) {
2118        // FIXME: We should settle on either Declaration storage or
2119        // Expression storage for template template parameters.
2120        TemplateTemplateParmDecl *ArgDecl
2121          = dyn_cast_or_null<TemplateTemplateParmDecl>(
2122                                                  ArgList[I].getAsDecl());
2123        if (!ArgDecl)
2124          if (DeclRefExpr *DRE
2125                = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
2126            ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2127
2128        if (!ArgDecl ||
2129            ArgDecl->getIndex() != TTP->getIndex() ||
2130            ArgDecl->getDepth() != TTP->getDepth())
2131          MirrorsPrimaryTemplate = false;
2132      }
2133    }
2134
2135    NonTypeTemplateParmDecl *Param
2136      = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
2137    if (!Param) {
2138      continue;
2139    }
2140
2141    Expr *ArgExpr = ArgList[I].getAsExpr();
2142    if (!ArgExpr) {
2143      MirrorsPrimaryTemplate = false;
2144      continue;
2145    }
2146
2147    // C++ [temp.class.spec]p8:
2148    //   A non-type argument is non-specialized if it is the name of a
2149    //   non-type parameter. All other non-type arguments are
2150    //   specialized.
2151    //
2152    // Below, we check the two conditions that only apply to
2153    // specialized non-type arguments, so skip any non-specialized
2154    // arguments.
2155    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
2156      if (NonTypeTemplateParmDecl *NTTP
2157            = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2158        if (MirrorsPrimaryTemplate &&
2159            (Param->getIndex() != NTTP->getIndex() ||
2160             Param->getDepth() != NTTP->getDepth()))
2161          MirrorsPrimaryTemplate = false;
2162
2163        continue;
2164      }
2165
2166    // C++ [temp.class.spec]p9:
2167    //   Within the argument list of a class template partial
2168    //   specialization, the following restrictions apply:
2169    //     -- A partially specialized non-type argument expression
2170    //        shall not involve a template parameter of the partial
2171    //        specialization except when the argument expression is a
2172    //        simple identifier.
2173    if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2174      Diag(ArgExpr->getLocStart(),
2175           diag::err_dependent_non_type_arg_in_partial_spec)
2176        << ArgExpr->getSourceRange();
2177      return true;
2178    }
2179
2180    //     -- The type of a template parameter corresponding to a
2181    //        specialized non-type argument shall not be dependent on a
2182    //        parameter of the specialization.
2183    if (Param->getType()->isDependentType()) {
2184      Diag(ArgExpr->getLocStart(),
2185           diag::err_dependent_typed_non_type_arg_in_partial_spec)
2186        << Param->getType()
2187        << ArgExpr->getSourceRange();
2188      Diag(Param->getLocation(), diag::note_template_param_here);
2189      return true;
2190    }
2191
2192    MirrorsPrimaryTemplate = false;
2193  }
2194
2195  return false;
2196}
2197
2198Sema::DeclResult
2199Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2200                                       SourceLocation KWLoc,
2201                                       const CXXScopeSpec &SS,
2202                                       TemplateTy TemplateD,
2203                                       SourceLocation TemplateNameLoc,
2204                                       SourceLocation LAngleLoc,
2205                                       ASTTemplateArgsPtr TemplateArgsIn,
2206                                       SourceLocation *TemplateArgLocs,
2207                                       SourceLocation RAngleLoc,
2208                                       AttributeList *Attr,
2209                               MultiTemplateParamsArg TemplateParameterLists) {
2210  // Find the class template we're specializing
2211  TemplateName Name = TemplateD.getAsVal<TemplateName>();
2212  ClassTemplateDecl *ClassTemplate
2213    = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2214
2215  bool isPartialSpecialization = false;
2216
2217  // Check the validity of the template headers that introduce this
2218  // template.
2219  // FIXME: Once we have member templates, we'll need to check
2220  // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2221  // template<> headers.
2222  if (TemplateParameterLists.size() == 0)
2223    Diag(KWLoc, diag::err_template_spec_needs_header)
2224      << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
2225  else {
2226    TemplateParameterList *TemplateParams
2227      = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2228    if (TemplateParameterLists.size() > 1) {
2229      Diag(TemplateParams->getTemplateLoc(),
2230           diag::err_template_spec_extra_headers);
2231      return true;
2232    }
2233
2234    if (TemplateParams->size() > 0) {
2235      isPartialSpecialization = true;
2236
2237      // C++ [temp.class.spec]p10:
2238      //   The template parameter list of a specialization shall not
2239      //   contain default template argument values.
2240      for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2241        Decl *Param = TemplateParams->getParam(I);
2242        if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2243          if (TTP->hasDefaultArgument()) {
2244            Diag(TTP->getDefaultArgumentLoc(),
2245                 diag::err_default_arg_in_partial_spec);
2246            TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2247          }
2248        } else if (NonTypeTemplateParmDecl *NTTP
2249                     = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2250          if (Expr *DefArg = NTTP->getDefaultArgument()) {
2251            Diag(NTTP->getDefaultArgumentLoc(),
2252                 diag::err_default_arg_in_partial_spec)
2253              << DefArg->getSourceRange();
2254            NTTP->setDefaultArgument(0);
2255            DefArg->Destroy(Context);
2256          }
2257        } else {
2258          TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2259          if (Expr *DefArg = TTP->getDefaultArgument()) {
2260            Diag(TTP->getDefaultArgumentLoc(),
2261                 diag::err_default_arg_in_partial_spec)
2262              << DefArg->getSourceRange();
2263            TTP->setDefaultArgument(0);
2264            DefArg->Destroy(Context);
2265          }
2266        }
2267      }
2268    }
2269  }
2270
2271  // Check that the specialization uses the same tag kind as the
2272  // original template.
2273  TagDecl::TagKind Kind;
2274  switch (TagSpec) {
2275  default: assert(0 && "Unknown tag type!");
2276  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2277  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
2278  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
2279  }
2280  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2281                                    Kind, KWLoc,
2282                                    *ClassTemplate->getIdentifier())) {
2283    Diag(KWLoc, diag::err_use_with_wrong_tag)
2284      << ClassTemplate
2285      << CodeModificationHint::CreateReplacement(KWLoc,
2286                            ClassTemplate->getTemplatedDecl()->getKindName());
2287    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2288         diag::note_previous_use);
2289    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2290  }
2291
2292  // Translate the parser's template argument list in our AST format.
2293  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2294  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2295
2296  // Check that the template argument list is well-formed for this
2297  // template.
2298  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2299                                        TemplateArgs.size());
2300  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
2301                                TemplateArgs.data(), TemplateArgs.size(),
2302                                RAngleLoc, Converted))
2303    return true;
2304
2305  assert((Converted.structuredSize() ==
2306            ClassTemplate->getTemplateParameters()->size()) &&
2307         "Converted template argument list is too short!");
2308
2309  // Find the class template (partial) specialization declaration that
2310  // corresponds to these arguments.
2311  llvm::FoldingSetNodeID ID;
2312  if (isPartialSpecialization) {
2313    bool MirrorsPrimaryTemplate;
2314    if (CheckClassTemplatePartialSpecializationArgs(
2315                                         ClassTemplate->getTemplateParameters(),
2316                                         Converted, MirrorsPrimaryTemplate))
2317      return true;
2318
2319    if (MirrorsPrimaryTemplate) {
2320      // C++ [temp.class.spec]p9b3:
2321      //
2322      //   -- The argument list of the specialization shall not be identical
2323      //      to the implicit argument list of the primary template.
2324      Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2325        << (TK == TK_Definition)
2326        << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2327                                                           RAngleLoc));
2328      return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2329                                ClassTemplate->getIdentifier(),
2330                                TemplateNameLoc,
2331                                Attr,
2332                                move(TemplateParameterLists),
2333                                AS_none);
2334    }
2335
2336    // FIXME: Template parameter list matters, too
2337    ClassTemplatePartialSpecializationDecl::Profile(ID,
2338                                                   Converted.getFlatArguments(),
2339                                                   Converted.flatSize());
2340  }
2341  else
2342    ClassTemplateSpecializationDecl::Profile(ID,
2343                                             Converted.getFlatArguments(),
2344                                             Converted.flatSize());
2345  void *InsertPos = 0;
2346  ClassTemplateSpecializationDecl *PrevDecl = 0;
2347
2348  if (isPartialSpecialization)
2349    PrevDecl
2350      = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2351                                                                    InsertPos);
2352  else
2353    PrevDecl
2354      = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2355
2356  ClassTemplateSpecializationDecl *Specialization = 0;
2357
2358  // Check whether we can declare a class template specialization in
2359  // the current scope.
2360  if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2361                                            TemplateNameLoc,
2362                                            SS.getRange(),
2363                                            isPartialSpecialization,
2364                                            /*ExplicitInstantiation=*/false))
2365    return true;
2366
2367  if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2368    // Since the only prior class template specialization with these
2369    // arguments was referenced but not declared, reuse that
2370    // declaration node as our own, updating its source location to
2371    // reflect our new declaration.
2372    Specialization = PrevDecl;
2373    Specialization->setLocation(TemplateNameLoc);
2374    PrevDecl = 0;
2375  } else if (isPartialSpecialization) {
2376    // Create a new class template partial specialization declaration node.
2377    TemplateParameterList *TemplateParams
2378      = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2379    ClassTemplatePartialSpecializationDecl *PrevPartial
2380      = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2381    ClassTemplatePartialSpecializationDecl *Partial
2382      = ClassTemplatePartialSpecializationDecl::Create(Context,
2383                                             ClassTemplate->getDeclContext(),
2384                                                       TemplateNameLoc,
2385                                                       TemplateParams,
2386                                                       ClassTemplate,
2387                                                       Converted,
2388                                                       PrevPartial);
2389
2390    if (PrevPartial) {
2391      ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2392      ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2393    } else {
2394      ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2395    }
2396    Specialization = Partial;
2397
2398    // Check that all of the template parameters of the class template
2399    // partial specialization are deducible from the template
2400    // arguments. If not, this class template partial specialization
2401    // will never be used.
2402    llvm::SmallVector<bool, 8> DeducibleParams;
2403    DeducibleParams.resize(TemplateParams->size());
2404    MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2405    unsigned NumNonDeducible = 0;
2406    for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2407      if (!DeducibleParams[I])
2408        ++NumNonDeducible;
2409
2410    if (NumNonDeducible) {
2411      Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2412        << (NumNonDeducible > 1)
2413        << SourceRange(TemplateNameLoc, RAngleLoc);
2414      for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2415        if (!DeducibleParams[I]) {
2416          NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2417          if (Param->getDeclName())
2418            Diag(Param->getLocation(),
2419                 diag::note_partial_spec_unused_parameter)
2420              << Param->getDeclName();
2421          else
2422            Diag(Param->getLocation(),
2423                 diag::note_partial_spec_unused_parameter)
2424              << std::string("<anonymous>");
2425        }
2426      }
2427    }
2428
2429  } else {
2430    // Create a new class template specialization declaration node for
2431    // this explicit specialization.
2432    Specialization
2433      = ClassTemplateSpecializationDecl::Create(Context,
2434                                             ClassTemplate->getDeclContext(),
2435                                                TemplateNameLoc,
2436                                                ClassTemplate,
2437                                                Converted,
2438                                                PrevDecl);
2439
2440    if (PrevDecl) {
2441      ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2442      ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2443    } else {
2444      ClassTemplate->getSpecializations().InsertNode(Specialization,
2445                                                     InsertPos);
2446    }
2447  }
2448
2449  // Note that this is an explicit specialization.
2450  Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2451
2452  // Check that this isn't a redefinition of this specialization.
2453  if (TK == TK_Definition) {
2454    if (RecordDecl *Def = Specialization->getDefinition(Context)) {
2455      // FIXME: Should also handle explicit specialization after implicit
2456      // instantiation with a special diagnostic.
2457      SourceRange Range(TemplateNameLoc, RAngleLoc);
2458      Diag(TemplateNameLoc, diag::err_redefinition)
2459        << Context.getTypeDeclType(Specialization) << Range;
2460      Diag(Def->getLocation(), diag::note_previous_definition);
2461      Specialization->setInvalidDecl();
2462      return true;
2463    }
2464  }
2465
2466  // Build the fully-sugared type for this class template
2467  // specialization as the user wrote in the specialization
2468  // itself. This means that we'll pretty-print the type retrieved
2469  // from the specialization's declaration the way that the user
2470  // actually wrote the specialization, rather than formatting the
2471  // name based on the "canonical" representation used to store the
2472  // template arguments in the specialization.
2473  QualType WrittenTy
2474    = Context.getTemplateSpecializationType(Name,
2475                                            TemplateArgs.data(),
2476                                            TemplateArgs.size(),
2477                                  Context.getTypeDeclType(Specialization));
2478  Specialization->setTypeAsWritten(WrittenTy);
2479  TemplateArgsIn.release();
2480
2481  // C++ [temp.expl.spec]p9:
2482  //   A template explicit specialization is in the scope of the
2483  //   namespace in which the template was defined.
2484  //
2485  // We actually implement this paragraph where we set the semantic
2486  // context (in the creation of the ClassTemplateSpecializationDecl),
2487  // but we also maintain the lexical context where the actual
2488  // definition occurs.
2489  Specialization->setLexicalDeclContext(CurContext);
2490
2491  // We may be starting the definition of this specialization.
2492  if (TK == TK_Definition)
2493    Specialization->startDefinition();
2494
2495  // Add the specialization into its lexical context, so that it can
2496  // be seen when iterating through the list of declarations in that
2497  // context. However, specializations are not found by name lookup.
2498  CurContext->addDecl(Context, Specialization);
2499  return DeclPtrTy::make(Specialization);
2500}
2501
2502// Explicit instantiation of a class template specialization
2503Sema::DeclResult
2504Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2505                                 unsigned TagSpec,
2506                                 SourceLocation KWLoc,
2507                                 const CXXScopeSpec &SS,
2508                                 TemplateTy TemplateD,
2509                                 SourceLocation TemplateNameLoc,
2510                                 SourceLocation LAngleLoc,
2511                                 ASTTemplateArgsPtr TemplateArgsIn,
2512                                 SourceLocation *TemplateArgLocs,
2513                                 SourceLocation RAngleLoc,
2514                                 AttributeList *Attr) {
2515  // Find the class template we're specializing
2516  TemplateName Name = TemplateD.getAsVal<TemplateName>();
2517  ClassTemplateDecl *ClassTemplate
2518    = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2519
2520  // Check that the specialization uses the same tag kind as the
2521  // original template.
2522  TagDecl::TagKind Kind;
2523  switch (TagSpec) {
2524  default: assert(0 && "Unknown tag type!");
2525  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2526  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
2527  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
2528  }
2529  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2530                                    Kind, KWLoc,
2531                                    *ClassTemplate->getIdentifier())) {
2532    Diag(KWLoc, diag::err_use_with_wrong_tag)
2533      << ClassTemplate
2534      << CodeModificationHint::CreateReplacement(KWLoc,
2535                            ClassTemplate->getTemplatedDecl()->getKindName());
2536    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2537         diag::note_previous_use);
2538    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2539  }
2540
2541  // C++0x [temp.explicit]p2:
2542  //   [...] An explicit instantiation shall appear in an enclosing
2543  //   namespace of its template. [...]
2544  //
2545  // This is C++ DR 275.
2546  if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2547                                            TemplateNameLoc,
2548                                            SS.getRange(),
2549                                            /*PartialSpecialization=*/false,
2550                                            /*ExplicitInstantiation=*/true))
2551    return true;
2552
2553  // Translate the parser's template argument list in our AST format.
2554  llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2555  translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2556
2557  // Check that the template argument list is well-formed for this
2558  // template.
2559  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2560                                        TemplateArgs.size());
2561  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
2562                                TemplateArgs.data(), TemplateArgs.size(),
2563                                RAngleLoc, Converted))
2564    return true;
2565
2566  assert((Converted.structuredSize() ==
2567            ClassTemplate->getTemplateParameters()->size()) &&
2568         "Converted template argument list is too short!");
2569
2570  // Find the class template specialization declaration that
2571  // corresponds to these arguments.
2572  llvm::FoldingSetNodeID ID;
2573  ClassTemplateSpecializationDecl::Profile(ID,
2574                                           Converted.getFlatArguments(),
2575                                           Converted.flatSize());
2576  void *InsertPos = 0;
2577  ClassTemplateSpecializationDecl *PrevDecl
2578    = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2579
2580  ClassTemplateSpecializationDecl *Specialization = 0;
2581
2582  bool SpecializationRequiresInstantiation = true;
2583  if (PrevDecl) {
2584    if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
2585      // This particular specialization has already been declared or
2586      // instantiated. We cannot explicitly instantiate it.
2587      Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2588        << Context.getTypeDeclType(PrevDecl);
2589      Diag(PrevDecl->getLocation(),
2590           diag::note_previous_explicit_instantiation);
2591      return DeclPtrTy::make(PrevDecl);
2592    }
2593
2594    if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
2595      // C++ DR 259, C++0x [temp.explicit]p4:
2596      //   For a given set of template parameters, if an explicit
2597      //   instantiation of a template appears after a declaration of
2598      //   an explicit specialization for that template, the explicit
2599      //   instantiation has no effect.
2600      if (!getLangOptions().CPlusPlus0x) {
2601        Diag(TemplateNameLoc,
2602             diag::ext_explicit_instantiation_after_specialization)
2603          << Context.getTypeDeclType(PrevDecl);
2604        Diag(PrevDecl->getLocation(),
2605             diag::note_previous_template_specialization);
2606      }
2607
2608      // Create a new class template specialization declaration node
2609      // for this explicit specialization. This node is only used to
2610      // record the existence of this explicit instantiation for
2611      // accurate reproduction of the source code; we don't actually
2612      // use it for anything, since it is semantically irrelevant.
2613      Specialization
2614        = ClassTemplateSpecializationDecl::Create(Context,
2615                                             ClassTemplate->getDeclContext(),
2616                                                  TemplateNameLoc,
2617                                                  ClassTemplate,
2618                                                  Converted, 0);
2619      Specialization->setLexicalDeclContext(CurContext);
2620      CurContext->addDecl(Context, Specialization);
2621      return DeclPtrTy::make(Specialization);
2622    }
2623
2624    // If we have already (implicitly) instantiated this
2625    // specialization, there is less work to do.
2626    if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2627      SpecializationRequiresInstantiation = false;
2628
2629    // Since the only prior class template specialization with these
2630    // arguments was referenced but not declared, reuse that
2631    // declaration node as our own, updating its source location to
2632    // reflect our new declaration.
2633    Specialization = PrevDecl;
2634    Specialization->setLocation(TemplateNameLoc);
2635    PrevDecl = 0;
2636  } else {
2637    // Create a new class template specialization declaration node for
2638    // this explicit specialization.
2639    Specialization
2640      = ClassTemplateSpecializationDecl::Create(Context,
2641                                             ClassTemplate->getDeclContext(),
2642                                                TemplateNameLoc,
2643                                                ClassTemplate,
2644                                                Converted, 0);
2645
2646    ClassTemplate->getSpecializations().InsertNode(Specialization,
2647                                                   InsertPos);
2648  }
2649
2650  // Build the fully-sugared type for this explicit instantiation as
2651  // the user wrote in the explicit instantiation itself. This means
2652  // that we'll pretty-print the type retrieved from the
2653  // specialization's declaration the way that the user actually wrote
2654  // the explicit instantiation, rather than formatting the name based
2655  // on the "canonical" representation used to store the template
2656  // arguments in the specialization.
2657  QualType WrittenTy
2658    = Context.getTemplateSpecializationType(Name,
2659                                            TemplateArgs.data(),
2660                                            TemplateArgs.size(),
2661                                  Context.getTypeDeclType(Specialization));
2662  Specialization->setTypeAsWritten(WrittenTy);
2663  TemplateArgsIn.release();
2664
2665  // Add the explicit instantiation into its lexical context. However,
2666  // since explicit instantiations are never found by name lookup, we
2667  // just put it into the declaration context directly.
2668  Specialization->setLexicalDeclContext(CurContext);
2669  CurContext->addDecl(Context, Specialization);
2670
2671  // C++ [temp.explicit]p3:
2672  //   A definition of a class template or class member template
2673  //   shall be in scope at the point of the explicit instantiation of
2674  //   the class template or class member template.
2675  //
2676  // This check comes when we actually try to perform the
2677  // instantiation.
2678  if (SpecializationRequiresInstantiation)
2679    InstantiateClassTemplateSpecialization(Specialization, true);
2680  else // Instantiate the members of this class template specialization.
2681    InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
2682
2683  return DeclPtrTy::make(Specialization);
2684}
2685
2686// Explicit instantiation of a member class of a class template.
2687Sema::DeclResult
2688Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2689                                 unsigned TagSpec,
2690                                 SourceLocation KWLoc,
2691                                 const CXXScopeSpec &SS,
2692                                 IdentifierInfo *Name,
2693                                 SourceLocation NameLoc,
2694                                 AttributeList *Attr) {
2695
2696  bool Owned = false;
2697  DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
2698                            KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
2699  if (!TagD)
2700    return true;
2701
2702  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2703  if (Tag->isEnum()) {
2704    Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2705      << Context.getTypeDeclType(Tag);
2706    return true;
2707  }
2708
2709  if (Tag->isInvalidDecl())
2710    return true;
2711
2712  CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2713  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2714  if (!Pattern) {
2715    Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2716      << Context.getTypeDeclType(Record);
2717    Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2718    return true;
2719  }
2720
2721  // C++0x [temp.explicit]p2:
2722  //   [...] An explicit instantiation shall appear in an enclosing
2723  //   namespace of its template. [...]
2724  //
2725  // This is C++ DR 275.
2726  if (getLangOptions().CPlusPlus0x) {
2727    // FIXME: In C++98, we would like to turn these errors into warnings,
2728    // dependent on a -Wc++0x flag.
2729    DeclContext *PatternContext
2730      = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2731    if (!CurContext->Encloses(PatternContext)) {
2732      Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2733        << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2734      Diag(Pattern->getLocation(), diag::note_previous_declaration);
2735    }
2736  }
2737
2738  if (!Record->getDefinition(Context)) {
2739    // If the class has a definition, instantiate it (and all of its
2740    // members, recursively).
2741    Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2742    if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
2743                                    getTemplateInstantiationArgs(Record),
2744                                    /*ExplicitInstantiation=*/true))
2745      return true;
2746  } else // Instantiate all of the members of class.
2747    InstantiateClassMembers(TemplateLoc, Record,
2748                            getTemplateInstantiationArgs(Record));
2749
2750  // FIXME: We don't have any representation for explicit instantiations of
2751  // member classes. Such a representation is not needed for compilation, but it
2752  // should be available for clients that want to see all of the declarations in
2753  // the source code.
2754  return TagD;
2755}
2756
2757Sema::TypeResult
2758Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2759                        const IdentifierInfo &II, SourceLocation IdLoc) {
2760  NestedNameSpecifier *NNS
2761    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2762  if (!NNS)
2763    return true;
2764
2765  QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
2766  if (T.isNull())
2767    return true;
2768  return T.getAsOpaquePtr();
2769}
2770
2771Sema::TypeResult
2772Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2773                        SourceLocation TemplateLoc, TypeTy *Ty) {
2774  QualType T = QualType::getFromOpaquePtr(Ty);
2775  NestedNameSpecifier *NNS
2776    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2777  const TemplateSpecializationType *TemplateId
2778    = T->getAsTemplateSpecializationType();
2779  assert(TemplateId && "Expected a template specialization type");
2780
2781  if (NNS->isDependent())
2782    return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2783
2784  return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2785}
2786
2787/// \brief Build the type that describes a C++ typename specifier,
2788/// e.g., "typename T::type".
2789QualType
2790Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2791                        SourceRange Range) {
2792  CXXRecordDecl *CurrentInstantiation = 0;
2793  if (NNS->isDependent()) {
2794    CurrentInstantiation = getCurrentInstantiationOf(NNS);
2795
2796    // If the nested-name-specifier does not refer to the current
2797    // instantiation, then build a typename type.
2798    if (!CurrentInstantiation)
2799      return Context.getTypenameType(NNS, &II);
2800  }
2801
2802  DeclContext *Ctx = 0;
2803
2804  if (CurrentInstantiation)
2805    Ctx = CurrentInstantiation;
2806  else {
2807    CXXScopeSpec SS;
2808    SS.setScopeRep(NNS);
2809    SS.setRange(Range);
2810    if (RequireCompleteDeclContext(SS))
2811      return QualType();
2812
2813    Ctx = computeDeclContext(SS);
2814  }
2815  assert(Ctx && "No declaration context?");
2816
2817  DeclarationName Name(&II);
2818  LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2819                                            false);
2820  unsigned DiagID = 0;
2821  Decl *Referenced = 0;
2822  switch (Result.getKind()) {
2823  case LookupResult::NotFound:
2824    if (Ctx->isTranslationUnit())
2825      DiagID = diag::err_typename_nested_not_found_global;
2826    else
2827      DiagID = diag::err_typename_nested_not_found;
2828    break;
2829
2830  case LookupResult::Found:
2831    if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2832      // We found a type. Build a QualifiedNameType, since the
2833      // typename-specifier was just sugar. FIXME: Tell
2834      // QualifiedNameType that it has a "typename" prefix.
2835      return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2836    }
2837
2838    DiagID = diag::err_typename_nested_not_type;
2839    Referenced = Result.getAsDecl();
2840    break;
2841
2842  case LookupResult::FoundOverloaded:
2843    DiagID = diag::err_typename_nested_not_type;
2844    Referenced = *Result.begin();
2845    break;
2846
2847  case LookupResult::AmbiguousBaseSubobjectTypes:
2848  case LookupResult::AmbiguousBaseSubobjects:
2849  case LookupResult::AmbiguousReference:
2850    DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2851    return QualType();
2852  }
2853
2854  // If we get here, it's because name lookup did not find a
2855  // type. Emit an appropriate diagnostic and return an error.
2856  if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2857    Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2858  else
2859    Diag(Range.getEnd(), DiagID) << Range << Name;
2860  if (Referenced)
2861    Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2862      << Name;
2863  return QualType();
2864}
2865