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