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