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