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