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