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