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