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