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