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