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