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