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