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