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