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