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