1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===//
7 //
8 //  This file implements semantic analysis for C++ templates.
9 //===----------------------------------------------------------------------===//
10 
11 #include "TreeTransform.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclFriend.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/AST/TemplateName.h"
21 #include "clang/AST/TypeVisitor.h"
22 #include "clang/Basic/Builtins.h"
23 #include "clang/Basic/DiagnosticSema.h"
24 #include "clang/Basic/LangOptions.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/SourceLocation.h"
27 #include "clang/Basic/Stack.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/EnterExpressionEvaluationContext.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Overload.h"
34 #include "clang/Sema/ParsedTemplate.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/SemaInternal.h"
37 #include "clang/Sema/Template.h"
38 #include "clang/Sema/TemplateDeduction.h"
39 #include "llvm/ADT/SmallBitVector.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/StringExtras.h"
42 
43 #include <iterator>
44 #include <optional>
45 using namespace clang;
46 using namespace sema;
47 
48 // Exported for use by Parser.
49 SourceRange
getTemplateParamsRange(TemplateParameterList const * const * Ps,unsigned N)50 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
51                               unsigned N) {
52   if (!N) return SourceRange();
53   return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
54 }
55 
getTemplateDepth(Scope * S) const56 unsigned Sema::getTemplateDepth(Scope *S) const {
57   unsigned Depth = 0;
58 
59   // Each template parameter scope represents one level of template parameter
60   // depth.
61   for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
62        TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
63     ++Depth;
64   }
65 
66   // Note that there are template parameters with the given depth.
67   auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
68 
69   // Look for parameters of an enclosing generic lambda. We don't create a
70   // template parameter scope for these.
71   for (FunctionScopeInfo *FSI : getFunctionScopes()) {
72     if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
73       if (!LSI->TemplateParams.empty()) {
74         ParamsAtDepth(LSI->AutoTemplateParameterDepth);
75         break;
76       }
77       if (LSI->GLTemplateParameterList) {
78         ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
79         break;
80       }
81     }
82   }
83 
84   // Look for parameters of an enclosing terse function template. We don't
85   // create a template parameter scope for these either.
86   for (const InventedTemplateParameterInfo &Info :
87        getInventedParameterInfos()) {
88     if (!Info.TemplateParams.empty()) {
89       ParamsAtDepth(Info.AutoTemplateParameterDepth);
90       break;
91     }
92   }
93 
94   return Depth;
95 }
96 
97 /// \brief Determine whether the declaration found is acceptable as the name
98 /// of a template and, if so, return that template declaration. Otherwise,
99 /// returns null.
100 ///
101 /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
102 /// is true. In all other cases it will return a TemplateDecl (or null).
getAsTemplateNameDecl(NamedDecl * D,bool AllowFunctionTemplates,bool AllowDependent)103 NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
104                                        bool AllowFunctionTemplates,
105                                        bool AllowDependent) {
106   D = D->getUnderlyingDecl();
107 
108   if (isa<TemplateDecl>(D)) {
109     if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
110       return nullptr;
111 
112     return D;
113   }
114 
115   if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
116     // C++ [temp.local]p1:
117     //   Like normal (non-template) classes, class templates have an
118     //   injected-class-name (Clause 9). The injected-class-name
119     //   can be used with or without a template-argument-list. When
120     //   it is used without a template-argument-list, it is
121     //   equivalent to the injected-class-name followed by the
122     //   template-parameters of the class template enclosed in
123     //   <>. When it is used with a template-argument-list, it
124     //   refers to the specified class template specialization,
125     //   which could be the current specialization or another
126     //   specialization.
127     if (Record->isInjectedClassName()) {
128       Record = cast<CXXRecordDecl>(Record->getDeclContext());
129       if (Record->getDescribedClassTemplate())
130         return Record->getDescribedClassTemplate();
131 
132       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
133         return Spec->getSpecializedTemplate();
134     }
135 
136     return nullptr;
137   }
138 
139   // 'using Dependent::foo;' can resolve to a template name.
140   // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
141   // injected-class-name).
142   if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
143     return D;
144 
145   return nullptr;
146 }
147 
FilterAcceptableTemplateNames(LookupResult & R,bool AllowFunctionTemplates,bool AllowDependent)148 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
149                                          bool AllowFunctionTemplates,
150                                          bool AllowDependent) {
151   LookupResult::Filter filter = R.makeFilter();
152   while (filter.hasNext()) {
153     NamedDecl *Orig = filter.next();
154     if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
155       filter.erase();
156   }
157   filter.done();
158 }
159 
hasAnyAcceptableTemplateNames(LookupResult & R,bool AllowFunctionTemplates,bool AllowDependent,bool AllowNonTemplateFunctions)160 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
161                                          bool AllowFunctionTemplates,
162                                          bool AllowDependent,
163                                          bool AllowNonTemplateFunctions) {
164   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
165     if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
166       return true;
167     if (AllowNonTemplateFunctions &&
168         isa<FunctionDecl>((*I)->getUnderlyingDecl()))
169       return true;
170   }
171 
172   return false;
173 }
174 
isTemplateName(Scope * S,CXXScopeSpec & SS,bool hasTemplateKeyword,const UnqualifiedId & Name,ParsedType ObjectTypePtr,bool EnteringContext,TemplateTy & TemplateResult,bool & MemberOfUnknownSpecialization,bool Disambiguation)175 TemplateNameKind Sema::isTemplateName(Scope *S,
176                                       CXXScopeSpec &SS,
177                                       bool hasTemplateKeyword,
178                                       const UnqualifiedId &Name,
179                                       ParsedType ObjectTypePtr,
180                                       bool EnteringContext,
181                                       TemplateTy &TemplateResult,
182                                       bool &MemberOfUnknownSpecialization,
183                                       bool Disambiguation) {
184   assert(getLangOpts().CPlusPlus && "No template names in C!");
185 
186   DeclarationName TName;
187   MemberOfUnknownSpecialization = false;
188 
189   switch (Name.getKind()) {
190   case UnqualifiedIdKind::IK_Identifier:
191     TName = DeclarationName(Name.Identifier);
192     break;
193 
194   case UnqualifiedIdKind::IK_OperatorFunctionId:
195     TName = Context.DeclarationNames.getCXXOperatorName(
196                                               Name.OperatorFunctionId.Operator);
197     break;
198 
199   case UnqualifiedIdKind::IK_LiteralOperatorId:
200     TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
201     break;
202 
203   default:
204     return TNK_Non_template;
205   }
206 
207   QualType ObjectType = ObjectTypePtr.get();
208 
209   AssumedTemplateKind AssumedTemplate;
210   LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
211   if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
212                          MemberOfUnknownSpecialization, SourceLocation(),
213                          &AssumedTemplate,
214                          /*AllowTypoCorrection=*/!Disambiguation))
215     return TNK_Non_template;
216 
217   if (AssumedTemplate != AssumedTemplateKind::None) {
218     TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
219     // Let the parser know whether we found nothing or found functions; if we
220     // found nothing, we want to more carefully check whether this is actually
221     // a function template name versus some other kind of undeclared identifier.
222     return AssumedTemplate == AssumedTemplateKind::FoundNothing
223                ? TNK_Undeclared_template
224                : TNK_Function_template;
225   }
226 
227   if (R.empty())
228     return TNK_Non_template;
229 
230   NamedDecl *D = nullptr;
231   UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
232   if (R.isAmbiguous()) {
233     // If we got an ambiguity involving a non-function template, treat this
234     // as a template name, and pick an arbitrary template for error recovery.
235     bool AnyFunctionTemplates = false;
236     for (NamedDecl *FoundD : R) {
237       if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
238         if (isa<FunctionTemplateDecl>(FoundTemplate))
239           AnyFunctionTemplates = true;
240         else {
241           D = FoundTemplate;
242           FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
243           break;
244         }
245       }
246     }
247 
248     // If we didn't find any templates at all, this isn't a template name.
249     // Leave the ambiguity for a later lookup to diagnose.
250     if (!D && !AnyFunctionTemplates) {
251       R.suppressDiagnostics();
252       return TNK_Non_template;
253     }
254 
255     // If the only templates were function templates, filter out the rest.
256     // We'll diagnose the ambiguity later.
257     if (!D)
258       FilterAcceptableTemplateNames(R);
259   }
260 
261   // At this point, we have either picked a single template name declaration D
262   // or we have a non-empty set of results R containing either one template name
263   // declaration or a set of function templates.
264 
265   TemplateName Template;
266   TemplateNameKind TemplateKind;
267 
268   unsigned ResultCount = R.end() - R.begin();
269   if (!D && ResultCount > 1) {
270     // We assume that we'll preserve the qualifier from a function
271     // template name in other ways.
272     Template = Context.getOverloadedTemplateName(R.begin(), R.end());
273     TemplateKind = TNK_Function_template;
274 
275     // We'll do this lookup again later.
276     R.suppressDiagnostics();
277   } else {
278     if (!D) {
279       D = getAsTemplateNameDecl(*R.begin());
280       assert(D && "unambiguous result is not a template name");
281     }
282 
283     if (isa<UnresolvedUsingValueDecl>(D)) {
284       // We don't yet know whether this is a template-name or not.
285       MemberOfUnknownSpecialization = true;
286       return TNK_Non_template;
287     }
288 
289     TemplateDecl *TD = cast<TemplateDecl>(D);
290     Template =
291         FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
292     assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
293     if (SS.isSet() && !SS.isInvalid()) {
294       NestedNameSpecifier *Qualifier = SS.getScopeRep();
295       Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
296                                                   Template);
297     }
298 
299     if (isa<FunctionTemplateDecl>(TD)) {
300       TemplateKind = TNK_Function_template;
301 
302       // We'll do this lookup again later.
303       R.suppressDiagnostics();
304     } else {
305       assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
306              isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
307              isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
308       TemplateKind =
309           isa<VarTemplateDecl>(TD) ? TNK_Var_template :
310           isa<ConceptDecl>(TD) ? TNK_Concept_template :
311           TNK_Type_template;
312     }
313   }
314 
315   TemplateResult = TemplateTy::make(Template);
316   return TemplateKind;
317 }
318 
isDeductionGuideName(Scope * S,const IdentifierInfo & Name,SourceLocation NameLoc,CXXScopeSpec & SS,ParsedTemplateTy * Template)319 bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
320                                 SourceLocation NameLoc, CXXScopeSpec &SS,
321                                 ParsedTemplateTy *Template /*=nullptr*/) {
322   bool MemberOfUnknownSpecialization = false;
323 
324   // We could use redeclaration lookup here, but we don't need to: the
325   // syntactic form of a deduction guide is enough to identify it even
326   // if we can't look up the template name at all.
327   LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
328   if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
329                          /*EnteringContext*/ false,
330                          MemberOfUnknownSpecialization))
331     return false;
332 
333   if (R.empty()) return false;
334   if (R.isAmbiguous()) {
335     // FIXME: Diagnose an ambiguity if we find at least one template.
336     R.suppressDiagnostics();
337     return false;
338   }
339 
340   // We only treat template-names that name type templates as valid deduction
341   // guide names.
342   TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
343   if (!TD || !getAsTypeTemplateDecl(TD))
344     return false;
345 
346   if (Template)
347     *Template = TemplateTy::make(TemplateName(TD));
348   return true;
349 }
350 
DiagnoseUnknownTemplateName(const IdentifierInfo & II,SourceLocation IILoc,Scope * S,const CXXScopeSpec * SS,TemplateTy & SuggestedTemplate,TemplateNameKind & SuggestedKind)351 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
352                                        SourceLocation IILoc,
353                                        Scope *S,
354                                        const CXXScopeSpec *SS,
355                                        TemplateTy &SuggestedTemplate,
356                                        TemplateNameKind &SuggestedKind) {
357   // We can't recover unless there's a dependent scope specifier preceding the
358   // template name.
359   // FIXME: Typo correction?
360   if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
361       computeDeclContext(*SS))
362     return false;
363 
364   // The code is missing a 'template' keyword prior to the dependent template
365   // name.
366   NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
367   Diag(IILoc, diag::err_template_kw_missing)
368     << Qualifier << II.getName()
369     << FixItHint::CreateInsertion(IILoc, "template ");
370   SuggestedTemplate
371     = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
372   SuggestedKind = TNK_Dependent_template_name;
373   return true;
374 }
375 
LookupTemplateName(LookupResult & Found,Scope * S,CXXScopeSpec & SS,QualType ObjectType,bool EnteringContext,bool & MemberOfUnknownSpecialization,RequiredTemplateKind RequiredTemplate,AssumedTemplateKind * ATK,bool AllowTypoCorrection)376 bool Sema::LookupTemplateName(LookupResult &Found,
377                               Scope *S, CXXScopeSpec &SS,
378                               QualType ObjectType,
379                               bool EnteringContext,
380                               bool &MemberOfUnknownSpecialization,
381                               RequiredTemplateKind RequiredTemplate,
382                               AssumedTemplateKind *ATK,
383                               bool AllowTypoCorrection) {
384   if (ATK)
385     *ATK = AssumedTemplateKind::None;
386 
387   if (SS.isInvalid())
388     return true;
389 
390   Found.setTemplateNameLookup(true);
391 
392   // Determine where to perform name lookup
393   MemberOfUnknownSpecialization = false;
394   DeclContext *LookupCtx = nullptr;
395   bool IsDependent = false;
396   if (!ObjectType.isNull()) {
397     // This nested-name-specifier occurs in a member access expression, e.g.,
398     // x->B::f, and we are looking into the type of the object.
399     assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
400     LookupCtx = computeDeclContext(ObjectType);
401     IsDependent = !LookupCtx && ObjectType->isDependentType();
402     assert((IsDependent || !ObjectType->isIncompleteType() ||
403             !ObjectType->getAs<TagType>() ||
404             ObjectType->castAs<TagType>()->isBeingDefined()) &&
405            "Caller should have completed object type");
406 
407     // Template names cannot appear inside an Objective-C class or object type
408     // or a vector type.
409     //
410     // FIXME: This is wrong. For example:
411     //
412     //   template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
413     //   Vec<int> vi;
414     //   vi.Vec<int>::~Vec<int>();
415     //
416     // ... should be accepted but we will not treat 'Vec' as a template name
417     // here. The right thing to do would be to check if the name is a valid
418     // vector component name, and look up a template name if not. And similarly
419     // for lookups into Objective-C class and object types, where the same
420     // problem can arise.
421     if (ObjectType->isObjCObjectOrInterfaceType() ||
422         ObjectType->isVectorType()) {
423       Found.clear();
424       return false;
425     }
426   } else if (SS.isNotEmpty()) {
427     // This nested-name-specifier occurs after another nested-name-specifier,
428     // so long into the context associated with the prior nested-name-specifier.
429     LookupCtx = computeDeclContext(SS, EnteringContext);
430     IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
431 
432     // The declaration context must be complete.
433     if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
434       return true;
435   }
436 
437   bool ObjectTypeSearchedInScope = false;
438   bool AllowFunctionTemplatesInLookup = true;
439   if (LookupCtx) {
440     // Perform "qualified" name lookup into the declaration context we
441     // computed, which is either the type of the base of a member access
442     // expression or the declaration context associated with a prior
443     // nested-name-specifier.
444     LookupQualifiedName(Found, LookupCtx);
445 
446     // FIXME: The C++ standard does not clearly specify what happens in the
447     // case where the object type is dependent, and implementations vary. In
448     // Clang, we treat a name after a . or -> as a template-name if lookup
449     // finds a non-dependent member or member of the current instantiation that
450     // is a type template, or finds no such members and lookup in the context
451     // of the postfix-expression finds a type template. In the latter case, the
452     // name is nonetheless dependent, and we may resolve it to a member of an
453     // unknown specialization when we come to instantiate the template.
454     IsDependent |= Found.wasNotFoundInCurrentInstantiation();
455   }
456 
457   if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
458     // C++ [basic.lookup.classref]p1:
459     //   In a class member access expression (5.2.5), if the . or -> token is
460     //   immediately followed by an identifier followed by a <, the
461     //   identifier must be looked up to determine whether the < is the
462     //   beginning of a template argument list (14.2) or a less-than operator.
463     //   The identifier is first looked up in the class of the object
464     //   expression. If the identifier is not found, it is then looked up in
465     //   the context of the entire postfix-expression and shall name a class
466     //   template.
467     if (S)
468       LookupName(Found, S);
469 
470     if (!ObjectType.isNull()) {
471       //  FIXME: We should filter out all non-type templates here, particularly
472       //  variable templates and concepts. But the exclusion of alias templates
473       //  and template template parameters is a wording defect.
474       AllowFunctionTemplatesInLookup = false;
475       ObjectTypeSearchedInScope = true;
476     }
477 
478     IsDependent |= Found.wasNotFoundInCurrentInstantiation();
479   }
480 
481   if (Found.isAmbiguous())
482     return false;
483 
484   if (ATK && SS.isEmpty() && ObjectType.isNull() &&
485       !RequiredTemplate.hasTemplateKeyword()) {
486     // C++2a [temp.names]p2:
487     //   A name is also considered to refer to a template if it is an
488     //   unqualified-id followed by a < and name lookup finds either one or more
489     //   functions or finds nothing.
490     //
491     // To keep our behavior consistent, we apply the "finds nothing" part in
492     // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
493     // successfully form a call to an undeclared template-id.
494     bool AllFunctions =
495         getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
496           return isa<FunctionDecl>(ND->getUnderlyingDecl());
497         });
498     if (AllFunctions || (Found.empty() && !IsDependent)) {
499       // If lookup found any functions, or if this is a name that can only be
500       // used for a function, then strongly assume this is a function
501       // template-id.
502       *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
503                  ? AssumedTemplateKind::FoundNothing
504                  : AssumedTemplateKind::FoundFunctions;
505       Found.clear();
506       return false;
507     }
508   }
509 
510   if (Found.empty() && !IsDependent && AllowTypoCorrection) {
511     // If we did not find any names, and this is not a disambiguation, attempt
512     // to correct any typos.
513     DeclarationName Name = Found.getLookupName();
514     Found.clear();
515     // Simple filter callback that, for keywords, only accepts the C++ *_cast
516     DefaultFilterCCC FilterCCC{};
517     FilterCCC.WantTypeSpecifiers = false;
518     FilterCCC.WantExpressionKeywords = false;
519     FilterCCC.WantRemainingKeywords = false;
520     FilterCCC.WantCXXNamedCasts = true;
521     if (TypoCorrection Corrected =
522             CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
523                         &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
524       if (auto *ND = Corrected.getFoundDecl())
525         Found.addDecl(ND);
526       FilterAcceptableTemplateNames(Found);
527       if (Found.isAmbiguous()) {
528         Found.clear();
529       } else if (!Found.empty()) {
530         Found.setLookupName(Corrected.getCorrection());
531         if (LookupCtx) {
532           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
533           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
534                                   Name.getAsString() == CorrectedStr;
535           diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
536                                     << Name << LookupCtx << DroppedSpecifier
537                                     << SS.getRange());
538         } else {
539           diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
540         }
541       }
542     }
543   }
544 
545   NamedDecl *ExampleLookupResult =
546       Found.empty() ? nullptr : Found.getRepresentativeDecl();
547   FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
548   if (Found.empty()) {
549     if (IsDependent) {
550       MemberOfUnknownSpecialization = true;
551       return false;
552     }
553 
554     // If a 'template' keyword was used, a lookup that finds only non-template
555     // names is an error.
556     if (ExampleLookupResult && RequiredTemplate) {
557       Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
558           << Found.getLookupName() << SS.getRange()
559           << RequiredTemplate.hasTemplateKeyword()
560           << RequiredTemplate.getTemplateKeywordLoc();
561       Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
562            diag::note_template_kw_refers_to_non_template)
563           << Found.getLookupName();
564       return true;
565     }
566 
567     return false;
568   }
569 
570   if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
571       !getLangOpts().CPlusPlus11) {
572     // C++03 [basic.lookup.classref]p1:
573     //   [...] If the lookup in the class of the object expression finds a
574     //   template, the name is also looked up in the context of the entire
575     //   postfix-expression and [...]
576     //
577     // Note: C++11 does not perform this second lookup.
578     LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
579                             LookupOrdinaryName);
580     FoundOuter.setTemplateNameLookup(true);
581     LookupName(FoundOuter, S);
582     // FIXME: We silently accept an ambiguous lookup here, in violation of
583     // [basic.lookup]/1.
584     FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
585 
586     NamedDecl *OuterTemplate;
587     if (FoundOuter.empty()) {
588       //   - if the name is not found, the name found in the class of the
589       //     object expression is used, otherwise
590     } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
591                !(OuterTemplate =
592                      getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
593       //   - if the name is found in the context of the entire
594       //     postfix-expression and does not name a class template, the name
595       //     found in the class of the object expression is used, otherwise
596       FoundOuter.clear();
597     } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
598       //   - if the name found is a class template, it must refer to the same
599       //     entity as the one found in the class of the object expression,
600       //     otherwise the program is ill-formed.
601       if (!Found.isSingleResult() ||
602           getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
603               OuterTemplate->getCanonicalDecl()) {
604         Diag(Found.getNameLoc(),
605              diag::ext_nested_name_member_ref_lookup_ambiguous)
606           << Found.getLookupName()
607           << ObjectType;
608         Diag(Found.getRepresentativeDecl()->getLocation(),
609              diag::note_ambig_member_ref_object_type)
610           << ObjectType;
611         Diag(FoundOuter.getFoundDecl()->getLocation(),
612              diag::note_ambig_member_ref_scope);
613 
614         // Recover by taking the template that we found in the object
615         // expression's type.
616       }
617     }
618   }
619 
620   return false;
621 }
622 
diagnoseExprIntendedAsTemplateName(Scope * S,ExprResult TemplateName,SourceLocation Less,SourceLocation Greater)623 void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
624                                               SourceLocation Less,
625                                               SourceLocation Greater) {
626   if (TemplateName.isInvalid())
627     return;
628 
629   DeclarationNameInfo NameInfo;
630   CXXScopeSpec SS;
631   LookupNameKind LookupKind;
632 
633   DeclContext *LookupCtx = nullptr;
634   NamedDecl *Found = nullptr;
635   bool MissingTemplateKeyword = false;
636 
637   // Figure out what name we looked up.
638   if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
639     NameInfo = DRE->getNameInfo();
640     SS.Adopt(DRE->getQualifierLoc());
641     LookupKind = LookupOrdinaryName;
642     Found = DRE->getFoundDecl();
643   } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
644     NameInfo = ME->getMemberNameInfo();
645     SS.Adopt(ME->getQualifierLoc());
646     LookupKind = LookupMemberName;
647     LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
648     Found = ME->getMemberDecl();
649   } else if (auto *DSDRE =
650                  dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
651     NameInfo = DSDRE->getNameInfo();
652     SS.Adopt(DSDRE->getQualifierLoc());
653     MissingTemplateKeyword = true;
654   } else if (auto *DSME =
655                  dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
656     NameInfo = DSME->getMemberNameInfo();
657     SS.Adopt(DSME->getQualifierLoc());
658     MissingTemplateKeyword = true;
659   } else {
660     llvm_unreachable("unexpected kind of potential template name");
661   }
662 
663   // If this is a dependent-scope lookup, diagnose that the 'template' keyword
664   // was missing.
665   if (MissingTemplateKeyword) {
666     Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
667         << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
668     return;
669   }
670 
671   // Try to correct the name by looking for templates and C++ named casts.
672   struct TemplateCandidateFilter : CorrectionCandidateCallback {
673     Sema &S;
674     TemplateCandidateFilter(Sema &S) : S(S) {
675       WantTypeSpecifiers = false;
676       WantExpressionKeywords = false;
677       WantRemainingKeywords = false;
678       WantCXXNamedCasts = true;
679     };
680     bool ValidateCandidate(const TypoCorrection &Candidate) override {
681       if (auto *ND = Candidate.getCorrectionDecl())
682         return S.getAsTemplateNameDecl(ND);
683       return Candidate.isKeyword();
684     }
685 
686     std::unique_ptr<CorrectionCandidateCallback> clone() override {
687       return std::make_unique<TemplateCandidateFilter>(*this);
688     }
689   };
690 
691   DeclarationName Name = NameInfo.getName();
692   TemplateCandidateFilter CCC(*this);
693   if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
694                                              CTK_ErrorRecovery, LookupCtx)) {
695     auto *ND = Corrected.getFoundDecl();
696     if (ND)
697       ND = getAsTemplateNameDecl(ND);
698     if (ND || Corrected.isKeyword()) {
699       if (LookupCtx) {
700         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
701         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
702                                 Name.getAsString() == CorrectedStr;
703         diagnoseTypo(Corrected,
704                      PDiag(diag::err_non_template_in_member_template_id_suggest)
705                          << Name << LookupCtx << DroppedSpecifier
706                          << SS.getRange(), false);
707       } else {
708         diagnoseTypo(Corrected,
709                      PDiag(diag::err_non_template_in_template_id_suggest)
710                          << Name, false);
711       }
712       if (Found)
713         Diag(Found->getLocation(),
714              diag::note_non_template_in_template_id_found);
715       return;
716     }
717   }
718 
719   Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
720     << Name << SourceRange(Less, Greater);
721   if (Found)
722     Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
723 }
724 
725 /// ActOnDependentIdExpression - Handle a dependent id-expression that
726 /// was just parsed.  This is only possible with an explicit scope
727 /// specifier naming a dependent type.
728 ExprResult
ActOnDependentIdExpression(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,bool isAddressOfOperand,const TemplateArgumentListInfo * TemplateArgs)729 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
730                                  SourceLocation TemplateKWLoc,
731                                  const DeclarationNameInfo &NameInfo,
732                                  bool isAddressOfOperand,
733                            const TemplateArgumentListInfo *TemplateArgs) {
734   DeclContext *DC = getFunctionLevelDeclContext();
735 
736   // C++11 [expr.prim.general]p12:
737   //   An id-expression that denotes a non-static data member or non-static
738   //   member function of a class can only be used:
739   //   (...)
740   //   - if that id-expression denotes a non-static data member and it
741   //     appears in an unevaluated operand.
742   //
743   // If this might be the case, form a DependentScopeDeclRefExpr instead of a
744   // CXXDependentScopeMemberExpr. The former can instantiate to either
745   // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
746   // always a MemberExpr.
747   bool MightBeCxx11UnevalField =
748       getLangOpts().CPlusPlus11 && isUnevaluatedContext();
749 
750   // Check if the nested name specifier is an enum type.
751   bool IsEnum = false;
752   if (NestedNameSpecifier *NNS = SS.getScopeRep())
753     IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType());
754 
755   if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
756       isa<CXXMethodDecl>(DC) &&
757       cast<CXXMethodDecl>(DC)->isImplicitObjectMemberFunction()) {
758     QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType().getNonReferenceType();
759 
760     // Since the 'this' expression is synthesized, we don't need to
761     // perform the double-lookup check.
762     NamedDecl *FirstQualifierInScope = nullptr;
763 
764     return CXXDependentScopeMemberExpr::Create(
765         Context, /*This=*/nullptr, ThisType,
766         /*IsArrow=*/!Context.getLangOpts().HLSL,
767         /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
768         FirstQualifierInScope, NameInfo, TemplateArgs);
769   }
770 
771   return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
772 }
773 
774 ExprResult
BuildDependentDeclRefExpr(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * TemplateArgs)775 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
776                                 SourceLocation TemplateKWLoc,
777                                 const DeclarationNameInfo &NameInfo,
778                                 const TemplateArgumentListInfo *TemplateArgs) {
779   // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
780   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
781   if (!QualifierLoc)
782     return ExprError();
783 
784   return DependentScopeDeclRefExpr::Create(
785       Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
786 }
787 
788 
789 /// Determine whether we would be unable to instantiate this template (because
790 /// it either has no definition, or is in the process of being instantiated).
DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,NamedDecl * Instantiation,bool InstantiatedFromMember,const NamedDecl * Pattern,const NamedDecl * PatternDef,TemplateSpecializationKind TSK,bool Complain)791 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
792                                           NamedDecl *Instantiation,
793                                           bool InstantiatedFromMember,
794                                           const NamedDecl *Pattern,
795                                           const NamedDecl *PatternDef,
796                                           TemplateSpecializationKind TSK,
797                                           bool Complain /*= true*/) {
798   assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
799          isa<VarDecl>(Instantiation));
800 
801   bool IsEntityBeingDefined = false;
802   if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
803     IsEntityBeingDefined = TD->isBeingDefined();
804 
805   if (PatternDef && !IsEntityBeingDefined) {
806     NamedDecl *SuggestedDef = nullptr;
807     if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
808                                 &SuggestedDef,
809                                 /*OnlyNeedComplete*/ false)) {
810       // If we're allowed to diagnose this and recover, do so.
811       bool Recover = Complain && !isSFINAEContext();
812       if (Complain)
813         diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
814                               Sema::MissingImportKind::Definition, Recover);
815       return !Recover;
816     }
817     return false;
818   }
819 
820   if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
821     return true;
822 
823   QualType InstantiationTy;
824   if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
825     InstantiationTy = Context.getTypeDeclType(TD);
826   if (PatternDef) {
827     Diag(PointOfInstantiation,
828          diag::err_template_instantiate_within_definition)
829       << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
830       << InstantiationTy;
831     // Not much point in noting the template declaration here, since
832     // we're lexically inside it.
833     Instantiation->setInvalidDecl();
834   } else if (InstantiatedFromMember) {
835     if (isa<FunctionDecl>(Instantiation)) {
836       Diag(PointOfInstantiation,
837            diag::err_explicit_instantiation_undefined_member)
838         << /*member function*/ 1 << Instantiation->getDeclName()
839         << Instantiation->getDeclContext();
840       Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
841     } else {
842       assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
843       Diag(PointOfInstantiation,
844            diag::err_implicit_instantiate_member_undefined)
845         << InstantiationTy;
846       Diag(Pattern->getLocation(), diag::note_member_declared_at);
847     }
848   } else {
849     if (isa<FunctionDecl>(Instantiation)) {
850       Diag(PointOfInstantiation,
851            diag::err_explicit_instantiation_undefined_func_template)
852         << Pattern;
853       Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
854     } else if (isa<TagDecl>(Instantiation)) {
855       Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
856         << (TSK != TSK_ImplicitInstantiation)
857         << InstantiationTy;
858       NoteTemplateLocation(*Pattern);
859     } else {
860       assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
861       if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
862         Diag(PointOfInstantiation,
863              diag::err_explicit_instantiation_undefined_var_template)
864           << Instantiation;
865         Instantiation->setInvalidDecl();
866       } else
867         Diag(PointOfInstantiation,
868              diag::err_explicit_instantiation_undefined_member)
869           << /*static data member*/ 2 << Instantiation->getDeclName()
870           << Instantiation->getDeclContext();
871       Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
872     }
873   }
874 
875   // In general, Instantiation isn't marked invalid to get more than one
876   // error for multiple undefined instantiations. But the code that does
877   // explicit declaration -> explicit definition conversion can't handle
878   // invalid declarations, so mark as invalid in that case.
879   if (TSK == TSK_ExplicitInstantiationDeclaration)
880     Instantiation->setInvalidDecl();
881   return true;
882 }
883 
884 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
885 /// that the template parameter 'PrevDecl' is being shadowed by a new
886 /// declaration at location Loc. Returns true to indicate that this is
887 /// an error, and false otherwise.
DiagnoseTemplateParameterShadow(SourceLocation Loc,Decl * PrevDecl)888 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
889   assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
890 
891   // C++ [temp.local]p4:
892   //   A template-parameter shall not be redeclared within its
893   //   scope (including nested scopes).
894   //
895   // Make this a warning when MSVC compatibility is requested.
896   unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
897                                              : diag::err_template_param_shadow;
898   const auto *ND = cast<NamedDecl>(PrevDecl);
899   Diag(Loc, DiagId) << ND->getDeclName();
900   NoteTemplateParameterLocation(*ND);
901 }
902 
903 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
904 /// the parameter D to reference the templated declaration and return a pointer
905 /// to the template declaration. Otherwise, do nothing to D and return null.
AdjustDeclIfTemplate(Decl * & D)906 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
907   if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
908     D = Temp->getTemplatedDecl();
909     return Temp;
910   }
911   return nullptr;
912 }
913 
getTemplatePackExpansion(SourceLocation EllipsisLoc) const914 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
915                                              SourceLocation EllipsisLoc) const {
916   assert(Kind == Template &&
917          "Only template template arguments can be pack expansions here");
918   assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
919          "Template template argument pack expansion without packs");
920   ParsedTemplateArgument Result(*this);
921   Result.EllipsisLoc = EllipsisLoc;
922   return Result;
923 }
924 
translateTemplateArgument(Sema & SemaRef,const ParsedTemplateArgument & Arg)925 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
926                                             const ParsedTemplateArgument &Arg) {
927 
928   switch (Arg.getKind()) {
929   case ParsedTemplateArgument::Type: {
930     TypeSourceInfo *DI;
931     QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
932     if (!DI)
933       DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
934     return TemplateArgumentLoc(TemplateArgument(T), DI);
935   }
936 
937   case ParsedTemplateArgument::NonType: {
938     Expr *E = static_cast<Expr *>(Arg.getAsExpr());
939     return TemplateArgumentLoc(TemplateArgument(E), E);
940   }
941 
942   case ParsedTemplateArgument::Template: {
943     TemplateName Template = Arg.getAsTemplate().get();
944     TemplateArgument TArg;
945     if (Arg.getEllipsisLoc().isValid())
946       TArg = TemplateArgument(Template, std::optional<unsigned int>());
947     else
948       TArg = Template;
949     return TemplateArgumentLoc(
950         SemaRef.Context, TArg,
951         Arg.getScopeSpec().getWithLocInContext(SemaRef.Context),
952         Arg.getLocation(), Arg.getEllipsisLoc());
953   }
954   }
955 
956   llvm_unreachable("Unhandled parsed template argument");
957 }
958 
959 /// Translates template arguments as provided by the parser
960 /// into template arguments used by semantic analysis.
translateTemplateArguments(const ASTTemplateArgsPtr & TemplateArgsIn,TemplateArgumentListInfo & TemplateArgs)961 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
962                                       TemplateArgumentListInfo &TemplateArgs) {
963  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
964    TemplateArgs.addArgument(translateTemplateArgument(*this,
965                                                       TemplateArgsIn[I]));
966 }
967 
maybeDiagnoseTemplateParameterShadow(Sema & SemaRef,Scope * S,SourceLocation Loc,IdentifierInfo * Name)968 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
969                                                  SourceLocation Loc,
970                                                  IdentifierInfo *Name) {
971   NamedDecl *PrevDecl = SemaRef.LookupSingleName(
972       S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
973   if (PrevDecl && PrevDecl->isTemplateParameter())
974     SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
975 }
976 
977 /// Convert a parsed type into a parsed template argument. This is mostly
978 /// trivial, except that we may have parsed a C++17 deduced class template
979 /// specialization type, in which case we should form a template template
980 /// argument instead of a type template argument.
ActOnTemplateTypeArgument(TypeResult ParsedType)981 ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
982   TypeSourceInfo *TInfo;
983   QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
984   if (T.isNull())
985     return ParsedTemplateArgument();
986   assert(TInfo && "template argument with no location");
987 
988   // If we might have formed a deduced template specialization type, convert
989   // it to a template template argument.
990   if (getLangOpts().CPlusPlus17) {
991     TypeLoc TL = TInfo->getTypeLoc();
992     SourceLocation EllipsisLoc;
993     if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
994       EllipsisLoc = PET.getEllipsisLoc();
995       TL = PET.getPatternLoc();
996     }
997 
998     CXXScopeSpec SS;
999     if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
1000       SS.Adopt(ET.getQualifierLoc());
1001       TL = ET.getNamedTypeLoc();
1002     }
1003 
1004     if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1005       TemplateName Name = DTST.getTypePtr()->getTemplateName();
1006       if (SS.isSet())
1007         Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
1008                                                 /*HasTemplateKeyword=*/false,
1009                                                 Name);
1010       ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
1011                                     DTST.getTemplateNameLoc());
1012       if (EllipsisLoc.isValid())
1013         Result = Result.getTemplatePackExpansion(EllipsisLoc);
1014       return Result;
1015     }
1016   }
1017 
1018   // This is a normal type template argument. Note, if the type template
1019   // argument is an injected-class-name for a template, it has a dual nature
1020   // and can be used as either a type or a template. We handle that in
1021   // convertTypeTemplateArgumentToTemplate.
1022   return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1023                                 ParsedType.get().getAsOpaquePtr(),
1024                                 TInfo->getTypeLoc().getBeginLoc());
1025 }
1026 
1027 /// ActOnTypeParameter - Called when a C++ template type parameter
1028 /// (e.g., "typename T") has been parsed. Typename specifies whether
1029 /// the keyword "typename" was used to declare the type parameter
1030 /// (otherwise, "class" was used), and KeyLoc is the location of the
1031 /// "class" or "typename" keyword. ParamName is the name of the
1032 /// parameter (NULL indicates an unnamed template parameter) and
1033 /// ParamNameLoc is the location of the parameter name (if any).
1034 /// If the type parameter has a default argument, it will be added
1035 /// later via ActOnTypeParameterDefault.
ActOnTypeParameter(Scope * S,bool Typename,SourceLocation EllipsisLoc,SourceLocation KeyLoc,IdentifierInfo * ParamName,SourceLocation ParamNameLoc,unsigned Depth,unsigned Position,SourceLocation EqualLoc,ParsedType DefaultArg,bool HasTypeConstraint)1036 NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1037                                     SourceLocation EllipsisLoc,
1038                                     SourceLocation KeyLoc,
1039                                     IdentifierInfo *ParamName,
1040                                     SourceLocation ParamNameLoc,
1041                                     unsigned Depth, unsigned Position,
1042                                     SourceLocation EqualLoc,
1043                                     ParsedType DefaultArg,
1044                                     bool HasTypeConstraint) {
1045   assert(S->isTemplateParamScope() &&
1046          "Template type parameter not in template parameter scope!");
1047 
1048   bool IsParameterPack = EllipsisLoc.isValid();
1049   TemplateTypeParmDecl *Param
1050     = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1051                                    KeyLoc, ParamNameLoc, Depth, Position,
1052                                    ParamName, Typename, IsParameterPack,
1053                                    HasTypeConstraint);
1054   Param->setAccess(AS_public);
1055 
1056   if (Param->isParameterPack())
1057     if (auto *LSI = getEnclosingLambda())
1058       LSI->LocalPacks.push_back(Param);
1059 
1060   if (ParamName) {
1061     maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1062 
1063     // Add the template parameter into the current scope.
1064     S->AddDecl(Param);
1065     IdResolver.AddDecl(Param);
1066   }
1067 
1068   // C++0x [temp.param]p9:
1069   //   A default template-argument may be specified for any kind of
1070   //   template-parameter that is not a template parameter pack.
1071   if (DefaultArg && IsParameterPack) {
1072     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1073     DefaultArg = nullptr;
1074   }
1075 
1076   // Handle the default argument, if provided.
1077   if (DefaultArg) {
1078     TypeSourceInfo *DefaultTInfo;
1079     GetTypeFromParser(DefaultArg, &DefaultTInfo);
1080 
1081     assert(DefaultTInfo && "expected source information for type");
1082 
1083     // Check for unexpanded parameter packs.
1084     if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1085                                         UPPC_DefaultArgument))
1086       return Param;
1087 
1088     // Check the template argument itself.
1089     if (CheckTemplateArgument(DefaultTInfo)) {
1090       Param->setInvalidDecl();
1091       return Param;
1092     }
1093 
1094     Param->setDefaultArgument(DefaultTInfo);
1095   }
1096 
1097   return Param;
1098 }
1099 
1100 /// Convert the parser's template argument list representation into our form.
1101 static TemplateArgumentListInfo
makeTemplateArgumentListInfo(Sema & S,TemplateIdAnnotation & TemplateId)1102 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1103   TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1104                                         TemplateId.RAngleLoc);
1105   ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1106                                      TemplateId.NumArgs);
1107   S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1108   return TemplateArgs;
1109 }
1110 
CheckTypeConstraint(TemplateIdAnnotation * TypeConstr)1111 bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1112 
1113   TemplateName TN = TypeConstr->Template.get();
1114   ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1115 
1116   // C++2a [temp.param]p4:
1117   //     [...] The concept designated by a type-constraint shall be a type
1118   //     concept ([temp.concept]).
1119   if (!CD->isTypeConcept()) {
1120     Diag(TypeConstr->TemplateNameLoc,
1121          diag::err_type_constraint_non_type_concept);
1122     return true;
1123   }
1124 
1125   bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1126 
1127   if (!WereArgsSpecified &&
1128       CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1129     Diag(TypeConstr->TemplateNameLoc,
1130          diag::err_type_constraint_missing_arguments)
1131         << CD;
1132     return true;
1133   }
1134   return false;
1135 }
1136 
ActOnTypeConstraint(const CXXScopeSpec & SS,TemplateIdAnnotation * TypeConstr,TemplateTypeParmDecl * ConstrainedParameter,SourceLocation EllipsisLoc)1137 bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1138                                TemplateIdAnnotation *TypeConstr,
1139                                TemplateTypeParmDecl *ConstrainedParameter,
1140                                SourceLocation EllipsisLoc) {
1141   return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1142                              false);
1143 }
1144 
BuildTypeConstraint(const CXXScopeSpec & SS,TemplateIdAnnotation * TypeConstr,TemplateTypeParmDecl * ConstrainedParameter,SourceLocation EllipsisLoc,bool AllowUnexpandedPack)1145 bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1146                                TemplateIdAnnotation *TypeConstr,
1147                                TemplateTypeParmDecl *ConstrainedParameter,
1148                                SourceLocation EllipsisLoc,
1149                                bool AllowUnexpandedPack) {
1150 
1151   if (CheckTypeConstraint(TypeConstr))
1152     return true;
1153 
1154   TemplateName TN = TypeConstr->Template.get();
1155   ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1156 
1157   DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1158                                   TypeConstr->TemplateNameLoc);
1159 
1160   TemplateArgumentListInfo TemplateArgs;
1161   if (TypeConstr->LAngleLoc.isValid()) {
1162     TemplateArgs =
1163         makeTemplateArgumentListInfo(*this, *TypeConstr);
1164 
1165     if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1166       for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1167         if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint))
1168           return true;
1169       }
1170     }
1171   }
1172   return AttachTypeConstraint(
1173       SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1174       ConceptName, CD,
1175       TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1176       ConstrainedParameter, EllipsisLoc);
1177 }
1178 
1179 template<typename ArgumentLocAppender>
formImmediatelyDeclaredConstraint(Sema & S,NestedNameSpecifierLoc NS,DeclarationNameInfo NameInfo,ConceptDecl * NamedConcept,SourceLocation LAngleLoc,SourceLocation RAngleLoc,QualType ConstrainedType,SourceLocation ParamNameLoc,ArgumentLocAppender Appender,SourceLocation EllipsisLoc)1180 static ExprResult formImmediatelyDeclaredConstraint(
1181     Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1182     ConceptDecl *NamedConcept, SourceLocation LAngleLoc,
1183     SourceLocation RAngleLoc, QualType ConstrainedType,
1184     SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1185     SourceLocation EllipsisLoc) {
1186 
1187   TemplateArgumentListInfo ConstraintArgs;
1188   ConstraintArgs.addArgument(
1189     S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1190                                     /*NTTPType=*/QualType(), ParamNameLoc));
1191 
1192   ConstraintArgs.setRAngleLoc(RAngleLoc);
1193   ConstraintArgs.setLAngleLoc(LAngleLoc);
1194   Appender(ConstraintArgs);
1195 
1196   // C++2a [temp.param]p4:
1197   //     [...] This constraint-expression E is called the immediately-declared
1198   //     constraint of T. [...]
1199   CXXScopeSpec SS;
1200   SS.Adopt(NS);
1201   ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1202       SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1203       /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
1204   if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1205     return ImmediatelyDeclaredConstraint;
1206 
1207   // C++2a [temp.param]p4:
1208   //     [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1209   //
1210   // We have the following case:
1211   //
1212   // template<typename T> concept C1 = true;
1213   // template<C1... T> struct s1;
1214   //
1215   // The constraint: (C1<T> && ...)
1216   //
1217   // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1218   // any unqualified lookups for 'operator&&' here.
1219   return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1220                             /*LParenLoc=*/SourceLocation(),
1221                             ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1222                             EllipsisLoc, /*RHS=*/nullptr,
1223                             /*RParenLoc=*/SourceLocation(),
1224                             /*NumExpansions=*/std::nullopt);
1225 }
1226 
1227 /// Attach a type-constraint to a template parameter.
1228 /// \returns true if an error occurred. This can happen if the
1229 /// immediately-declared constraint could not be formed (e.g. incorrect number
1230 /// of arguments for the named concept).
AttachTypeConstraint(NestedNameSpecifierLoc NS,DeclarationNameInfo NameInfo,ConceptDecl * NamedConcept,const TemplateArgumentListInfo * TemplateArgs,TemplateTypeParmDecl * ConstrainedParameter,SourceLocation EllipsisLoc)1231 bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1232                                 DeclarationNameInfo NameInfo,
1233                                 ConceptDecl *NamedConcept,
1234                                 const TemplateArgumentListInfo *TemplateArgs,
1235                                 TemplateTypeParmDecl *ConstrainedParameter,
1236                                 SourceLocation EllipsisLoc) {
1237   // C++2a [temp.param]p4:
1238   //     [...] If Q is of the form C<A1, ..., An>, then let E' be
1239   //     C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1240   const ASTTemplateArgumentListInfo *ArgsAsWritten =
1241     TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1242                                                        *TemplateArgs) : nullptr;
1243 
1244   QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1245 
1246   ExprResult ImmediatelyDeclaredConstraint =
1247       formImmediatelyDeclaredConstraint(
1248           *this, NS, NameInfo, NamedConcept,
1249           TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1250           TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1251           ParamAsArgument, ConstrainedParameter->getLocation(),
1252           [&] (TemplateArgumentListInfo &ConstraintArgs) {
1253             if (TemplateArgs)
1254               for (const auto &ArgLoc : TemplateArgs->arguments())
1255                 ConstraintArgs.addArgument(ArgLoc);
1256           }, EllipsisLoc);
1257   if (ImmediatelyDeclaredConstraint.isInvalid())
1258     return true;
1259 
1260   auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1261                                       /*TemplateKWLoc=*/SourceLocation{},
1262                                       /*ConceptNameInfo=*/NameInfo,
1263                                       /*FoundDecl=*/NamedConcept,
1264                                       /*NamedConcept=*/NamedConcept,
1265                                       /*ArgsWritten=*/ArgsAsWritten);
1266   ConstrainedParameter->setTypeConstraint(CL,
1267                                           ImmediatelyDeclaredConstraint.get());
1268   return false;
1269 }
1270 
AttachTypeConstraint(AutoTypeLoc TL,NonTypeTemplateParmDecl * NewConstrainedParm,NonTypeTemplateParmDecl * OrigConstrainedParm,SourceLocation EllipsisLoc)1271 bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1272                                 NonTypeTemplateParmDecl *NewConstrainedParm,
1273                                 NonTypeTemplateParmDecl *OrigConstrainedParm,
1274                                 SourceLocation EllipsisLoc) {
1275   if (NewConstrainedParm->getType() != TL.getType() ||
1276       TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1277     Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1278          diag::err_unsupported_placeholder_constraint)
1279         << NewConstrainedParm->getTypeSourceInfo()
1280                ->getTypeLoc()
1281                .getSourceRange();
1282     return true;
1283   }
1284   // FIXME: Concepts: This should be the type of the placeholder, but this is
1285   // unclear in the wording right now.
1286   DeclRefExpr *Ref =
1287       BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1288                        VK_PRValue, OrigConstrainedParm->getLocation());
1289   if (!Ref)
1290     return true;
1291   ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1292       *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
1293       TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(),
1294       BuildDecltypeType(Ref), OrigConstrainedParm->getLocation(),
1295       [&](TemplateArgumentListInfo &ConstraintArgs) {
1296         for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1297           ConstraintArgs.addArgument(TL.getArgLoc(I));
1298       },
1299       EllipsisLoc);
1300   if (ImmediatelyDeclaredConstraint.isInvalid() ||
1301       !ImmediatelyDeclaredConstraint.isUsable())
1302     return true;
1303 
1304   NewConstrainedParm->setPlaceholderTypeConstraint(
1305       ImmediatelyDeclaredConstraint.get());
1306   return false;
1307 }
1308 
1309 /// Check that the type of a non-type template parameter is
1310 /// well-formed.
1311 ///
1312 /// \returns the (possibly-promoted) parameter type if valid;
1313 /// otherwise, produces a diagnostic and returns a NULL type.
CheckNonTypeTemplateParameterType(TypeSourceInfo * & TSI,SourceLocation Loc)1314 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1315                                                  SourceLocation Loc) {
1316   if (TSI->getType()->isUndeducedType()) {
1317     // C++17 [temp.dep.expr]p3:
1318     //   An id-expression is type-dependent if it contains
1319     //    - an identifier associated by name lookup with a non-type
1320     //      template-parameter declared with a type that contains a
1321     //      placeholder type (7.1.7.4),
1322     TSI = SubstAutoTypeSourceInfoDependent(TSI);
1323   }
1324 
1325   return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1326 }
1327 
1328 /// Require the given type to be a structural type, and diagnose if it is not.
1329 ///
1330 /// \return \c true if an error was produced.
RequireStructuralType(QualType T,SourceLocation Loc)1331 bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1332   if (T->isDependentType())
1333     return false;
1334 
1335   if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1336     return true;
1337 
1338   if (T->isStructuralType())
1339     return false;
1340 
1341   // Structural types are required to be object types or lvalue references.
1342   if (T->isRValueReferenceType()) {
1343     Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1344     return true;
1345   }
1346 
1347   // Don't mention structural types in our diagnostic prior to C++20. Also,
1348   // there's not much more we can say about non-scalar non-class types --
1349   // because we can't see functions or arrays here, those can only be language
1350   // extensions.
1351   if (!getLangOpts().CPlusPlus20 ||
1352       (!T->isScalarType() && !T->isRecordType())) {
1353     Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1354     return true;
1355   }
1356 
1357   // Structural types are required to be literal types.
1358   if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1359     return true;
1360 
1361   Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1362 
1363   // Drill down into the reason why the class is non-structural.
1364   while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1365     // All members are required to be public and non-mutable, and can't be of
1366     // rvalue reference type. Check these conditions first to prefer a "local"
1367     // reason over a more distant one.
1368     for (const FieldDecl *FD : RD->fields()) {
1369       if (FD->getAccess() != AS_public) {
1370         Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1371         return true;
1372       }
1373       if (FD->isMutable()) {
1374         Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1375         return true;
1376       }
1377       if (FD->getType()->isRValueReferenceType()) {
1378         Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1379             << T;
1380         return true;
1381       }
1382     }
1383 
1384     // All bases are required to be public.
1385     for (const auto &BaseSpec : RD->bases()) {
1386       if (BaseSpec.getAccessSpecifier() != AS_public) {
1387         Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1388             << T << 1;
1389         return true;
1390       }
1391     }
1392 
1393     // All subobjects are required to be of structural types.
1394     SourceLocation SubLoc;
1395     QualType SubType;
1396     int Kind = -1;
1397 
1398     for (const FieldDecl *FD : RD->fields()) {
1399       QualType T = Context.getBaseElementType(FD->getType());
1400       if (!T->isStructuralType()) {
1401         SubLoc = FD->getLocation();
1402         SubType = T;
1403         Kind = 0;
1404         break;
1405       }
1406     }
1407 
1408     if (Kind == -1) {
1409       for (const auto &BaseSpec : RD->bases()) {
1410         QualType T = BaseSpec.getType();
1411         if (!T->isStructuralType()) {
1412           SubLoc = BaseSpec.getBaseTypeLoc();
1413           SubType = T;
1414           Kind = 1;
1415           break;
1416         }
1417       }
1418     }
1419 
1420     assert(Kind != -1 && "couldn't find reason why type is not structural");
1421     Diag(SubLoc, diag::note_not_structural_subobject)
1422         << T << Kind << SubType;
1423     T = SubType;
1424     RD = T->getAsCXXRecordDecl();
1425   }
1426 
1427   return true;
1428 }
1429 
CheckNonTypeTemplateParameterType(QualType T,SourceLocation Loc)1430 QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1431                                                  SourceLocation Loc) {
1432   // We don't allow variably-modified types as the type of non-type template
1433   // parameters.
1434   if (T->isVariablyModifiedType()) {
1435     Diag(Loc, diag::err_variably_modified_nontype_template_param)
1436       << T;
1437     return QualType();
1438   }
1439 
1440   // C++ [temp.param]p4:
1441   //
1442   // A non-type template-parameter shall have one of the following
1443   // (optionally cv-qualified) types:
1444   //
1445   //       -- integral or enumeration type,
1446   if (T->isIntegralOrEnumerationType() ||
1447       //   -- pointer to object or pointer to function,
1448       T->isPointerType() ||
1449       //   -- lvalue reference to object or lvalue reference to function,
1450       T->isLValueReferenceType() ||
1451       //   -- pointer to member,
1452       T->isMemberPointerType() ||
1453       //   -- std::nullptr_t, or
1454       T->isNullPtrType() ||
1455       //   -- a type that contains a placeholder type.
1456       T->isUndeducedType()) {
1457     // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1458     // are ignored when determining its type.
1459     return T.getUnqualifiedType();
1460   }
1461 
1462   // C++ [temp.param]p8:
1463   //
1464   //   A non-type template-parameter of type "array of T" or
1465   //   "function returning T" is adjusted to be of type "pointer to
1466   //   T" or "pointer to function returning T", respectively.
1467   if (T->isArrayType() || T->isFunctionType())
1468     return Context.getDecayedType(T);
1469 
1470   // If T is a dependent type, we can't do the check now, so we
1471   // assume that it is well-formed. Note that stripping off the
1472   // qualifiers here is not really correct if T turns out to be
1473   // an array type, but we'll recompute the type everywhere it's
1474   // used during instantiation, so that should be OK. (Using the
1475   // qualified type is equally wrong.)
1476   if (T->isDependentType())
1477     return T.getUnqualifiedType();
1478 
1479   // C++20 [temp.param]p6:
1480   //   -- a structural type
1481   if (RequireStructuralType(T, Loc))
1482     return QualType();
1483 
1484   if (!getLangOpts().CPlusPlus20) {
1485     // FIXME: Consider allowing structural types as an extension in C++17. (In
1486     // earlier language modes, the template argument evaluation rules are too
1487     // inflexible.)
1488     Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1489     return QualType();
1490   }
1491 
1492   Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1493   return T.getUnqualifiedType();
1494 }
1495 
ActOnNonTypeTemplateParameter(Scope * S,Declarator & D,unsigned Depth,unsigned Position,SourceLocation EqualLoc,Expr * Default)1496 NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1497                                           unsigned Depth,
1498                                           unsigned Position,
1499                                           SourceLocation EqualLoc,
1500                                           Expr *Default) {
1501   TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1502 
1503   // Check that we have valid decl-specifiers specified.
1504   auto CheckValidDeclSpecifiers = [this, &D] {
1505     // C++ [temp.param]
1506     // p1
1507     //   template-parameter:
1508     //     ...
1509     //     parameter-declaration
1510     // p2
1511     //   ... A storage class shall not be specified in a template-parameter
1512     //   declaration.
1513     // [dcl.typedef]p1:
1514     //   The typedef specifier [...] shall not be used in the decl-specifier-seq
1515     //   of a parameter-declaration
1516     const DeclSpec &DS = D.getDeclSpec();
1517     auto EmitDiag = [this](SourceLocation Loc) {
1518       Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1519           << FixItHint::CreateRemoval(Loc);
1520     };
1521     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1522       EmitDiag(DS.getStorageClassSpecLoc());
1523 
1524     if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1525       EmitDiag(DS.getThreadStorageClassSpecLoc());
1526 
1527     // [dcl.inline]p1:
1528     //   The inline specifier can be applied only to the declaration or
1529     //   definition of a variable or function.
1530 
1531     if (DS.isInlineSpecified())
1532       EmitDiag(DS.getInlineSpecLoc());
1533 
1534     // [dcl.constexpr]p1:
1535     //   The constexpr specifier shall be applied only to the definition of a
1536     //   variable or variable template or the declaration of a function or
1537     //   function template.
1538 
1539     if (DS.hasConstexprSpecifier())
1540       EmitDiag(DS.getConstexprSpecLoc());
1541 
1542     // [dcl.fct.spec]p1:
1543     //   Function-specifiers can be used only in function declarations.
1544 
1545     if (DS.isVirtualSpecified())
1546       EmitDiag(DS.getVirtualSpecLoc());
1547 
1548     if (DS.hasExplicitSpecifier())
1549       EmitDiag(DS.getExplicitSpecLoc());
1550 
1551     if (DS.isNoreturnSpecified())
1552       EmitDiag(DS.getNoreturnSpecLoc());
1553   };
1554 
1555   CheckValidDeclSpecifiers();
1556 
1557   if (const auto *T = TInfo->getType()->getContainedDeducedType())
1558     if (isa<AutoType>(T))
1559       Diag(D.getIdentifierLoc(),
1560            diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1561           << QualType(TInfo->getType()->getContainedAutoType(), 0);
1562 
1563   assert(S->isTemplateParamScope() &&
1564          "Non-type template parameter not in template parameter scope!");
1565   bool Invalid = false;
1566 
1567   QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1568   if (T.isNull()) {
1569     T = Context.IntTy; // Recover with an 'int' type.
1570     Invalid = true;
1571   }
1572 
1573   CheckFunctionOrTemplateParamDeclarator(S, D);
1574 
1575   IdentifierInfo *ParamName = D.getIdentifier();
1576   bool IsParameterPack = D.hasEllipsis();
1577   NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1578       Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1579       D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1580       TInfo);
1581   Param->setAccess(AS_public);
1582 
1583   if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1584     if (TL.isConstrained())
1585       if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1586         Invalid = true;
1587 
1588   if (Invalid)
1589     Param->setInvalidDecl();
1590 
1591   if (Param->isParameterPack())
1592     if (auto *LSI = getEnclosingLambda())
1593       LSI->LocalPacks.push_back(Param);
1594 
1595   if (ParamName) {
1596     maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1597                                          ParamName);
1598 
1599     // Add the template parameter into the current scope.
1600     S->AddDecl(Param);
1601     IdResolver.AddDecl(Param);
1602   }
1603 
1604   // C++0x [temp.param]p9:
1605   //   A default template-argument may be specified for any kind of
1606   //   template-parameter that is not a template parameter pack.
1607   if (Default && IsParameterPack) {
1608     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1609     Default = nullptr;
1610   }
1611 
1612   // Check the well-formedness of the default template argument, if provided.
1613   if (Default) {
1614     // Check for unexpanded parameter packs.
1615     if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1616       return Param;
1617 
1618     Param->setDefaultArgument(Default);
1619   }
1620 
1621   return Param;
1622 }
1623 
1624 /// ActOnTemplateTemplateParameter - Called when a C++ template template
1625 /// parameter (e.g. T in template <template \<typename> class T> class array)
1626 /// has been parsed. S is the current scope.
ActOnTemplateTemplateParameter(Scope * S,SourceLocation TmpLoc,TemplateParameterList * Params,SourceLocation EllipsisLoc,IdentifierInfo * Name,SourceLocation NameLoc,unsigned Depth,unsigned Position,SourceLocation EqualLoc,ParsedTemplateArgument Default)1627 NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1628                                            SourceLocation TmpLoc,
1629                                            TemplateParameterList *Params,
1630                                            SourceLocation EllipsisLoc,
1631                                            IdentifierInfo *Name,
1632                                            SourceLocation NameLoc,
1633                                            unsigned Depth,
1634                                            unsigned Position,
1635                                            SourceLocation EqualLoc,
1636                                            ParsedTemplateArgument Default) {
1637   assert(S->isTemplateParamScope() &&
1638          "Template template parameter not in template parameter scope!");
1639 
1640   // Construct the parameter object.
1641   bool IsParameterPack = EllipsisLoc.isValid();
1642   TemplateTemplateParmDecl *Param =
1643     TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1644                                      NameLoc.isInvalid()? TmpLoc : NameLoc,
1645                                      Depth, Position, IsParameterPack,
1646                                      Name, Params);
1647   Param->setAccess(AS_public);
1648 
1649   if (Param->isParameterPack())
1650     if (auto *LSI = getEnclosingLambda())
1651       LSI->LocalPacks.push_back(Param);
1652 
1653   // If the template template parameter has a name, then link the identifier
1654   // into the scope and lookup mechanisms.
1655   if (Name) {
1656     maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1657 
1658     S->AddDecl(Param);
1659     IdResolver.AddDecl(Param);
1660   }
1661 
1662   if (Params->size() == 0) {
1663     Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1664     << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1665     Param->setInvalidDecl();
1666   }
1667 
1668   // C++0x [temp.param]p9:
1669   //   A default template-argument may be specified for any kind of
1670   //   template-parameter that is not a template parameter pack.
1671   if (IsParameterPack && !Default.isInvalid()) {
1672     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1673     Default = ParsedTemplateArgument();
1674   }
1675 
1676   if (!Default.isInvalid()) {
1677     // Check only that we have a template template argument. We don't want to
1678     // try to check well-formedness now, because our template template parameter
1679     // might have dependent types in its template parameters, which we wouldn't
1680     // be able to match now.
1681     //
1682     // If none of the template template parameter's template arguments mention
1683     // other template parameters, we could actually perform more checking here.
1684     // However, it isn't worth doing.
1685     TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1686     if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1687       Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1688         << DefaultArg.getSourceRange();
1689       return Param;
1690     }
1691 
1692     // Check for unexpanded parameter packs.
1693     if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1694                                         DefaultArg.getArgument().getAsTemplate(),
1695                                         UPPC_DefaultArgument))
1696       return Param;
1697 
1698     Param->setDefaultArgument(Context, DefaultArg);
1699   }
1700 
1701   return Param;
1702 }
1703 
1704 namespace {
1705 class ConstraintRefersToContainingTemplateChecker
1706     : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1707   bool Result = false;
1708   const FunctionDecl *Friend = nullptr;
1709   unsigned TemplateDepth = 0;
1710 
1711   // Check a record-decl that we've seen to see if it is a lexical parent of the
1712   // Friend, likely because it was referred to without its template arguments.
CheckIfContainingRecord(const CXXRecordDecl * CheckingRD)1713   void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1714     CheckingRD = CheckingRD->getMostRecentDecl();
1715     if (!CheckingRD->isTemplated())
1716       return;
1717 
1718     for (const DeclContext *DC = Friend->getLexicalDeclContext();
1719          DC && !DC->isFileContext(); DC = DC->getParent())
1720       if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1721         if (CheckingRD == RD->getMostRecentDecl())
1722           Result = true;
1723   }
1724 
CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl * D)1725   void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1726     assert(D->getDepth() <= TemplateDepth &&
1727            "Nothing should reference a value below the actual template depth, "
1728            "depth is likely wrong");
1729     if (D->getDepth() != TemplateDepth)
1730       Result = true;
1731 
1732     // Necessary because the type of the NTTP might be what refers to the parent
1733     // constriant.
1734     TransformType(D->getType());
1735   }
1736 
1737 public:
1738   using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>;
1739 
ConstraintRefersToContainingTemplateChecker(Sema & SemaRef,const FunctionDecl * Friend,unsigned TemplateDepth)1740   ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1741                                               const FunctionDecl *Friend,
1742                                               unsigned TemplateDepth)
1743       : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
getResult() const1744   bool getResult() const { return Result; }
1745 
1746   // This should be the only template parm type that we have to deal with.
1747   // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1748   // FunctionParmPackExpr are all partially substituted, which cannot happen
1749   // with concepts at this point in translation.
1750   using inherited::TransformTemplateTypeParmType;
TransformTemplateTypeParmType(TypeLocBuilder & TLB,TemplateTypeParmTypeLoc TL,bool)1751   QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1752                                          TemplateTypeParmTypeLoc TL, bool) {
1753     assert(TL.getDecl()->getDepth() <= TemplateDepth &&
1754            "Nothing should reference a value below the actual template depth, "
1755            "depth is likely wrong");
1756     if (TL.getDecl()->getDepth() != TemplateDepth)
1757       Result = true;
1758     return inherited::TransformTemplateTypeParmType(
1759         TLB, TL,
1760         /*SuppressObjCLifetime=*/false);
1761   }
1762 
TransformDecl(SourceLocation Loc,Decl * D)1763   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1764     if (!D)
1765       return D;
1766     // FIXME : This is possibly an incomplete list, but it is unclear what other
1767     // Decl kinds could be used to refer to the template parameters.  This is a
1768     // best guess so far based on examples currently available, but the
1769     // unreachable should catch future instances/cases.
1770     if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1771       TransformType(TD->getUnderlyingType());
1772     else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1773       CheckNonTypeTemplateParmDecl(NTTPD);
1774     else if (auto *VD = dyn_cast<ValueDecl>(D))
1775       TransformType(VD->getType());
1776     else if (auto *TD = dyn_cast<TemplateDecl>(D))
1777       TransformTemplateParameterList(TD->getTemplateParameters());
1778     else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1779       CheckIfContainingRecord(RD);
1780     else if (isa<NamedDecl>(D)) {
1781       // No direct types to visit here I believe.
1782     } else
1783       llvm_unreachable("Don't know how to handle this declaration type yet");
1784     return D;
1785   }
1786 };
1787 } // namespace
1788 
ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl * Friend,unsigned TemplateDepth,const Expr * Constraint)1789 bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1790     const FunctionDecl *Friend, unsigned TemplateDepth,
1791     const Expr *Constraint) {
1792   assert(Friend->getFriendObjectKind() && "Only works on a friend");
1793   ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1794                                                       TemplateDepth);
1795   Checker.TransformExpr(const_cast<Expr *>(Constraint));
1796   return Checker.getResult();
1797 }
1798 
1799 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1800 /// constrained by RequiresClause, that contains the template parameters in
1801 /// Params.
1802 TemplateParameterList *
ActOnTemplateParameterList(unsigned Depth,SourceLocation ExportLoc,SourceLocation TemplateLoc,SourceLocation LAngleLoc,ArrayRef<NamedDecl * > Params,SourceLocation RAngleLoc,Expr * RequiresClause)1803 Sema::ActOnTemplateParameterList(unsigned Depth,
1804                                  SourceLocation ExportLoc,
1805                                  SourceLocation TemplateLoc,
1806                                  SourceLocation LAngleLoc,
1807                                  ArrayRef<NamedDecl *> Params,
1808                                  SourceLocation RAngleLoc,
1809                                  Expr *RequiresClause) {
1810   if (ExportLoc.isValid())
1811     Diag(ExportLoc, diag::warn_template_export_unsupported);
1812 
1813   for (NamedDecl *P : Params)
1814     warnOnReservedIdentifier(P);
1815 
1816   return TemplateParameterList::Create(
1817       Context, TemplateLoc, LAngleLoc,
1818       llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1819 }
1820 
SetNestedNameSpecifier(Sema & S,TagDecl * T,const CXXScopeSpec & SS)1821 static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1822                                    const CXXScopeSpec &SS) {
1823   if (SS.isSet())
1824     T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1825 }
1826 
1827 // Returns the template parameter list with all default template argument
1828 // information.
GetTemplateParameterList(TemplateDecl * TD)1829 static TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD) {
1830   // Make sure we get the template parameter list from the most
1831   // recent declaration, since that is the only one that is guaranteed to
1832   // have all the default template argument information.
1833   Decl *D = TD->getMostRecentDecl();
1834   // C++11 [temp.param]p12:
1835   // A default template argument shall not be specified in a friend class
1836   // template declaration.
1837   //
1838   // Skip past friend *declarations* because they are not supposed to contain
1839   // default template arguments. Moreover, these declarations may introduce
1840   // template parameters living in different template depths than the
1841   // corresponding template parameters in TD, causing unmatched constraint
1842   // substitution.
1843   //
1844   // FIXME: Diagnose such cases within a class template:
1845   //  template <class T>
1846   //  struct S {
1847   //    template <class = void> friend struct C;
1848   //  };
1849   //  template struct S<int>;
1850   while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1851          D->getPreviousDecl())
1852     D = D->getPreviousDecl();
1853   return cast<TemplateDecl>(D)->getTemplateParameters();
1854 }
1855 
CheckClassTemplate(Scope * S,unsigned TagSpec,TagUseKind TUK,SourceLocation KWLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,const ParsedAttributesView & Attr,TemplateParameterList * TemplateParams,AccessSpecifier AS,SourceLocation ModulePrivateLoc,SourceLocation FriendLoc,unsigned NumOuterTemplateParamLists,TemplateParameterList ** OuterTemplateParamLists,SkipBodyInfo * SkipBody)1856 DeclResult Sema::CheckClassTemplate(
1857     Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1858     CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1859     const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1860     AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1861     SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1862     TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1863   assert(TemplateParams && TemplateParams->size() > 0 &&
1864          "No template parameters");
1865   assert(TUK != TUK_Reference && "Can only declare or define class templates");
1866   bool Invalid = false;
1867 
1868   // Check that we can declare a template here.
1869   if (CheckTemplateDeclScope(S, TemplateParams))
1870     return true;
1871 
1872   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1873   assert(Kind != TagTypeKind::Enum &&
1874          "can't build template of enumerated type");
1875 
1876   // There is no such thing as an unnamed class template.
1877   if (!Name) {
1878     Diag(KWLoc, diag::err_template_unnamed_class);
1879     return true;
1880   }
1881 
1882   // Find any previous declaration with this name. For a friend with no
1883   // scope explicitly specified, we only look for tag declarations (per
1884   // C++11 [basic.lookup.elab]p2).
1885   DeclContext *SemanticContext;
1886   LookupResult Previous(*this, Name, NameLoc,
1887                         (SS.isEmpty() && TUK == TUK_Friend)
1888                           ? LookupTagName : LookupOrdinaryName,
1889                         forRedeclarationInCurContext());
1890   if (SS.isNotEmpty() && !SS.isInvalid()) {
1891     SemanticContext = computeDeclContext(SS, true);
1892     if (!SemanticContext) {
1893       // FIXME: Horrible, horrible hack! We can't currently represent this
1894       // in the AST, and historically we have just ignored such friend
1895       // class templates, so don't complain here.
1896       Diag(NameLoc, TUK == TUK_Friend
1897                         ? diag::warn_template_qualified_friend_ignored
1898                         : diag::err_template_qualified_declarator_no_match)
1899           << SS.getScopeRep() << SS.getRange();
1900       return TUK != TUK_Friend;
1901     }
1902 
1903     if (RequireCompleteDeclContext(SS, SemanticContext))
1904       return true;
1905 
1906     // If we're adding a template to a dependent context, we may need to
1907     // rebuilding some of the types used within the template parameter list,
1908     // now that we know what the current instantiation is.
1909     if (SemanticContext->isDependentContext()) {
1910       ContextRAII SavedContext(*this, SemanticContext);
1911       if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1912         Invalid = true;
1913     } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1914       diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1915 
1916     LookupQualifiedName(Previous, SemanticContext);
1917   } else {
1918     SemanticContext = CurContext;
1919 
1920     // C++14 [class.mem]p14:
1921     //   If T is the name of a class, then each of the following shall have a
1922     //   name different from T:
1923     //    -- every member template of class T
1924     if (TUK != TUK_Friend &&
1925         DiagnoseClassNameShadow(SemanticContext,
1926                                 DeclarationNameInfo(Name, NameLoc)))
1927       return true;
1928 
1929     LookupName(Previous, S);
1930   }
1931 
1932   if (Previous.isAmbiguous())
1933     return true;
1934 
1935   NamedDecl *PrevDecl = nullptr;
1936   if (Previous.begin() != Previous.end())
1937     PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1938 
1939   if (PrevDecl && PrevDecl->isTemplateParameter()) {
1940     // Maybe we will complain about the shadowed template parameter.
1941     DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1942     // Just pretend that we didn't see the previous declaration.
1943     PrevDecl = nullptr;
1944   }
1945 
1946   // If there is a previous declaration with the same name, check
1947   // whether this is a valid redeclaration.
1948   ClassTemplateDecl *PrevClassTemplate =
1949       dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1950 
1951   // We may have found the injected-class-name of a class template,
1952   // class template partial specialization, or class template specialization.
1953   // In these cases, grab the template that is being defined or specialized.
1954   if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1955       cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1956     PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1957     PrevClassTemplate
1958       = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1959     if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1960       PrevClassTemplate
1961         = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1962             ->getSpecializedTemplate();
1963     }
1964   }
1965 
1966   if (TUK == TUK_Friend) {
1967     // C++ [namespace.memdef]p3:
1968     //   [...] When looking for a prior declaration of a class or a function
1969     //   declared as a friend, and when the name of the friend class or
1970     //   function is neither a qualified name nor a template-id, scopes outside
1971     //   the innermost enclosing namespace scope are not considered.
1972     if (!SS.isSet()) {
1973       DeclContext *OutermostContext = CurContext;
1974       while (!OutermostContext->isFileContext())
1975         OutermostContext = OutermostContext->getLookupParent();
1976 
1977       if (PrevDecl &&
1978           (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1979            OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1980         SemanticContext = PrevDecl->getDeclContext();
1981       } else {
1982         // Declarations in outer scopes don't matter. However, the outermost
1983         // context we computed is the semantic context for our new
1984         // declaration.
1985         PrevDecl = PrevClassTemplate = nullptr;
1986         SemanticContext = OutermostContext;
1987 
1988         // Check that the chosen semantic context doesn't already contain a
1989         // declaration of this name as a non-tag type.
1990         Previous.clear(LookupOrdinaryName);
1991         DeclContext *LookupContext = SemanticContext;
1992         while (LookupContext->isTransparentContext())
1993           LookupContext = LookupContext->getLookupParent();
1994         LookupQualifiedName(Previous, LookupContext);
1995 
1996         if (Previous.isAmbiguous())
1997           return true;
1998 
1999         if (Previous.begin() != Previous.end())
2000           PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2001       }
2002     }
2003   } else if (PrevDecl &&
2004              !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
2005                             S, SS.isValid()))
2006     PrevDecl = PrevClassTemplate = nullptr;
2007 
2008   if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2009           PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2010     if (SS.isEmpty() &&
2011         !(PrevClassTemplate &&
2012           PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2013               SemanticContext->getRedeclContext()))) {
2014       Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2015       Diag(Shadow->getTargetDecl()->getLocation(),
2016            diag::note_using_decl_target);
2017       Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2018       // Recover by ignoring the old declaration.
2019       PrevDecl = PrevClassTemplate = nullptr;
2020     }
2021   }
2022 
2023   if (PrevClassTemplate) {
2024     // Ensure that the template parameter lists are compatible. Skip this check
2025     // for a friend in a dependent context: the template parameter list itself
2026     // could be dependent.
2027     if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2028         !TemplateParameterListsAreEqual(
2029             TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2030                                                        : CurContext,
2031                                        CurContext, KWLoc),
2032             TemplateParams, PrevClassTemplate,
2033             PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2034             TPL_TemplateMatch))
2035       return true;
2036 
2037     // C++ [temp.class]p4:
2038     //   In a redeclaration, partial specialization, explicit
2039     //   specialization or explicit instantiation of a class template,
2040     //   the class-key shall agree in kind with the original class
2041     //   template declaration (7.1.5.3).
2042     RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2043     if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
2044                                       TUK == TUK_Definition,  KWLoc, Name)) {
2045       Diag(KWLoc, diag::err_use_with_wrong_tag)
2046         << Name
2047         << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2048       Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2049       Kind = PrevRecordDecl->getTagKind();
2050     }
2051 
2052     // Check for redefinition of this class template.
2053     if (TUK == TUK_Definition) {
2054       if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2055         // If we have a prior definition that is not visible, treat this as
2056         // simply making that previous definition visible.
2057         NamedDecl *Hidden = nullptr;
2058         if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2059           SkipBody->ShouldSkip = true;
2060           SkipBody->Previous = Def;
2061           auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2062           assert(Tmpl && "original definition of a class template is not a "
2063                          "class template?");
2064           makeMergedDefinitionVisible(Hidden);
2065           makeMergedDefinitionVisible(Tmpl);
2066         } else {
2067           Diag(NameLoc, diag::err_redefinition) << Name;
2068           Diag(Def->getLocation(), diag::note_previous_definition);
2069           // FIXME: Would it make sense to try to "forget" the previous
2070           // definition, as part of error recovery?
2071           return true;
2072         }
2073       }
2074     }
2075   } else if (PrevDecl) {
2076     // C++ [temp]p5:
2077     //   A class template shall not have the same name as any other
2078     //   template, class, function, object, enumeration, enumerator,
2079     //   namespace, or type in the same scope (3.3), except as specified
2080     //   in (14.5.4).
2081     Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2082     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2083     return true;
2084   }
2085 
2086   // Check the template parameter list of this declaration, possibly
2087   // merging in the template parameter list from the previous class
2088   // template declaration. Skip this check for a friend in a dependent
2089   // context, because the template parameter list might be dependent.
2090   if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2091       CheckTemplateParameterList(
2092           TemplateParams,
2093           PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2094                             : nullptr,
2095           (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2096            SemanticContext->isDependentContext())
2097               ? TPC_ClassTemplateMember
2098           : TUK == TUK_Friend ? TPC_FriendClassTemplate
2099                               : TPC_ClassTemplate,
2100           SkipBody))
2101     Invalid = true;
2102 
2103   if (SS.isSet()) {
2104     // If the name of the template was qualified, we must be defining the
2105     // template out-of-line.
2106     if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2107       Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
2108                                       : diag::err_member_decl_does_not_match)
2109         << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
2110       Invalid = true;
2111     }
2112   }
2113 
2114   // If this is a templated friend in a dependent context we should not put it
2115   // on the redecl chain. In some cases, the templated friend can be the most
2116   // recent declaration tricking the template instantiator to make substitutions
2117   // there.
2118   // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2119   bool ShouldAddRedecl
2120     = !(TUK == TUK_Friend && CurContext->isDependentContext());
2121 
2122   CXXRecordDecl *NewClass =
2123     CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2124                           PrevClassTemplate && ShouldAddRedecl ?
2125                             PrevClassTemplate->getTemplatedDecl() : nullptr,
2126                           /*DelayTypeCreation=*/true);
2127   SetNestedNameSpecifier(*this, NewClass, SS);
2128   if (NumOuterTemplateParamLists > 0)
2129     NewClass->setTemplateParameterListsInfo(
2130         Context,
2131         llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2132 
2133   // Add alignment attributes if necessary; these attributes are checked when
2134   // the ASTContext lays out the structure.
2135   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2136     AddAlignmentAttributesForRecord(NewClass);
2137     AddMsStructLayoutForRecord(NewClass);
2138   }
2139 
2140   ClassTemplateDecl *NewTemplate
2141     = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2142                                 DeclarationName(Name), TemplateParams,
2143                                 NewClass);
2144 
2145   if (ShouldAddRedecl)
2146     NewTemplate->setPreviousDecl(PrevClassTemplate);
2147 
2148   NewClass->setDescribedClassTemplate(NewTemplate);
2149 
2150   if (ModulePrivateLoc.isValid())
2151     NewTemplate->setModulePrivate();
2152 
2153   // Build the type for the class template declaration now.
2154   QualType T = NewTemplate->getInjectedClassNameSpecialization();
2155   T = Context.getInjectedClassNameType(NewClass, T);
2156   assert(T->isDependentType() && "Class template type is not dependent?");
2157   (void)T;
2158 
2159   // If we are providing an explicit specialization of a member that is a
2160   // class template, make a note of that.
2161   if (PrevClassTemplate &&
2162       PrevClassTemplate->getInstantiatedFromMemberTemplate())
2163     PrevClassTemplate->setMemberSpecialization();
2164 
2165   // Set the access specifier.
2166   if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
2167     SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2168 
2169   // Set the lexical context of these templates
2170   NewClass->setLexicalDeclContext(CurContext);
2171   NewTemplate->setLexicalDeclContext(CurContext);
2172 
2173   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
2174     NewClass->startDefinition();
2175 
2176   ProcessDeclAttributeList(S, NewClass, Attr);
2177 
2178   if (PrevClassTemplate)
2179     mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2180 
2181   AddPushedVisibilityAttribute(NewClass);
2182   inferGslOwnerPointerAttribute(NewClass);
2183 
2184   if (TUK != TUK_Friend) {
2185     // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2186     Scope *Outer = S;
2187     while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2188       Outer = Outer->getParent();
2189     PushOnScopeChains(NewTemplate, Outer);
2190   } else {
2191     if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2192       NewTemplate->setAccess(PrevClassTemplate->getAccess());
2193       NewClass->setAccess(PrevClassTemplate->getAccess());
2194     }
2195 
2196     NewTemplate->setObjectOfFriendDecl();
2197 
2198     // Friend templates are visible in fairly strange ways.
2199     if (!CurContext->isDependentContext()) {
2200       DeclContext *DC = SemanticContext->getRedeclContext();
2201       DC->makeDeclVisibleInContext(NewTemplate);
2202       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2203         PushOnScopeChains(NewTemplate, EnclosingScope,
2204                           /* AddToContext = */ false);
2205     }
2206 
2207     FriendDecl *Friend = FriendDecl::Create(
2208         Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2209     Friend->setAccess(AS_public);
2210     CurContext->addDecl(Friend);
2211   }
2212 
2213   if (PrevClassTemplate)
2214     CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2215 
2216   if (Invalid) {
2217     NewTemplate->setInvalidDecl();
2218     NewClass->setInvalidDecl();
2219   }
2220 
2221   ActOnDocumentableDecl(NewTemplate);
2222 
2223   if (SkipBody && SkipBody->ShouldSkip)
2224     return SkipBody->Previous;
2225 
2226   return NewTemplate;
2227 }
2228 
2229 namespace {
2230 /// Tree transform to "extract" a transformed type from a class template's
2231 /// constructor to a deduction guide.
2232 class ExtractTypeForDeductionGuide
2233   : public TreeTransform<ExtractTypeForDeductionGuide> {
2234   llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
2235 
2236 public:
2237   typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
ExtractTypeForDeductionGuide(Sema & SemaRef,llvm::SmallVectorImpl<TypedefNameDecl * > & MaterializedTypedefs)2238   ExtractTypeForDeductionGuide(
2239       Sema &SemaRef,
2240       llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
2241       : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
2242 
transform(TypeSourceInfo * TSI)2243   TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
2244 
TransformTypedefType(TypeLocBuilder & TLB,TypedefTypeLoc TL)2245   QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
2246     ASTContext &Context = SemaRef.getASTContext();
2247     TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
2248     TypedefNameDecl *Decl = OrigDecl;
2249     // Transform the underlying type of the typedef and clone the Decl only if
2250     // the typedef has a dependent context.
2251     if (OrigDecl->getDeclContext()->isDependentContext()) {
2252       TypeLocBuilder InnerTLB;
2253       QualType Transformed =
2254           TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
2255       TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
2256       if (isa<TypeAliasDecl>(OrigDecl))
2257         Decl = TypeAliasDecl::Create(
2258             Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2259             OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2260       else {
2261         assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
2262         Decl = TypedefDecl::Create(
2263             Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2264             OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2265       }
2266       MaterializedTypedefs.push_back(Decl);
2267     }
2268 
2269     QualType TDTy = Context.getTypedefType(Decl);
2270     TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
2271     TypedefTL.setNameLoc(TL.getNameLoc());
2272 
2273     return TDTy;
2274   }
2275 };
2276 
2277 /// Transform to convert portions of a constructor declaration into the
2278 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
2279 struct ConvertConstructorToDeductionGuideTransform {
ConvertConstructorToDeductionGuideTransform__anonb04a1dd90811::ConvertConstructorToDeductionGuideTransform2280   ConvertConstructorToDeductionGuideTransform(Sema &S,
2281                                               ClassTemplateDecl *Template)
2282       : SemaRef(S), Template(Template) {
2283     // If the template is nested, then we need to use the original
2284     // pattern to iterate over the constructors.
2285     ClassTemplateDecl *Pattern = Template;
2286     while (Pattern->getInstantiatedFromMemberTemplate()) {
2287       if (Pattern->isMemberSpecialization())
2288         break;
2289       Pattern = Pattern->getInstantiatedFromMemberTemplate();
2290       NestedPattern = Pattern;
2291     }
2292 
2293     if (NestedPattern)
2294       OuterInstantiationArgs = SemaRef.getTemplateInstantiationArgs(Template);
2295   }
2296 
2297   Sema &SemaRef;
2298   ClassTemplateDecl *Template;
2299   ClassTemplateDecl *NestedPattern = nullptr;
2300 
2301   DeclContext *DC = Template->getDeclContext();
2302   CXXRecordDecl *Primary = Template->getTemplatedDecl();
2303   DeclarationName DeductionGuideName =
2304       SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
2305 
2306   QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
2307 
2308   // Index adjustment to apply to convert depth-1 template parameters into
2309   // depth-0 template parameters.
2310   unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
2311 
2312   // Instantiation arguments for the outermost depth-1 templates
2313   // when the template is nested
2314   MultiLevelTemplateArgumentList OuterInstantiationArgs;
2315 
2316   /// Transform a constructor declaration into a deduction guide.
transformConstructor__anonb04a1dd90811::ConvertConstructorToDeductionGuideTransform2317   NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
2318                                   CXXConstructorDecl *CD) {
2319     SmallVector<TemplateArgument, 16> SubstArgs;
2320 
2321     LocalInstantiationScope Scope(SemaRef);
2322 
2323     // C++ [over.match.class.deduct]p1:
2324     // -- For each constructor of the class template designated by the
2325     //    template-name, a function template with the following properties:
2326 
2327     //    -- The template parameters are the template parameters of the class
2328     //       template followed by the template parameters (including default
2329     //       template arguments) of the constructor, if any.
2330     TemplateParameterList *TemplateParams = GetTemplateParameterList(Template);
2331     if (FTD) {
2332       TemplateParameterList *InnerParams = FTD->getTemplateParameters();
2333       SmallVector<NamedDecl *, 16> AllParams;
2334       SmallVector<TemplateArgument, 16> Depth1Args;
2335       AllParams.reserve(TemplateParams->size() + InnerParams->size());
2336       AllParams.insert(AllParams.begin(),
2337                        TemplateParams->begin(), TemplateParams->end());
2338       SubstArgs.reserve(InnerParams->size());
2339       Depth1Args.reserve(InnerParams->size());
2340 
2341       // Later template parameters could refer to earlier ones, so build up
2342       // a list of substituted template arguments as we go.
2343       for (NamedDecl *Param : *InnerParams) {
2344         MultiLevelTemplateArgumentList Args;
2345         Args.setKind(TemplateSubstitutionKind::Rewrite);
2346         Args.addOuterTemplateArguments(Depth1Args);
2347         Args.addOuterRetainedLevel();
2348         if (NestedPattern)
2349           Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2350         NamedDecl *NewParam = transformTemplateParameter(Param, Args);
2351         if (!NewParam)
2352           return nullptr;
2353 
2354         // Constraints require that we substitute depth-1 arguments
2355         // to match depths when substituted for evaluation later
2356         Depth1Args.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2357             SemaRef.Context.getInjectedTemplateArg(NewParam)));
2358 
2359         if (NestedPattern) {
2360           TemplateDeclInstantiator Instantiator(SemaRef, DC,
2361                                                 OuterInstantiationArgs);
2362           Instantiator.setEvaluateConstraints(false);
2363           SemaRef.runWithSufficientStackSpace(NewParam->getLocation(), [&] {
2364             NewParam = cast<NamedDecl>(Instantiator.Visit(NewParam));
2365           });
2366         }
2367 
2368         assert(NewParam->getTemplateDepth() == 0 &&
2369                "Unexpected template parameter depth");
2370 
2371         AllParams.push_back(NewParam);
2372         SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2373             SemaRef.Context.getInjectedTemplateArg(NewParam)));
2374       }
2375 
2376       // Substitute new template parameters into requires-clause if present.
2377       Expr *RequiresClause = nullptr;
2378       if (Expr *InnerRC = InnerParams->getRequiresClause()) {
2379         MultiLevelTemplateArgumentList Args;
2380         Args.setKind(TemplateSubstitutionKind::Rewrite);
2381         Args.addOuterTemplateArguments(Depth1Args);
2382         Args.addOuterRetainedLevel();
2383         if (NestedPattern)
2384           Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2385         ExprResult E = SemaRef.SubstExpr(InnerRC, Args);
2386         if (E.isInvalid())
2387           return nullptr;
2388         RequiresClause = E.getAs<Expr>();
2389       }
2390 
2391       TemplateParams = TemplateParameterList::Create(
2392           SemaRef.Context, InnerParams->getTemplateLoc(),
2393           InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
2394           RequiresClause);
2395     }
2396 
2397     // If we built a new template-parameter-list, track that we need to
2398     // substitute references to the old parameters into references to the
2399     // new ones.
2400     MultiLevelTemplateArgumentList Args;
2401     Args.setKind(TemplateSubstitutionKind::Rewrite);
2402     if (FTD) {
2403       Args.addOuterTemplateArguments(SubstArgs);
2404       Args.addOuterRetainedLevel();
2405     }
2406 
2407     FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
2408                                    .getAsAdjusted<FunctionProtoTypeLoc>();
2409     assert(FPTL && "no prototype for constructor declaration");
2410 
2411     // Transform the type of the function, adjusting the return type and
2412     // replacing references to the old parameters with references to the
2413     // new ones.
2414     TypeLocBuilder TLB;
2415     SmallVector<ParmVarDecl*, 8> Params;
2416     SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
2417     QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
2418                                                   MaterializedTypedefs);
2419     if (NewType.isNull())
2420       return nullptr;
2421     TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
2422 
2423     return buildDeductionGuide(TemplateParams, CD, CD->getExplicitSpecifier(),
2424                                NewTInfo, CD->getBeginLoc(), CD->getLocation(),
2425                                CD->getEndLoc(), MaterializedTypedefs);
2426   }
2427 
2428   /// Build a deduction guide with the specified parameter types.
buildSimpleDeductionGuide__anonb04a1dd90811::ConvertConstructorToDeductionGuideTransform2429   NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
2430     SourceLocation Loc = Template->getLocation();
2431 
2432     // Build the requested type.
2433     FunctionProtoType::ExtProtoInfo EPI;
2434     EPI.HasTrailingReturn = true;
2435     QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
2436                                                 DeductionGuideName, EPI);
2437     TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
2438     if (NestedPattern)
2439       TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
2440                               DeductionGuideName);
2441 
2442     FunctionProtoTypeLoc FPTL =
2443         TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
2444 
2445     // Build the parameters, needed during deduction / substitution.
2446     SmallVector<ParmVarDecl*, 4> Params;
2447     for (auto T : ParamTypes) {
2448       auto *TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc);
2449       if (NestedPattern)
2450         TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
2451                                 DeclarationName());
2452       ParmVarDecl *NewParam =
2453           ParmVarDecl::Create(SemaRef.Context, DC, Loc, Loc, nullptr,
2454                               TSI->getType(), TSI, SC_None, nullptr);
2455       NewParam->setScopeInfo(0, Params.size());
2456       FPTL.setParam(Params.size(), NewParam);
2457       Params.push_back(NewParam);
2458     }
2459 
2460     return buildDeductionGuide(GetTemplateParameterList(Template), nullptr,
2461                                ExplicitSpecifier(), TSI, Loc, Loc, Loc);
2462   }
2463 
2464 private:
2465   /// Transform a constructor template parameter into a deduction guide template
2466   /// parameter, rebuilding any internal references to earlier parameters and
2467   /// renumbering as we go.
transformTemplateParameter__anonb04a1dd90811::ConvertConstructorToDeductionGuideTransform2468   NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
2469                                         MultiLevelTemplateArgumentList &Args) {
2470     if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
2471       // TemplateTypeParmDecl's index cannot be changed after creation, so
2472       // substitute it directly.
2473       auto *NewTTP = TemplateTypeParmDecl::Create(
2474           SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
2475           TTP->getDepth() - 1, Depth1IndexAdjustment + TTP->getIndex(),
2476           TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
2477           TTP->isParameterPack(), TTP->hasTypeConstraint(),
2478           TTP->isExpandedParameterPack()
2479               ? std::optional<unsigned>(TTP->getNumExpansionParameters())
2480               : std::nullopt);
2481       if (const auto *TC = TTP->getTypeConstraint())
2482         SemaRef.SubstTypeConstraint(NewTTP, TC, Args,
2483                                     /*EvaluateConstraint*/ true);
2484       if (TTP->hasDefaultArgument()) {
2485         TypeSourceInfo *InstantiatedDefaultArg =
2486             SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2487                               TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2488         if (InstantiatedDefaultArg)
2489           NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2490       }
2491       SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
2492                                                            NewTTP);
2493       return NewTTP;
2494     }
2495 
2496     if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2497       return transformTemplateParameterImpl(TTP, Args);
2498 
2499     return transformTemplateParameterImpl(
2500         cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
2501   }
2502   template<typename TemplateParmDecl>
2503   TemplateParmDecl *
transformTemplateParameterImpl__anonb04a1dd90811::ConvertConstructorToDeductionGuideTransform2504   transformTemplateParameterImpl(TemplateParmDecl *OldParam,
2505                                  MultiLevelTemplateArgumentList &Args) {
2506     // Ask the template instantiator to do the heavy lifting for us, then adjust
2507     // the index of the parameter once it's done.
2508     auto *NewParam =
2509         cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2510     assert(NewParam->getDepth() == OldParam->getDepth() - 1 &&
2511            "unexpected template param depth");
2512     NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2513     return NewParam;
2514   }
2515 
transformFunctionProtoType__anonb04a1dd90811::ConvertConstructorToDeductionGuideTransform2516   QualType transformFunctionProtoType(
2517       TypeLocBuilder &TLB, FunctionProtoTypeLoc TL,
2518       SmallVectorImpl<ParmVarDecl *> &Params,
2519       MultiLevelTemplateArgumentList &Args,
2520       SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2521     SmallVector<QualType, 4> ParamTypes;
2522     const FunctionProtoType *T = TL.getTypePtr();
2523 
2524     //    -- The types of the function parameters are those of the constructor.
2525     for (auto *OldParam : TL.getParams()) {
2526       ParmVarDecl *NewParam = OldParam;
2527       // Given
2528       //   template <class T> struct C {
2529       //     template <class U> struct D {
2530       //       template <class V> D(U, V);
2531       //     };
2532       //   };
2533       // First, transform all the references to template parameters that are
2534       // defined outside of the surrounding class template. That is T in the
2535       // above example.
2536       if (NestedPattern) {
2537         NewParam = transformFunctionTypeParam(NewParam, OuterInstantiationArgs,
2538                                               MaterializedTypedefs);
2539         if (!NewParam)
2540           return QualType();
2541       }
2542       // Then, transform all the references to template parameters that are
2543       // defined at the class template and the constructor. In this example,
2544       // they're U and V, respectively.
2545       NewParam =
2546           transformFunctionTypeParam(NewParam, Args, MaterializedTypedefs);
2547       if (!NewParam)
2548         return QualType();
2549       ParamTypes.push_back(NewParam->getType());
2550       Params.push_back(NewParam);
2551     }
2552 
2553     //    -- The return type is the class template specialization designated by
2554     //       the template-name and template arguments corresponding to the
2555     //       template parameters obtained from the class template.
2556     //
2557     // We use the injected-class-name type of the primary template instead.
2558     // This has the convenient property that it is different from any type that
2559     // the user can write in a deduction-guide (because they cannot enter the
2560     // context of the template), so implicit deduction guides can never collide
2561     // with explicit ones.
2562     QualType ReturnType = DeducedType;
2563     TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2564 
2565     // Resolving a wording defect, we also inherit the variadicness of the
2566     // constructor.
2567     FunctionProtoType::ExtProtoInfo EPI;
2568     EPI.Variadic = T->isVariadic();
2569     EPI.HasTrailingReturn = true;
2570 
2571     QualType Result = SemaRef.BuildFunctionType(
2572         ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2573     if (Result.isNull())
2574       return QualType();
2575 
2576     FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2577     NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
2578     NewTL.setLParenLoc(TL.getLParenLoc());
2579     NewTL.setRParenLoc(TL.getRParenLoc());
2580     NewTL.setExceptionSpecRange(SourceRange());
2581     NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
2582     for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
2583       NewTL.setParam(I, Params[I]);
2584 
2585     return Result;
2586   }
2587 
transformFunctionTypeParam__anonb04a1dd90811::ConvertConstructorToDeductionGuideTransform2588   ParmVarDecl *transformFunctionTypeParam(
2589       ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args,
2590       llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2591     TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2592     TypeSourceInfo *NewDI;
2593     if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2594       // Expand out the one and only element in each inner pack.
2595       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2596       NewDI =
2597           SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2598                             OldParam->getLocation(), OldParam->getDeclName());
2599       if (!NewDI) return nullptr;
2600       NewDI =
2601           SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2602                                      PackTL.getTypePtr()->getNumExpansions());
2603     } else
2604       NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2605                                 OldParam->getDeclName());
2606     if (!NewDI)
2607       return nullptr;
2608 
2609     // Extract the type. This (for instance) replaces references to typedef
2610     // members of the current instantiations with the definitions of those
2611     // typedefs, avoiding triggering instantiation of the deduced type during
2612     // deduction.
2613     NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
2614                 .transform(NewDI);
2615 
2616     // Resolving a wording defect, we also inherit default arguments from the
2617     // constructor.
2618     ExprResult NewDefArg;
2619     if (OldParam->hasDefaultArg()) {
2620       // We don't care what the value is (we won't use it); just create a
2621       // placeholder to indicate there is a default argument.
2622       QualType ParamTy = NewDI->getType();
2623       NewDefArg = new (SemaRef.Context)
2624           OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(),
2625                           ParamTy.getNonLValueExprType(SemaRef.Context),
2626                           ParamTy->isLValueReferenceType()   ? VK_LValue
2627                           : ParamTy->isRValueReferenceType() ? VK_XValue
2628                                                              : VK_PRValue);
2629     }
2630     // Handle arrays and functions decay.
2631     auto NewType = NewDI->getType();
2632     if (NewType->isArrayType() || NewType->isFunctionType())
2633       NewType = SemaRef.Context.getDecayedType(NewType);
2634 
2635     ParmVarDecl *NewParam = ParmVarDecl::Create(
2636         SemaRef.Context, DC, OldParam->getInnerLocStart(),
2637         OldParam->getLocation(), OldParam->getIdentifier(), NewType, NewDI,
2638         OldParam->getStorageClass(), NewDefArg.get());
2639     NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2640                            OldParam->getFunctionScopeIndex());
2641     SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2642     return NewParam;
2643   }
2644 
buildDeductionGuide__anonb04a1dd90811::ConvertConstructorToDeductionGuideTransform2645   FunctionTemplateDecl *buildDeductionGuide(
2646       TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
2647       ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart,
2648       SourceLocation Loc, SourceLocation LocEnd,
2649       llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
2650     DeclarationNameInfo Name(DeductionGuideName, Loc);
2651     ArrayRef<ParmVarDecl *> Params =
2652         TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2653 
2654     // Build the implicit deduction guide template.
2655     auto *Guide =
2656         CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2657                                       TInfo->getType(), TInfo, LocEnd, Ctor);
2658     Guide->setImplicit();
2659     Guide->setParams(Params);
2660 
2661     for (auto *Param : Params)
2662       Param->setDeclContext(Guide);
2663     for (auto *TD : MaterializedTypedefs)
2664       TD->setDeclContext(Guide);
2665 
2666     auto *GuideTemplate = FunctionTemplateDecl::Create(
2667         SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2668     GuideTemplate->setImplicit();
2669     Guide->setDescribedFunctionTemplate(GuideTemplate);
2670 
2671     if (isa<CXXRecordDecl>(DC)) {
2672       Guide->setAccess(AS_public);
2673       GuideTemplate->setAccess(AS_public);
2674     }
2675 
2676     DC->addDecl(GuideTemplate);
2677     return GuideTemplate;
2678   }
2679 };
2680 }
2681 
DeclareImplicitDeductionGuideFromInitList(TemplateDecl * Template,MutableArrayRef<QualType> ParamTypes,SourceLocation Loc)2682 FunctionTemplateDecl *Sema::DeclareImplicitDeductionGuideFromInitList(
2683     TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
2684     SourceLocation Loc) {
2685   if (CXXRecordDecl *DefRecord =
2686           cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2687     if (TemplateDecl *DescribedTemplate =
2688             DefRecord->getDescribedClassTemplate())
2689       Template = DescribedTemplate;
2690   }
2691 
2692   DeclContext *DC = Template->getDeclContext();
2693   if (DC->isDependentContext())
2694     return nullptr;
2695 
2696   ConvertConstructorToDeductionGuideTransform Transform(
2697       *this, cast<ClassTemplateDecl>(Template));
2698   if (!isCompleteType(Loc, Transform.DeducedType))
2699     return nullptr;
2700 
2701   // In case we were expanding a pack when we attempted to declare deduction
2702   // guides, turn off pack expansion for everything we're about to do.
2703   ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
2704                                                /*NewSubstitutionIndex=*/-1);
2705   // Create a template instantiation record to track the "instantiation" of
2706   // constructors into deduction guides.
2707   InstantiatingTemplate BuildingDeductionGuides(
2708       *this, Loc, Template,
2709       Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{});
2710   if (BuildingDeductionGuides.isInvalid())
2711     return nullptr;
2712 
2713   ClassTemplateDecl *Pattern =
2714       Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
2715   ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
2716 
2717   auto *DG = cast<FunctionTemplateDecl>(
2718       Transform.buildSimpleDeductionGuide(ParamTypes));
2719   SavedContext.pop();
2720   return DG;
2721 }
2722 
DeclareImplicitDeductionGuides(TemplateDecl * Template,SourceLocation Loc)2723 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2724                                           SourceLocation Loc) {
2725   if (CXXRecordDecl *DefRecord =
2726           cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2727     if (TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate())
2728       Template = DescribedTemplate;
2729   }
2730 
2731   DeclContext *DC = Template->getDeclContext();
2732   if (DC->isDependentContext())
2733     return;
2734 
2735   ConvertConstructorToDeductionGuideTransform Transform(
2736       *this, cast<ClassTemplateDecl>(Template));
2737   if (!isCompleteType(Loc, Transform.DeducedType))
2738     return;
2739 
2740   // Check whether we've already declared deduction guides for this template.
2741   // FIXME: Consider storing a flag on the template to indicate this.
2742   auto Existing = DC->lookup(Transform.DeductionGuideName);
2743   for (auto *D : Existing)
2744     if (D->isImplicit())
2745       return;
2746 
2747   // In case we were expanding a pack when we attempted to declare deduction
2748   // guides, turn off pack expansion for everything we're about to do.
2749   ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2750   // Create a template instantiation record to track the "instantiation" of
2751   // constructors into deduction guides.
2752   InstantiatingTemplate BuildingDeductionGuides(
2753       *this, Loc, Template,
2754       Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{});
2755   if (BuildingDeductionGuides.isInvalid())
2756     return;
2757 
2758   // Convert declared constructors into deduction guide templates.
2759   // FIXME: Skip constructors for which deduction must necessarily fail (those
2760   // for which some class template parameter without a default argument never
2761   // appears in a deduced context).
2762   ClassTemplateDecl *Pattern =
2763       Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
2764   ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
2765   llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors;
2766   bool AddedAny = false;
2767   for (NamedDecl *D : LookupConstructors(Pattern->getTemplatedDecl())) {
2768     D = D->getUnderlyingDecl();
2769     if (D->isInvalidDecl() || D->isImplicit())
2770       continue;
2771 
2772     D = cast<NamedDecl>(D->getCanonicalDecl());
2773 
2774     // Within C++20 modules, we may have multiple same constructors in
2775     // multiple same RecordDecls. And it doesn't make sense to create
2776     // duplicated deduction guides for the duplicated constructors.
2777     if (ProcessedCtors.count(D))
2778       continue;
2779 
2780     auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2781     auto *CD =
2782         dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
2783     // Class-scope explicit specializations (MS extension) do not result in
2784     // deduction guides.
2785     if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
2786       continue;
2787 
2788     // Cannot make a deduction guide when unparsed arguments are present.
2789     if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) {
2790           return !P || P->hasUnparsedDefaultArg();
2791         }))
2792       continue;
2793 
2794     ProcessedCtors.insert(D);
2795     Transform.transformConstructor(FTD, CD);
2796     AddedAny = true;
2797   }
2798 
2799   // C++17 [over.match.class.deduct]
2800   //    --  If C is not defined or does not declare any constructors, an
2801   //    additional function template derived as above from a hypothetical
2802   //    constructor C().
2803   if (!AddedAny)
2804     Transform.buildSimpleDeductionGuide(std::nullopt);
2805 
2806   //    -- An additional function template derived as above from a hypothetical
2807   //    constructor C(C), called the copy deduction candidate.
2808   cast<CXXDeductionGuideDecl>(
2809       cast<FunctionTemplateDecl>(
2810           Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2811           ->getTemplatedDecl())
2812       ->setDeductionCandidateKind(DeductionCandidate::Copy);
2813 
2814   SavedContext.pop();
2815 }
2816 
2817 /// Diagnose the presence of a default template argument on a
2818 /// template parameter, which is ill-formed in certain contexts.
2819 ///
2820 /// \returns true if the default template argument should be dropped.
DiagnoseDefaultTemplateArgument(Sema & S,Sema::TemplateParamListContext TPC,SourceLocation ParamLoc,SourceRange DefArgRange)2821 static bool DiagnoseDefaultTemplateArgument(Sema &S,
2822                                             Sema::TemplateParamListContext TPC,
2823                                             SourceLocation ParamLoc,
2824                                             SourceRange DefArgRange) {
2825   switch (TPC) {
2826   case Sema::TPC_ClassTemplate:
2827   case Sema::TPC_VarTemplate:
2828   case Sema::TPC_TypeAliasTemplate:
2829     return false;
2830 
2831   case Sema::TPC_FunctionTemplate:
2832   case Sema::TPC_FriendFunctionTemplateDefinition:
2833     // C++ [temp.param]p9:
2834     //   A default template-argument shall not be specified in a
2835     //   function template declaration or a function template
2836     //   definition [...]
2837     //   If a friend function template declaration specifies a default
2838     //   template-argument, that declaration shall be a definition and shall be
2839     //   the only declaration of the function template in the translation unit.
2840     // (C++98/03 doesn't have this wording; see DR226).
2841     S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2842          diag::warn_cxx98_compat_template_parameter_default_in_function_template
2843            : diag::ext_template_parameter_default_in_function_template)
2844       << DefArgRange;
2845     return false;
2846 
2847   case Sema::TPC_ClassTemplateMember:
2848     // C++0x [temp.param]p9:
2849     //   A default template-argument shall not be specified in the
2850     //   template-parameter-lists of the definition of a member of a
2851     //   class template that appears outside of the member's class.
2852     S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2853       << DefArgRange;
2854     return true;
2855 
2856   case Sema::TPC_FriendClassTemplate:
2857   case Sema::TPC_FriendFunctionTemplate:
2858     // C++ [temp.param]p9:
2859     //   A default template-argument shall not be specified in a
2860     //   friend template declaration.
2861     S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2862       << DefArgRange;
2863     return true;
2864 
2865     // FIXME: C++0x [temp.param]p9 allows default template-arguments
2866     // for friend function templates if there is only a single
2867     // declaration (and it is a definition). Strange!
2868   }
2869 
2870   llvm_unreachable("Invalid TemplateParamListContext!");
2871 }
2872 
2873 /// Check for unexpanded parameter packs within the template parameters
2874 /// of a template template parameter, recursively.
DiagnoseUnexpandedParameterPacks(Sema & S,TemplateTemplateParmDecl * TTP)2875 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2876                                              TemplateTemplateParmDecl *TTP) {
2877   // A template template parameter which is a parameter pack is also a pack
2878   // expansion.
2879   if (TTP->isParameterPack())
2880     return false;
2881 
2882   TemplateParameterList *Params = TTP->getTemplateParameters();
2883   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2884     NamedDecl *P = Params->getParam(I);
2885     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2886       if (!TTP->isParameterPack())
2887         if (const TypeConstraint *TC = TTP->getTypeConstraint())
2888           if (TC->hasExplicitTemplateArgs())
2889             for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2890               if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2891                                                     Sema::UPPC_TypeConstraint))
2892                 return true;
2893       continue;
2894     }
2895 
2896     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2897       if (!NTTP->isParameterPack() &&
2898           S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2899                                             NTTP->getTypeSourceInfo(),
2900                                       Sema::UPPC_NonTypeTemplateParameterType))
2901         return true;
2902 
2903       continue;
2904     }
2905 
2906     if (TemplateTemplateParmDecl *InnerTTP
2907                                         = dyn_cast<TemplateTemplateParmDecl>(P))
2908       if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2909         return true;
2910   }
2911 
2912   return false;
2913 }
2914 
2915 /// Checks the validity of a template parameter list, possibly
2916 /// considering the template parameter list from a previous
2917 /// declaration.
2918 ///
2919 /// If an "old" template parameter list is provided, it must be
2920 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
2921 /// template parameter list.
2922 ///
2923 /// \param NewParams Template parameter list for a new template
2924 /// declaration. This template parameter list will be updated with any
2925 /// default arguments that are carried through from the previous
2926 /// template parameter list.
2927 ///
2928 /// \param OldParams If provided, template parameter list from a
2929 /// previous declaration of the same template. Default template
2930 /// arguments will be merged from the old template parameter list to
2931 /// the new template parameter list.
2932 ///
2933 /// \param TPC Describes the context in which we are checking the given
2934 /// template parameter list.
2935 ///
2936 /// \param SkipBody If we might have already made a prior merged definition
2937 /// of this template visible, the corresponding body-skipping information.
2938 /// Default argument redefinition is not an error when skipping such a body,
2939 /// because (under the ODR) we can assume the default arguments are the same
2940 /// as the prior merged definition.
2941 ///
2942 /// \returns true if an error occurred, false otherwise.
CheckTemplateParameterList(TemplateParameterList * NewParams,TemplateParameterList * OldParams,TemplateParamListContext TPC,SkipBodyInfo * SkipBody)2943 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2944                                       TemplateParameterList *OldParams,
2945                                       TemplateParamListContext TPC,
2946                                       SkipBodyInfo *SkipBody) {
2947   bool Invalid = false;
2948 
2949   // C++ [temp.param]p10:
2950   //   The set of default template-arguments available for use with a
2951   //   template declaration or definition is obtained by merging the
2952   //   default arguments from the definition (if in scope) and all
2953   //   declarations in scope in the same way default function
2954   //   arguments are (8.3.6).
2955   bool SawDefaultArgument = false;
2956   SourceLocation PreviousDefaultArgLoc;
2957 
2958   // Dummy initialization to avoid warnings.
2959   TemplateParameterList::iterator OldParam = NewParams->end();
2960   if (OldParams)
2961     OldParam = OldParams->begin();
2962 
2963   bool RemoveDefaultArguments = false;
2964   for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2965                                     NewParamEnd = NewParams->end();
2966        NewParam != NewParamEnd; ++NewParam) {
2967     // Whether we've seen a duplicate default argument in the same translation
2968     // unit.
2969     bool RedundantDefaultArg = false;
2970     // Whether we've found inconsis inconsitent default arguments in different
2971     // translation unit.
2972     bool InconsistentDefaultArg = false;
2973     // The name of the module which contains the inconsistent default argument.
2974     std::string PrevModuleName;
2975 
2976     SourceLocation OldDefaultLoc;
2977     SourceLocation NewDefaultLoc;
2978 
2979     // Variable used to diagnose missing default arguments
2980     bool MissingDefaultArg = false;
2981 
2982     // Variable used to diagnose non-final parameter packs
2983     bool SawParameterPack = false;
2984 
2985     if (TemplateTypeParmDecl *NewTypeParm
2986           = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2987       // Check the presence of a default argument here.
2988       if (NewTypeParm->hasDefaultArgument() &&
2989           DiagnoseDefaultTemplateArgument(*this, TPC,
2990                                           NewTypeParm->getLocation(),
2991                NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2992                                                        .getSourceRange()))
2993         NewTypeParm->removeDefaultArgument();
2994 
2995       // Merge default arguments for template type parameters.
2996       TemplateTypeParmDecl *OldTypeParm
2997           = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2998       if (NewTypeParm->isParameterPack()) {
2999         assert(!NewTypeParm->hasDefaultArgument() &&
3000                "Parameter packs can't have a default argument!");
3001         SawParameterPack = true;
3002       } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
3003                  NewTypeParm->hasDefaultArgument() &&
3004                  (!SkipBody || !SkipBody->ShouldSkip)) {
3005         OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
3006         NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
3007         SawDefaultArgument = true;
3008 
3009         if (!OldTypeParm->getOwningModule())
3010           RedundantDefaultArg = true;
3011         else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
3012                                                                 NewTypeParm)) {
3013           InconsistentDefaultArg = true;
3014           PrevModuleName =
3015               OldTypeParm->getImportedOwningModule()->getFullModuleName();
3016         }
3017         PreviousDefaultArgLoc = NewDefaultLoc;
3018       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
3019         // Merge the default argument from the old declaration to the
3020         // new declaration.
3021         NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
3022         PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
3023       } else if (NewTypeParm->hasDefaultArgument()) {
3024         SawDefaultArgument = true;
3025         PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
3026       } else if (SawDefaultArgument)
3027         MissingDefaultArg = true;
3028     } else if (NonTypeTemplateParmDecl *NewNonTypeParm
3029                = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
3030       // Check for unexpanded parameter packs.
3031       if (!NewNonTypeParm->isParameterPack() &&
3032           DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
3033                                           NewNonTypeParm->getTypeSourceInfo(),
3034                                           UPPC_NonTypeTemplateParameterType)) {
3035         Invalid = true;
3036         continue;
3037       }
3038 
3039       // Check the presence of a default argument here.
3040       if (NewNonTypeParm->hasDefaultArgument() &&
3041           DiagnoseDefaultTemplateArgument(*this, TPC,
3042                                           NewNonTypeParm->getLocation(),
3043                     NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
3044         NewNonTypeParm->removeDefaultArgument();
3045       }
3046 
3047       // Merge default arguments for non-type template parameters
3048       NonTypeTemplateParmDecl *OldNonTypeParm
3049         = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
3050       if (NewNonTypeParm->isParameterPack()) {
3051         assert(!NewNonTypeParm->hasDefaultArgument() &&
3052                "Parameter packs can't have a default argument!");
3053         if (!NewNonTypeParm->isPackExpansion())
3054           SawParameterPack = true;
3055       } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
3056                  NewNonTypeParm->hasDefaultArgument() &&
3057                  (!SkipBody || !SkipBody->ShouldSkip)) {
3058         OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
3059         NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
3060         SawDefaultArgument = true;
3061         if (!OldNonTypeParm->getOwningModule())
3062           RedundantDefaultArg = true;
3063         else if (!getASTContext().isSameDefaultTemplateArgument(
3064                      OldNonTypeParm, NewNonTypeParm)) {
3065           InconsistentDefaultArg = true;
3066           PrevModuleName =
3067               OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
3068         }
3069         PreviousDefaultArgLoc = NewDefaultLoc;
3070       } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
3071         // Merge the default argument from the old declaration to the
3072         // new declaration.
3073         NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
3074         PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
3075       } else if (NewNonTypeParm->hasDefaultArgument()) {
3076         SawDefaultArgument = true;
3077         PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
3078       } else if (SawDefaultArgument)
3079         MissingDefaultArg = true;
3080     } else {
3081       TemplateTemplateParmDecl *NewTemplateParm
3082         = cast<TemplateTemplateParmDecl>(*NewParam);
3083 
3084       // Check for unexpanded parameter packs, recursively.
3085       if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
3086         Invalid = true;
3087         continue;
3088       }
3089 
3090       // Check the presence of a default argument here.
3091       if (NewTemplateParm->hasDefaultArgument() &&
3092           DiagnoseDefaultTemplateArgument(*this, TPC,
3093                                           NewTemplateParm->getLocation(),
3094                      NewTemplateParm->getDefaultArgument().getSourceRange()))
3095         NewTemplateParm->removeDefaultArgument();
3096 
3097       // Merge default arguments for template template parameters
3098       TemplateTemplateParmDecl *OldTemplateParm
3099         = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
3100       if (NewTemplateParm->isParameterPack()) {
3101         assert(!NewTemplateParm->hasDefaultArgument() &&
3102                "Parameter packs can't have a default argument!");
3103         if (!NewTemplateParm->isPackExpansion())
3104           SawParameterPack = true;
3105       } else if (OldTemplateParm &&
3106                  hasVisibleDefaultArgument(OldTemplateParm) &&
3107                  NewTemplateParm->hasDefaultArgument() &&
3108                  (!SkipBody || !SkipBody->ShouldSkip)) {
3109         OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
3110         NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
3111         SawDefaultArgument = true;
3112         if (!OldTemplateParm->getOwningModule())
3113           RedundantDefaultArg = true;
3114         else if (!getASTContext().isSameDefaultTemplateArgument(
3115                      OldTemplateParm, NewTemplateParm)) {
3116           InconsistentDefaultArg = true;
3117           PrevModuleName =
3118               OldTemplateParm->getImportedOwningModule()->getFullModuleName();
3119         }
3120         PreviousDefaultArgLoc = NewDefaultLoc;
3121       } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
3122         // Merge the default argument from the old declaration to the
3123         // new declaration.
3124         NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
3125         PreviousDefaultArgLoc
3126           = OldTemplateParm->getDefaultArgument().getLocation();
3127       } else if (NewTemplateParm->hasDefaultArgument()) {
3128         SawDefaultArgument = true;
3129         PreviousDefaultArgLoc
3130           = NewTemplateParm->getDefaultArgument().getLocation();
3131       } else if (SawDefaultArgument)
3132         MissingDefaultArg = true;
3133     }
3134 
3135     // C++11 [temp.param]p11:
3136     //   If a template parameter of a primary class template or alias template
3137     //   is a template parameter pack, it shall be the last template parameter.
3138     if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
3139         (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
3140          TPC == TPC_TypeAliasTemplate)) {
3141       Diag((*NewParam)->getLocation(),
3142            diag::err_template_param_pack_must_be_last_template_parameter);
3143       Invalid = true;
3144     }
3145 
3146     // [basic.def.odr]/13:
3147     //     There can be more than one definition of a
3148     //     ...
3149     //     default template argument
3150     //     ...
3151     //     in a program provided that each definition appears in a different
3152     //     translation unit and the definitions satisfy the [same-meaning
3153     //     criteria of the ODR].
3154     //
3155     // Simply, the design of modules allows the definition of template default
3156     // argument to be repeated across translation unit. Note that the ODR is
3157     // checked elsewhere. But it is still not allowed to repeat template default
3158     // argument in the same translation unit.
3159     if (RedundantDefaultArg) {
3160       Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
3161       Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
3162       Invalid = true;
3163     } else if (InconsistentDefaultArg) {
3164       // We could only diagnose about the case that the OldParam is imported.
3165       // The case NewParam is imported should be handled in ASTReader.
3166       Diag(NewDefaultLoc,
3167            diag::err_template_param_default_arg_inconsistent_redefinition);
3168       Diag(OldDefaultLoc,
3169            diag::note_template_param_prev_default_arg_in_other_module)
3170           << PrevModuleName;
3171       Invalid = true;
3172     } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
3173       // C++ [temp.param]p11:
3174       //   If a template-parameter of a class template has a default
3175       //   template-argument, each subsequent template-parameter shall either
3176       //   have a default template-argument supplied or be a template parameter
3177       //   pack.
3178       Diag((*NewParam)->getLocation(),
3179            diag::err_template_param_default_arg_missing);
3180       Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
3181       Invalid = true;
3182       RemoveDefaultArguments = true;
3183     }
3184 
3185     // If we have an old template parameter list that we're merging
3186     // in, move on to the next parameter.
3187     if (OldParams)
3188       ++OldParam;
3189   }
3190 
3191   // We were missing some default arguments at the end of the list, so remove
3192   // all of the default arguments.
3193   if (RemoveDefaultArguments) {
3194     for (TemplateParameterList::iterator NewParam = NewParams->begin(),
3195                                       NewParamEnd = NewParams->end();
3196          NewParam != NewParamEnd; ++NewParam) {
3197       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
3198         TTP->removeDefaultArgument();
3199       else if (NonTypeTemplateParmDecl *NTTP
3200                                 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
3201         NTTP->removeDefaultArgument();
3202       else
3203         cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
3204     }
3205   }
3206 
3207   return Invalid;
3208 }
3209 
3210 namespace {
3211 
3212 /// A class which looks for a use of a certain level of template
3213 /// parameter.
3214 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
3215   typedef RecursiveASTVisitor<DependencyChecker> super;
3216 
3217   unsigned Depth;
3218 
3219   // Whether we're looking for a use of a template parameter that makes the
3220   // overall construct type-dependent / a dependent type. This is strictly
3221   // best-effort for now; we may fail to match at all for a dependent type
3222   // in some cases if this is set.
3223   bool IgnoreNonTypeDependent;
3224 
3225   bool Match;
3226   SourceLocation MatchLoc;
3227 
DependencyChecker__anonb04a1dd90b11::DependencyChecker3228   DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
3229       : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
3230         Match(false) {}
3231 
DependencyChecker__anonb04a1dd90b11::DependencyChecker3232   DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
3233       : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
3234     NamedDecl *ND = Params->getParam(0);
3235     if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
3236       Depth = PD->getDepth();
3237     } else if (NonTypeTemplateParmDecl *PD =
3238                  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
3239       Depth = PD->getDepth();
3240     } else {
3241       Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
3242     }
3243   }
3244 
Matches__anonb04a1dd90b11::DependencyChecker3245   bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
3246     if (ParmDepth >= Depth) {
3247       Match = true;
3248       MatchLoc = Loc;
3249       return true;
3250     }
3251     return false;
3252   }
3253 
TraverseStmt__anonb04a1dd90b11::DependencyChecker3254   bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
3255     // Prune out non-type-dependent expressions if requested. This can
3256     // sometimes result in us failing to find a template parameter reference
3257     // (if a value-dependent expression creates a dependent type), but this
3258     // mode is best-effort only.
3259     if (auto *E = dyn_cast_or_null<Expr>(S))
3260       if (IgnoreNonTypeDependent && !E->isTypeDependent())
3261         return true;
3262     return super::TraverseStmt(S, Q);
3263   }
3264 
TraverseTypeLoc__anonb04a1dd90b11::DependencyChecker3265   bool TraverseTypeLoc(TypeLoc TL) {
3266     if (IgnoreNonTypeDependent && !TL.isNull() &&
3267         !TL.getType()->isDependentType())
3268       return true;
3269     return super::TraverseTypeLoc(TL);
3270   }
3271 
VisitTemplateTypeParmTypeLoc__anonb04a1dd90b11::DependencyChecker3272   bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3273     return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
3274   }
3275 
VisitTemplateTypeParmType__anonb04a1dd90b11::DependencyChecker3276   bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
3277     // For a best-effort search, keep looking until we find a location.
3278     return IgnoreNonTypeDependent || !Matches(T->getDepth());
3279   }
3280 
TraverseTemplateName__anonb04a1dd90b11::DependencyChecker3281   bool TraverseTemplateName(TemplateName N) {
3282     if (TemplateTemplateParmDecl *PD =
3283           dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
3284       if (Matches(PD->getDepth()))
3285         return false;
3286     return super::TraverseTemplateName(N);
3287   }
3288 
VisitDeclRefExpr__anonb04a1dd90b11::DependencyChecker3289   bool VisitDeclRefExpr(DeclRefExpr *E) {
3290     if (NonTypeTemplateParmDecl *PD =
3291           dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
3292       if (Matches(PD->getDepth(), E->getExprLoc()))
3293         return false;
3294     return super::VisitDeclRefExpr(E);
3295   }
3296 
VisitSubstTemplateTypeParmType__anonb04a1dd90b11::DependencyChecker3297   bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
3298     return TraverseType(T->getReplacementType());
3299   }
3300 
3301   bool
VisitSubstTemplateTypeParmPackType__anonb04a1dd90b11::DependencyChecker3302   VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
3303     return TraverseTemplateArgument(T->getArgumentPack());
3304   }
3305 
TraverseInjectedClassNameType__anonb04a1dd90b11::DependencyChecker3306   bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
3307     return TraverseType(T->getInjectedSpecializationType());
3308   }
3309 };
3310 } // end anonymous namespace
3311 
3312 /// Determines whether a given type depends on the given parameter
3313 /// list.
3314 static bool
DependsOnTemplateParameters(QualType T,TemplateParameterList * Params)3315 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
3316   if (!Params->size())
3317     return false;
3318 
3319   DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
3320   Checker.TraverseType(T);
3321   return Checker.Match;
3322 }
3323 
3324 // Find the source range corresponding to the named type in the given
3325 // nested-name-specifier, if any.
getRangeOfTypeInNestedNameSpecifier(ASTContext & Context,QualType T,const CXXScopeSpec & SS)3326 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
3327                                                        QualType T,
3328                                                        const CXXScopeSpec &SS) {
3329   NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
3330   while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
3331     if (const Type *CurType = NNS->getAsType()) {
3332       if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
3333         return NNSLoc.getTypeLoc().getSourceRange();
3334     } else
3335       break;
3336 
3337     NNSLoc = NNSLoc.getPrefix();
3338   }
3339 
3340   return SourceRange();
3341 }
3342 
3343 /// Match the given template parameter lists to the given scope
3344 /// specifier, returning the template parameter list that applies to the
3345 /// name.
3346 ///
3347 /// \param DeclStartLoc the start of the declaration that has a scope
3348 /// specifier or a template parameter list.
3349 ///
3350 /// \param DeclLoc The location of the declaration itself.
3351 ///
3352 /// \param SS the scope specifier that will be matched to the given template
3353 /// parameter lists. This scope specifier precedes a qualified name that is
3354 /// being declared.
3355 ///
3356 /// \param TemplateId The template-id following the scope specifier, if there
3357 /// is one. Used to check for a missing 'template<>'.
3358 ///
3359 /// \param ParamLists the template parameter lists, from the outermost to the
3360 /// innermost template parameter lists.
3361 ///
3362 /// \param IsFriend Whether to apply the slightly different rules for
3363 /// matching template parameters to scope specifiers in friend
3364 /// declarations.
3365 ///
3366 /// \param IsMemberSpecialization will be set true if the scope specifier
3367 /// denotes a fully-specialized type, and therefore this is a declaration of
3368 /// a member specialization.
3369 ///
3370 /// \returns the template parameter list, if any, that corresponds to the
3371 /// name that is preceded by the scope specifier @p SS. This template
3372 /// parameter list may have template parameters (if we're declaring a
3373 /// template) or may have no template parameters (if we're declaring a
3374 /// template specialization), or may be NULL (if what we're declaring isn't
3375 /// itself a template).
MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,SourceLocation DeclLoc,const CXXScopeSpec & SS,TemplateIdAnnotation * TemplateId,ArrayRef<TemplateParameterList * > ParamLists,bool IsFriend,bool & IsMemberSpecialization,bool & Invalid,bool SuppressDiagnostic)3376 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
3377     SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
3378     TemplateIdAnnotation *TemplateId,
3379     ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
3380     bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
3381   IsMemberSpecialization = false;
3382   Invalid = false;
3383 
3384   // The sequence of nested types to which we will match up the template
3385   // parameter lists. We first build this list by starting with the type named
3386   // by the nested-name-specifier and walking out until we run out of types.
3387   SmallVector<QualType, 4> NestedTypes;
3388   QualType T;
3389   if (SS.getScopeRep()) {
3390     if (CXXRecordDecl *Record
3391               = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
3392       T = Context.getTypeDeclType(Record);
3393     else
3394       T = QualType(SS.getScopeRep()->getAsType(), 0);
3395   }
3396 
3397   // If we found an explicit specialization that prevents us from needing
3398   // 'template<>' headers, this will be set to the location of that
3399   // explicit specialization.
3400   SourceLocation ExplicitSpecLoc;
3401 
3402   while (!T.isNull()) {
3403     NestedTypes.push_back(T);
3404 
3405     // Retrieve the parent of a record type.
3406     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3407       // If this type is an explicit specialization, we're done.
3408       if (ClassTemplateSpecializationDecl *Spec
3409           = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3410         if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
3411             Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
3412           ExplicitSpecLoc = Spec->getLocation();
3413           break;
3414         }
3415       } else if (Record->getTemplateSpecializationKind()
3416                                                 == TSK_ExplicitSpecialization) {
3417         ExplicitSpecLoc = Record->getLocation();
3418         break;
3419       }
3420 
3421       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
3422         T = Context.getTypeDeclType(Parent);
3423       else
3424         T = QualType();
3425       continue;
3426     }
3427 
3428     if (const TemplateSpecializationType *TST
3429                                      = T->getAs<TemplateSpecializationType>()) {
3430       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3431         if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
3432           T = Context.getTypeDeclType(Parent);
3433         else
3434           T = QualType();
3435         continue;
3436       }
3437     }
3438 
3439     // Look one step prior in a dependent template specialization type.
3440     if (const DependentTemplateSpecializationType *DependentTST
3441                           = T->getAs<DependentTemplateSpecializationType>()) {
3442       if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
3443         T = QualType(NNS->getAsType(), 0);
3444       else
3445         T = QualType();
3446       continue;
3447     }
3448 
3449     // Look one step prior in a dependent name type.
3450     if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
3451       if (NestedNameSpecifier *NNS = DependentName->getQualifier())
3452         T = QualType(NNS->getAsType(), 0);
3453       else
3454         T = QualType();
3455       continue;
3456     }
3457 
3458     // Retrieve the parent of an enumeration type.
3459     if (const EnumType *EnumT = T->getAs<EnumType>()) {
3460       // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
3461       // check here.
3462       EnumDecl *Enum = EnumT->getDecl();
3463 
3464       // Get to the parent type.
3465       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
3466         T = Context.getTypeDeclType(Parent);
3467       else
3468         T = QualType();
3469       continue;
3470     }
3471 
3472     T = QualType();
3473   }
3474   // Reverse the nested types list, since we want to traverse from the outermost
3475   // to the innermost while checking template-parameter-lists.
3476   std::reverse(NestedTypes.begin(), NestedTypes.end());
3477 
3478   // C++0x [temp.expl.spec]p17:
3479   //   A member or a member template may be nested within many
3480   //   enclosing class templates. In an explicit specialization for
3481   //   such a member, the member declaration shall be preceded by a
3482   //   template<> for each enclosing class template that is
3483   //   explicitly specialized.
3484   bool SawNonEmptyTemplateParameterList = false;
3485 
3486   auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
3487     if (SawNonEmptyTemplateParameterList) {
3488       if (!SuppressDiagnostic)
3489         Diag(DeclLoc, diag::err_specialize_member_of_template)
3490           << !Recovery << Range;
3491       Invalid = true;
3492       IsMemberSpecialization = false;
3493       return true;
3494     }
3495 
3496     return false;
3497   };
3498 
3499   auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
3500     // Check that we can have an explicit specialization here.
3501     if (CheckExplicitSpecialization(Range, true))
3502       return true;
3503 
3504     // We don't have a template header, but we should.
3505     SourceLocation ExpectedTemplateLoc;
3506     if (!ParamLists.empty())
3507       ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
3508     else
3509       ExpectedTemplateLoc = DeclStartLoc;
3510 
3511     if (!SuppressDiagnostic)
3512       Diag(DeclLoc, diag::err_template_spec_needs_header)
3513         << Range
3514         << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
3515     return false;
3516   };
3517 
3518   unsigned ParamIdx = 0;
3519   for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3520        ++TypeIdx) {
3521     T = NestedTypes[TypeIdx];
3522 
3523     // Whether we expect a 'template<>' header.
3524     bool NeedEmptyTemplateHeader = false;
3525 
3526     // Whether we expect a template header with parameters.
3527     bool NeedNonemptyTemplateHeader = false;
3528 
3529     // For a dependent type, the set of template parameters that we
3530     // expect to see.
3531     TemplateParameterList *ExpectedTemplateParams = nullptr;
3532 
3533     // C++0x [temp.expl.spec]p15:
3534     //   A member or a member template may be nested within many enclosing
3535     //   class templates. In an explicit specialization for such a member, the
3536     //   member declaration shall be preceded by a template<> for each
3537     //   enclosing class template that is explicitly specialized.
3538     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3539       if (ClassTemplatePartialSpecializationDecl *Partial
3540             = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3541         ExpectedTemplateParams = Partial->getTemplateParameters();
3542         NeedNonemptyTemplateHeader = true;
3543       } else if (Record->isDependentType()) {
3544         if (Record->getDescribedClassTemplate()) {
3545           ExpectedTemplateParams = Record->getDescribedClassTemplate()
3546                                                       ->getTemplateParameters();
3547           NeedNonemptyTemplateHeader = true;
3548         }
3549       } else if (ClassTemplateSpecializationDecl *Spec
3550                      = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3551         // C++0x [temp.expl.spec]p4:
3552         //   Members of an explicitly specialized class template are defined
3553         //   in the same manner as members of normal classes, and not using
3554         //   the template<> syntax.
3555         if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3556           NeedEmptyTemplateHeader = true;
3557         else
3558           continue;
3559       } else if (Record->getTemplateSpecializationKind()) {
3560         if (Record->getTemplateSpecializationKind()
3561                                                 != TSK_ExplicitSpecialization &&
3562             TypeIdx == NumTypes - 1)
3563           IsMemberSpecialization = true;
3564 
3565         continue;
3566       }
3567     } else if (const TemplateSpecializationType *TST
3568                                      = T->getAs<TemplateSpecializationType>()) {
3569       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3570         ExpectedTemplateParams = Template->getTemplateParameters();
3571         NeedNonemptyTemplateHeader = true;
3572       }
3573     } else if (T->getAs<DependentTemplateSpecializationType>()) {
3574       // FIXME:  We actually could/should check the template arguments here
3575       // against the corresponding template parameter list.
3576       NeedNonemptyTemplateHeader = false;
3577     }
3578 
3579     // C++ [temp.expl.spec]p16:
3580     //   In an explicit specialization declaration for a member of a class
3581     //   template or a member template that ap- pears in namespace scope, the
3582     //   member template and some of its enclosing class templates may remain
3583     //   unspecialized, except that the declaration shall not explicitly
3584     //   specialize a class member template if its en- closing class templates
3585     //   are not explicitly specialized as well.
3586     if (ParamIdx < ParamLists.size()) {
3587       if (ParamLists[ParamIdx]->size() == 0) {
3588         if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3589                                         false))
3590           return nullptr;
3591       } else
3592         SawNonEmptyTemplateParameterList = true;
3593     }
3594 
3595     if (NeedEmptyTemplateHeader) {
3596       // If we're on the last of the types, and we need a 'template<>' header
3597       // here, then it's a member specialization.
3598       if (TypeIdx == NumTypes - 1)
3599         IsMemberSpecialization = true;
3600 
3601       if (ParamIdx < ParamLists.size()) {
3602         if (ParamLists[ParamIdx]->size() > 0) {
3603           // The header has template parameters when it shouldn't. Complain.
3604           if (!SuppressDiagnostic)
3605             Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3606                  diag::err_template_param_list_matches_nontemplate)
3607               << T
3608               << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3609                              ParamLists[ParamIdx]->getRAngleLoc())
3610               << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3611           Invalid = true;
3612           return nullptr;
3613         }
3614 
3615         // Consume this template header.
3616         ++ParamIdx;
3617         continue;
3618       }
3619 
3620       if (!IsFriend)
3621         if (DiagnoseMissingExplicitSpecialization(
3622                 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3623           return nullptr;
3624 
3625       continue;
3626     }
3627 
3628     if (NeedNonemptyTemplateHeader) {
3629       // In friend declarations we can have template-ids which don't
3630       // depend on the corresponding template parameter lists.  But
3631       // assume that empty parameter lists are supposed to match this
3632       // template-id.
3633       if (IsFriend && T->isDependentType()) {
3634         if (ParamIdx < ParamLists.size() &&
3635             DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3636           ExpectedTemplateParams = nullptr;
3637         else
3638           continue;
3639       }
3640 
3641       if (ParamIdx < ParamLists.size()) {
3642         // Check the template parameter list, if we can.
3643         if (ExpectedTemplateParams &&
3644             !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
3645                                             ExpectedTemplateParams,
3646                                             !SuppressDiagnostic, TPL_TemplateMatch))
3647           Invalid = true;
3648 
3649         if (!Invalid &&
3650             CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3651                                        TPC_ClassTemplateMember))
3652           Invalid = true;
3653 
3654         ++ParamIdx;
3655         continue;
3656       }
3657 
3658       if (!SuppressDiagnostic)
3659         Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3660           << T
3661           << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3662       Invalid = true;
3663       continue;
3664     }
3665   }
3666 
3667   // If there were at least as many template-ids as there were template
3668   // parameter lists, then there are no template parameter lists remaining for
3669   // the declaration itself.
3670   if (ParamIdx >= ParamLists.size()) {
3671     if (TemplateId && !IsFriend) {
3672       // We don't have a template header for the declaration itself, but we
3673       // should.
3674       DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3675                                                         TemplateId->RAngleLoc));
3676 
3677       // Fabricate an empty template parameter list for the invented header.
3678       return TemplateParameterList::Create(Context, SourceLocation(),
3679                                            SourceLocation(), std::nullopt,
3680                                            SourceLocation(), nullptr);
3681     }
3682 
3683     return nullptr;
3684   }
3685 
3686   // If there were too many template parameter lists, complain about that now.
3687   if (ParamIdx < ParamLists.size() - 1) {
3688     bool HasAnyExplicitSpecHeader = false;
3689     bool AllExplicitSpecHeaders = true;
3690     for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3691       if (ParamLists[I]->size() == 0)
3692         HasAnyExplicitSpecHeader = true;
3693       else
3694         AllExplicitSpecHeaders = false;
3695     }
3696 
3697     if (!SuppressDiagnostic)
3698       Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3699            AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
3700                                   : diag::err_template_spec_extra_headers)
3701           << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3702                          ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3703 
3704     // If there was a specialization somewhere, such that 'template<>' is
3705     // not required, and there were any 'template<>' headers, note where the
3706     // specialization occurred.
3707     if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3708         !SuppressDiagnostic)
3709       Diag(ExplicitSpecLoc,
3710            diag::note_explicit_template_spec_does_not_need_header)
3711         << NestedTypes.back();
3712 
3713     // We have a template parameter list with no corresponding scope, which
3714     // means that the resulting template declaration can't be instantiated
3715     // properly (we'll end up with dependent nodes when we shouldn't).
3716     if (!AllExplicitSpecHeaders)
3717       Invalid = true;
3718   }
3719 
3720   // C++ [temp.expl.spec]p16:
3721   //   In an explicit specialization declaration for a member of a class
3722   //   template or a member template that ap- pears in namespace scope, the
3723   //   member template and some of its enclosing class templates may remain
3724   //   unspecialized, except that the declaration shall not explicitly
3725   //   specialize a class member template if its en- closing class templates
3726   //   are not explicitly specialized as well.
3727   if (ParamLists.back()->size() == 0 &&
3728       CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3729                                   false))
3730     return nullptr;
3731 
3732   // Return the last template parameter list, which corresponds to the
3733   // entity being declared.
3734   return ParamLists.back();
3735 }
3736 
NoteAllFoundTemplates(TemplateName Name)3737 void Sema::NoteAllFoundTemplates(TemplateName Name) {
3738   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3739     Diag(Template->getLocation(), diag::note_template_declared_here)
3740         << (isa<FunctionTemplateDecl>(Template)
3741                 ? 0
3742                 : isa<ClassTemplateDecl>(Template)
3743                       ? 1
3744                       : isa<VarTemplateDecl>(Template)
3745                             ? 2
3746                             : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3747         << Template->getDeclName();
3748     return;
3749   }
3750 
3751   if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3752     for (OverloadedTemplateStorage::iterator I = OST->begin(),
3753                                           IEnd = OST->end();
3754          I != IEnd; ++I)
3755       Diag((*I)->getLocation(), diag::note_template_declared_here)
3756         << 0 << (*I)->getDeclName();
3757 
3758     return;
3759   }
3760 }
3761 
3762 static QualType
checkBuiltinTemplateIdType(Sema & SemaRef,BuiltinTemplateDecl * BTD,ArrayRef<TemplateArgument> Converted,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs)3763 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3764                            ArrayRef<TemplateArgument> Converted,
3765                            SourceLocation TemplateLoc,
3766                            TemplateArgumentListInfo &TemplateArgs) {
3767   ASTContext &Context = SemaRef.getASTContext();
3768 
3769   switch (BTD->getBuiltinTemplateKind()) {
3770   case BTK__make_integer_seq: {
3771     // Specializations of __make_integer_seq<S, T, N> are treated like
3772     // S<T, 0, ..., N-1>.
3773 
3774     QualType OrigType = Converted[1].getAsType();
3775     // C++14 [inteseq.intseq]p1:
3776     //   T shall be an integer type.
3777     if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3778       SemaRef.Diag(TemplateArgs[1].getLocation(),
3779                    diag::err_integer_sequence_integral_element_type);
3780       return QualType();
3781     }
3782 
3783     TemplateArgument NumArgsArg = Converted[2];
3784     if (NumArgsArg.isDependent())
3785       return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3786                                                             Converted);
3787 
3788     TemplateArgumentListInfo SyntheticTemplateArgs;
3789     // The type argument, wrapped in substitution sugar, gets reused as the
3790     // first template argument in the synthetic template argument list.
3791     SyntheticTemplateArgs.addArgument(
3792         TemplateArgumentLoc(TemplateArgument(OrigType),
3793                             SemaRef.Context.getTrivialTypeSourceInfo(
3794                                 OrigType, TemplateArgs[1].getLocation())));
3795 
3796     if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3797       // Expand N into 0 ... N-1.
3798       for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3799            I < NumArgs; ++I) {
3800         TemplateArgument TA(Context, I, OrigType);
3801         SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3802             TA, OrigType, TemplateArgs[2].getLocation()));
3803       }
3804     } else {
3805       // C++14 [inteseq.make]p1:
3806       //   If N is negative the program is ill-formed.
3807       SemaRef.Diag(TemplateArgs[2].getLocation(),
3808                    diag::err_integer_sequence_negative_length);
3809       return QualType();
3810     }
3811 
3812     // The first template argument will be reused as the template decl that
3813     // our synthetic template arguments will be applied to.
3814     return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3815                                        TemplateLoc, SyntheticTemplateArgs);
3816   }
3817 
3818   case BTK__type_pack_element:
3819     // Specializations of
3820     //    __type_pack_element<Index, T_1, ..., T_N>
3821     // are treated like T_Index.
3822     assert(Converted.size() == 2 &&
3823       "__type_pack_element should be given an index and a parameter pack");
3824 
3825     TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3826     if (IndexArg.isDependent() || Ts.isDependent())
3827       return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3828                                                             Converted);
3829 
3830     llvm::APSInt Index = IndexArg.getAsIntegral();
3831     assert(Index >= 0 && "the index used with __type_pack_element should be of "
3832                          "type std::size_t, and hence be non-negative");
3833     // If the Index is out of bounds, the program is ill-formed.
3834     if (Index >= Ts.pack_size()) {
3835       SemaRef.Diag(TemplateArgs[0].getLocation(),
3836                    diag::err_type_pack_element_out_of_bounds);
3837       return QualType();
3838     }
3839 
3840     // We simply return the type at index `Index`.
3841     int64_t N = Index.getExtValue();
3842     return Ts.getPackAsArray()[N].getAsType();
3843   }
3844   llvm_unreachable("unexpected BuiltinTemplateDecl!");
3845 }
3846 
3847 /// Determine whether this alias template is "enable_if_t".
3848 /// libc++ >=14 uses "__enable_if_t" in C++11 mode.
isEnableIfAliasTemplate(TypeAliasTemplateDecl * AliasTemplate)3849 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3850   return AliasTemplate->getName().equals("enable_if_t") ||
3851          AliasTemplate->getName().equals("__enable_if_t");
3852 }
3853 
3854 /// Collect all of the separable terms in the given condition, which
3855 /// might be a conjunction.
3856 ///
3857 /// FIXME: The right answer is to convert the logical expression into
3858 /// disjunctive normal form, so we can find the first failed term
3859 /// within each possible clause.
collectConjunctionTerms(Expr * Clause,SmallVectorImpl<Expr * > & Terms)3860 static void collectConjunctionTerms(Expr *Clause,
3861                                     SmallVectorImpl<Expr *> &Terms) {
3862   if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3863     if (BinOp->getOpcode() == BO_LAnd) {
3864       collectConjunctionTerms(BinOp->getLHS(), Terms);
3865       collectConjunctionTerms(BinOp->getRHS(), Terms);
3866       return;
3867     }
3868   }
3869 
3870   Terms.push_back(Clause);
3871 }
3872 
3873 // The ranges-v3 library uses an odd pattern of a top-level "||" with
3874 // a left-hand side that is value-dependent but never true. Identify
3875 // the idiom and ignore that term.
lookThroughRangesV3Condition(Preprocessor & PP,Expr * Cond)3876 static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3877   // Top-level '||'.
3878   auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3879   if (!BinOp) return Cond;
3880 
3881   if (BinOp->getOpcode() != BO_LOr) return Cond;
3882 
3883   // With an inner '==' that has a literal on the right-hand side.
3884   Expr *LHS = BinOp->getLHS();
3885   auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3886   if (!InnerBinOp) return Cond;
3887 
3888   if (InnerBinOp->getOpcode() != BO_EQ ||
3889       !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3890     return Cond;
3891 
3892   // If the inner binary operation came from a macro expansion named
3893   // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3894   // of the '||', which is the real, user-provided condition.
3895   SourceLocation Loc = InnerBinOp->getExprLoc();
3896   if (!Loc.isMacroID()) return Cond;
3897 
3898   StringRef MacroName = PP.getImmediateMacroName(Loc);
3899   if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3900     return BinOp->getRHS();
3901 
3902   return Cond;
3903 }
3904 
3905 namespace {
3906 
3907 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3908 // within failing boolean expression, such as substituting template parameters
3909 // for actual types.
3910 class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3911 public:
FailedBooleanConditionPrinterHelper(const PrintingPolicy & P)3912   explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3913       : Policy(P) {}
3914 
handledStmt(Stmt * E,raw_ostream & OS)3915   bool handledStmt(Stmt *E, raw_ostream &OS) override {
3916     const auto *DR = dyn_cast<DeclRefExpr>(E);
3917     if (DR && DR->getQualifier()) {
3918       // If this is a qualified name, expand the template arguments in nested
3919       // qualifiers.
3920       DR->getQualifier()->print(OS, Policy, true);
3921       // Then print the decl itself.
3922       const ValueDecl *VD = DR->getDecl();
3923       OS << VD->getName();
3924       if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3925         // This is a template variable, print the expanded template arguments.
3926         printTemplateArgumentList(
3927             OS, IV->getTemplateArgs().asArray(), Policy,
3928             IV->getSpecializedTemplate()->getTemplateParameters());
3929       }
3930       return true;
3931     }
3932     return false;
3933   }
3934 
3935 private:
3936   const PrintingPolicy Policy;
3937 };
3938 
3939 } // end anonymous namespace
3940 
3941 std::pair<Expr *, std::string>
findFailedBooleanCondition(Expr * Cond)3942 Sema::findFailedBooleanCondition(Expr *Cond) {
3943   Cond = lookThroughRangesV3Condition(PP, Cond);
3944 
3945   // Separate out all of the terms in a conjunction.
3946   SmallVector<Expr *, 4> Terms;
3947   collectConjunctionTerms(Cond, Terms);
3948 
3949   // Determine which term failed.
3950   Expr *FailedCond = nullptr;
3951   for (Expr *Term : Terms) {
3952     Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3953 
3954     // Literals are uninteresting.
3955     if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3956         isa<IntegerLiteral>(TermAsWritten))
3957       continue;
3958 
3959     // The initialization of the parameter from the argument is
3960     // a constant-evaluated context.
3961     EnterExpressionEvaluationContext ConstantEvaluated(
3962       *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3963 
3964     bool Succeeded;
3965     if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3966         !Succeeded) {
3967       FailedCond = TermAsWritten;
3968       break;
3969     }
3970   }
3971   if (!FailedCond)
3972     FailedCond = Cond->IgnoreParenImpCasts();
3973 
3974   std::string Description;
3975   {
3976     llvm::raw_string_ostream Out(Description);
3977     PrintingPolicy Policy = getPrintingPolicy();
3978     Policy.PrintCanonicalTypes = true;
3979     FailedBooleanConditionPrinterHelper Helper(Policy);
3980     FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3981   }
3982   return { FailedCond, Description };
3983 }
3984 
CheckTemplateIdType(TemplateName Name,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs)3985 QualType Sema::CheckTemplateIdType(TemplateName Name,
3986                                    SourceLocation TemplateLoc,
3987                                    TemplateArgumentListInfo &TemplateArgs) {
3988   DependentTemplateName *DTN
3989     = Name.getUnderlying().getAsDependentTemplateName();
3990   if (DTN && DTN->isIdentifier())
3991     // When building a template-id where the template-name is dependent,
3992     // assume the template is a type template. Either our assumption is
3993     // correct, or the code is ill-formed and will be diagnosed when the
3994     // dependent name is substituted.
3995     return Context.getDependentTemplateSpecializationType(
3996         ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3997         TemplateArgs.arguments());
3998 
3999   if (Name.getAsAssumedTemplateName() &&
4000       resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
4001     return QualType();
4002 
4003   TemplateDecl *Template = Name.getAsTemplateDecl();
4004   if (!Template || isa<FunctionTemplateDecl>(Template) ||
4005       isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
4006     // We might have a substituted template template parameter pack. If so,
4007     // build a template specialization type for it.
4008     if (Name.getAsSubstTemplateTemplateParmPack())
4009       return Context.getTemplateSpecializationType(Name,
4010                                                    TemplateArgs.arguments());
4011 
4012     Diag(TemplateLoc, diag::err_template_id_not_a_type)
4013       << Name;
4014     NoteAllFoundTemplates(Name);
4015     return QualType();
4016   }
4017 
4018   // Check that the template argument list is well-formed for this
4019   // template.
4020   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4021   if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false,
4022                                 SugaredConverted, CanonicalConverted,
4023                                 /*UpdateArgsWithConversions=*/true))
4024     return QualType();
4025 
4026   QualType CanonType;
4027 
4028   if (TypeAliasTemplateDecl *AliasTemplate =
4029           dyn_cast<TypeAliasTemplateDecl>(Template)) {
4030 
4031     // Find the canonical type for this type alias template specialization.
4032     TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
4033     if (Pattern->isInvalidDecl())
4034       return QualType();
4035 
4036     // Only substitute for the innermost template argument list.
4037     MultiLevelTemplateArgumentList TemplateArgLists;
4038     TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted,
4039                                                /*Final=*/false);
4040     TemplateArgLists.addOuterRetainedLevels(
4041         AliasTemplate->getTemplateParameters()->getDepth());
4042 
4043     LocalInstantiationScope Scope(*this);
4044     InstantiatingTemplate Inst(*this, TemplateLoc, Template);
4045     if (Inst.isInvalid())
4046       return QualType();
4047 
4048     CanonType = SubstType(Pattern->getUnderlyingType(),
4049                           TemplateArgLists, AliasTemplate->getLocation(),
4050                           AliasTemplate->getDeclName());
4051     if (CanonType.isNull()) {
4052       // If this was enable_if and we failed to find the nested type
4053       // within enable_if in a SFINAE context, dig out the specific
4054       // enable_if condition that failed and present that instead.
4055       if (isEnableIfAliasTemplate(AliasTemplate)) {
4056         if (auto DeductionInfo = isSFINAEContext()) {
4057           if (*DeductionInfo &&
4058               (*DeductionInfo)->hasSFINAEDiagnostic() &&
4059               (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
4060                 diag::err_typename_nested_not_found_enable_if &&
4061               TemplateArgs[0].getArgument().getKind()
4062                 == TemplateArgument::Expression) {
4063             Expr *FailedCond;
4064             std::string FailedDescription;
4065             std::tie(FailedCond, FailedDescription) =
4066               findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
4067 
4068             // Remove the old SFINAE diagnostic.
4069             PartialDiagnosticAt OldDiag =
4070               {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
4071             (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
4072 
4073             // Add a new SFINAE diagnostic specifying which condition
4074             // failed.
4075             (*DeductionInfo)->addSFINAEDiagnostic(
4076               OldDiag.first,
4077               PDiag(diag::err_typename_nested_not_found_requirement)
4078                 << FailedDescription
4079                 << FailedCond->getSourceRange());
4080           }
4081         }
4082       }
4083 
4084       return QualType();
4085     }
4086   } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
4087     CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
4088                                            TemplateLoc, TemplateArgs);
4089   } else if (Name.isDependent() ||
4090              TemplateSpecializationType::anyDependentTemplateArguments(
4091                  TemplateArgs, CanonicalConverted)) {
4092     // This class template specialization is a dependent
4093     // type. Therefore, its canonical type is another class template
4094     // specialization type that contains all of the converted
4095     // arguments in canonical form. This ensures that, e.g., A<T> and
4096     // A<T, T> have identical types when A is declared as:
4097     //
4098     //   template<typename T, typename U = T> struct A;
4099     CanonType = Context.getCanonicalTemplateSpecializationType(
4100         Name, CanonicalConverted);
4101 
4102     // This might work out to be a current instantiation, in which
4103     // case the canonical type needs to be the InjectedClassNameType.
4104     //
4105     // TODO: in theory this could be a simple hashtable lookup; most
4106     // changes to CurContext don't change the set of current
4107     // instantiations.
4108     if (isa<ClassTemplateDecl>(Template)) {
4109       for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
4110         // If we get out to a namespace, we're done.
4111         if (Ctx->isFileContext()) break;
4112 
4113         // If this isn't a record, keep looking.
4114         CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
4115         if (!Record) continue;
4116 
4117         // Look for one of the two cases with InjectedClassNameTypes
4118         // and check whether it's the same template.
4119         if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
4120             !Record->getDescribedClassTemplate())
4121           continue;
4122 
4123         // Fetch the injected class name type and check whether its
4124         // injected type is equal to the type we just built.
4125         QualType ICNT = Context.getTypeDeclType(Record);
4126         QualType Injected = cast<InjectedClassNameType>(ICNT)
4127           ->getInjectedSpecializationType();
4128 
4129         if (CanonType != Injected->getCanonicalTypeInternal())
4130           continue;
4131 
4132         // If so, the canonical type of this TST is the injected
4133         // class name type of the record we just found.
4134         assert(ICNT.isCanonical());
4135         CanonType = ICNT;
4136         break;
4137       }
4138     }
4139   } else if (ClassTemplateDecl *ClassTemplate =
4140                  dyn_cast<ClassTemplateDecl>(Template)) {
4141     // Find the class template specialization declaration that
4142     // corresponds to these arguments.
4143     void *InsertPos = nullptr;
4144     ClassTemplateSpecializationDecl *Decl =
4145         ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
4146     if (!Decl) {
4147       // This is the first time we have referenced this class template
4148       // specialization. Create the canonical declaration and add it to
4149       // the set of specializations.
4150       Decl = ClassTemplateSpecializationDecl::Create(
4151           Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
4152           ClassTemplate->getDeclContext(),
4153           ClassTemplate->getTemplatedDecl()->getBeginLoc(),
4154           ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
4155           nullptr);
4156       ClassTemplate->AddSpecialization(Decl, InsertPos);
4157       if (ClassTemplate->isOutOfLine())
4158         Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
4159     }
4160 
4161     if (Decl->getSpecializationKind() == TSK_Undeclared &&
4162         ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4163       InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4164       if (!Inst.isInvalid()) {
4165         MultiLevelTemplateArgumentList TemplateArgLists(Template,
4166                                                         CanonicalConverted,
4167                                                         /*Final=*/false);
4168         InstantiateAttrsForDecl(TemplateArgLists,
4169                                 ClassTemplate->getTemplatedDecl(), Decl);
4170       }
4171     }
4172 
4173     // Diagnose uses of this specialization.
4174     (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4175 
4176     CanonType = Context.getTypeDeclType(Decl);
4177     assert(isa<RecordType>(CanonType) &&
4178            "type of non-dependent specialization is not a RecordType");
4179   } else {
4180     llvm_unreachable("Unhandled template kind");
4181   }
4182 
4183   // Build the fully-sugared type for this class template
4184   // specialization, which refers back to the class template
4185   // specialization we created or found.
4186   return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
4187                                                CanonType);
4188 }
4189 
ActOnUndeclaredTypeTemplateName(Scope * S,TemplateTy & ParsedName,TemplateNameKind & TNK,SourceLocation NameLoc,IdentifierInfo * & II)4190 void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
4191                                            TemplateNameKind &TNK,
4192                                            SourceLocation NameLoc,
4193                                            IdentifierInfo *&II) {
4194   assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4195 
4196   TemplateName Name = ParsedName.get();
4197   auto *ATN = Name.getAsAssumedTemplateName();
4198   assert(ATN && "not an assumed template name");
4199   II = ATN->getDeclName().getAsIdentifierInfo();
4200 
4201   if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
4202     // Resolved to a type template name.
4203     ParsedName = TemplateTy::make(Name);
4204     TNK = TNK_Type_template;
4205   }
4206 }
4207 
resolveAssumedTemplateNameAsType(Scope * S,TemplateName & Name,SourceLocation NameLoc,bool Diagnose)4208 bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
4209                                             SourceLocation NameLoc,
4210                                             bool Diagnose) {
4211   // We assumed this undeclared identifier to be an (ADL-only) function
4212   // template name, but it was used in a context where a type was required.
4213   // Try to typo-correct it now.
4214   AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
4215   assert(ATN && "not an assumed template name");
4216 
4217   LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
4218   struct CandidateCallback : CorrectionCandidateCallback {
4219     bool ValidateCandidate(const TypoCorrection &TC) override {
4220       return TC.getCorrectionDecl() &&
4221              getAsTypeTemplateDecl(TC.getCorrectionDecl());
4222     }
4223     std::unique_ptr<CorrectionCandidateCallback> clone() override {
4224       return std::make_unique<CandidateCallback>(*this);
4225     }
4226   } FilterCCC;
4227 
4228   TypoCorrection Corrected =
4229       CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
4230                   FilterCCC, CTK_ErrorRecovery);
4231   if (Corrected && Corrected.getFoundDecl()) {
4232     diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
4233                                 << ATN->getDeclName());
4234     Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
4235     return false;
4236   }
4237 
4238   if (Diagnose)
4239     Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
4240   return true;
4241 }
4242 
ActOnTemplateIdType(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,TemplateTy TemplateD,IdentifierInfo * TemplateII,SourceLocation TemplateIILoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc,bool IsCtorOrDtorName,bool IsClassName,ImplicitTypenameContext AllowImplicitTypename)4243 TypeResult Sema::ActOnTemplateIdType(
4244     Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4245     TemplateTy TemplateD, IdentifierInfo *TemplateII,
4246     SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
4247     ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
4248     bool IsCtorOrDtorName, bool IsClassName,
4249     ImplicitTypenameContext AllowImplicitTypename) {
4250   if (SS.isInvalid())
4251     return true;
4252 
4253   if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4254     DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4255 
4256     // C++ [temp.res]p3:
4257     //   A qualified-id that refers to a type and in which the
4258     //   nested-name-specifier depends on a template-parameter (14.6.2)
4259     //   shall be prefixed by the keyword typename to indicate that the
4260     //   qualified-id denotes a type, forming an
4261     //   elaborated-type-specifier (7.1.5.3).
4262     if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4263       // C++2a relaxes some of those restrictions in [temp.res]p5.
4264       if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4265         if (getLangOpts().CPlusPlus20)
4266           Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
4267         else
4268           Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
4269               << SS.getScopeRep() << TemplateII->getName()
4270               << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4271       } else
4272         Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
4273             << SS.getScopeRep() << TemplateII->getName();
4274 
4275       // FIXME: This is not quite correct recovery as we don't transform SS
4276       // into the corresponding dependent form (and we don't diagnose missing
4277       // 'template' keywords within SS as a result).
4278       return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4279                                TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4280                                TemplateArgsIn, RAngleLoc);
4281     }
4282 
4283     // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4284     // it's not actually allowed to be used as a type in most cases. Because
4285     // we annotate it before we know whether it's valid, we have to check for
4286     // this case here.
4287     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4288     if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4289       Diag(TemplateIILoc,
4290            TemplateKWLoc.isInvalid()
4291                ? diag::err_out_of_line_qualified_id_type_names_constructor
4292                : diag::ext_out_of_line_qualified_id_type_names_constructor)
4293         << TemplateII << 0 /*injected-class-name used as template name*/
4294         << 1 /*if any keyword was present, it was 'template'*/;
4295     }
4296   }
4297 
4298   TemplateName Template = TemplateD.get();
4299   if (Template.getAsAssumedTemplateName() &&
4300       resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
4301     return true;
4302 
4303   // Translate the parser's template argument list in our AST format.
4304   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4305   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4306 
4307   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4308     assert(SS.getScopeRep() == DTN->getQualifier());
4309     QualType T = Context.getDependentTemplateSpecializationType(
4310         ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
4311         TemplateArgs.arguments());
4312     // Build type-source information.
4313     TypeLocBuilder TLB;
4314     DependentTemplateSpecializationTypeLoc SpecTL
4315       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
4316     SpecTL.setElaboratedKeywordLoc(SourceLocation());
4317     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4318     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4319     SpecTL.setTemplateNameLoc(TemplateIILoc);
4320     SpecTL.setLAngleLoc(LAngleLoc);
4321     SpecTL.setRAngleLoc(RAngleLoc);
4322     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4323       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4324     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4325   }
4326 
4327   QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
4328   if (SpecTy.isNull())
4329     return true;
4330 
4331   // Build type-source information.
4332   TypeLocBuilder TLB;
4333   TemplateSpecializationTypeLoc SpecTL =
4334       TLB.push<TemplateSpecializationTypeLoc>(SpecTy);
4335   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4336   SpecTL.setTemplateNameLoc(TemplateIILoc);
4337   SpecTL.setLAngleLoc(LAngleLoc);
4338   SpecTL.setRAngleLoc(RAngleLoc);
4339   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4340     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4341 
4342   // Create an elaborated-type-specifier containing the nested-name-specifier.
4343   QualType ElTy =
4344       getElaboratedType(ElaboratedTypeKeyword::None,
4345                         !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
4346   ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
4347   ElabTL.setElaboratedKeywordLoc(SourceLocation());
4348   if (!ElabTL.isEmpty())
4349     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4350   return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
4351 }
4352 
ActOnTagTemplateIdType(TagUseKind TUK,TypeSpecifierType TagSpec,SourceLocation TagLoc,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,TemplateTy TemplateD,SourceLocation TemplateLoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc)4353 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4354                                         TypeSpecifierType TagSpec,
4355                                         SourceLocation TagLoc,
4356                                         CXXScopeSpec &SS,
4357                                         SourceLocation TemplateKWLoc,
4358                                         TemplateTy TemplateD,
4359                                         SourceLocation TemplateLoc,
4360                                         SourceLocation LAngleLoc,
4361                                         ASTTemplateArgsPtr TemplateArgsIn,
4362                                         SourceLocation RAngleLoc) {
4363   if (SS.isInvalid())
4364     return TypeResult(true);
4365 
4366   TemplateName Template = TemplateD.get();
4367 
4368   // Translate the parser's template argument list in our AST format.
4369   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4370   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4371 
4372   // Determine the tag kind
4373   TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4374   ElaboratedTypeKeyword Keyword
4375     = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
4376 
4377   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4378     assert(SS.getScopeRep() == DTN->getQualifier());
4379     QualType T = Context.getDependentTemplateSpecializationType(
4380         Keyword, DTN->getQualifier(), DTN->getIdentifier(),
4381         TemplateArgs.arguments());
4382 
4383     // Build type-source information.
4384     TypeLocBuilder TLB;
4385     DependentTemplateSpecializationTypeLoc SpecTL
4386       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
4387     SpecTL.setElaboratedKeywordLoc(TagLoc);
4388     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4389     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4390     SpecTL.setTemplateNameLoc(TemplateLoc);
4391     SpecTL.setLAngleLoc(LAngleLoc);
4392     SpecTL.setRAngleLoc(RAngleLoc);
4393     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4394       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4395     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4396   }
4397 
4398   if (TypeAliasTemplateDecl *TAT =
4399         dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
4400     // C++0x [dcl.type.elab]p2:
4401     //   If the identifier resolves to a typedef-name or the simple-template-id
4402     //   resolves to an alias template specialization, the
4403     //   elaborated-type-specifier is ill-formed.
4404     Diag(TemplateLoc, diag::err_tag_reference_non_tag)
4405         << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
4406     Diag(TAT->getLocation(), diag::note_declared_at);
4407   }
4408 
4409   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
4410   if (Result.isNull())
4411     return TypeResult(true);
4412 
4413   // Check the tag kind
4414   if (const RecordType *RT = Result->getAs<RecordType>()) {
4415     RecordDecl *D = RT->getDecl();
4416 
4417     IdentifierInfo *Id = D->getIdentifier();
4418     assert(Id && "templated class must have an identifier");
4419 
4420     if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
4421                                       TagLoc, Id)) {
4422       Diag(TagLoc, diag::err_use_with_wrong_tag)
4423         << Result
4424         << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
4425       Diag(D->getLocation(), diag::note_previous_use);
4426     }
4427   }
4428 
4429   // Provide source-location information for the template specialization.
4430   TypeLocBuilder TLB;
4431   TemplateSpecializationTypeLoc SpecTL
4432     = TLB.push<TemplateSpecializationTypeLoc>(Result);
4433   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4434   SpecTL.setTemplateNameLoc(TemplateLoc);
4435   SpecTL.setLAngleLoc(LAngleLoc);
4436   SpecTL.setRAngleLoc(RAngleLoc);
4437   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4438     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4439 
4440   // Construct an elaborated type containing the nested-name-specifier (if any)
4441   // and tag keyword.
4442   Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
4443   ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
4444   ElabTL.setElaboratedKeywordLoc(TagLoc);
4445   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4446   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
4447 }
4448 
4449 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4450                                              NamedDecl *PrevDecl,
4451                                              SourceLocation Loc,
4452                                              bool IsPartialSpecialization);
4453 
4454 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4455 
isTemplateArgumentTemplateParameter(const TemplateArgument & Arg,unsigned Depth,unsigned Index)4456 static bool isTemplateArgumentTemplateParameter(
4457     const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
4458   switch (Arg.getKind()) {
4459   case TemplateArgument::Null:
4460   case TemplateArgument::NullPtr:
4461   case TemplateArgument::Integral:
4462   case TemplateArgument::Declaration:
4463   case TemplateArgument::StructuralValue:
4464   case TemplateArgument::Pack:
4465   case TemplateArgument::TemplateExpansion:
4466     return false;
4467 
4468   case TemplateArgument::Type: {
4469     QualType Type = Arg.getAsType();
4470     const TemplateTypeParmType *TPT =
4471         Arg.getAsType()->getAs<TemplateTypeParmType>();
4472     return TPT && !Type.hasQualifiers() &&
4473            TPT->getDepth() == Depth && TPT->getIndex() == Index;
4474   }
4475 
4476   case TemplateArgument::Expression: {
4477     DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4478     if (!DRE || !DRE->getDecl())
4479       return false;
4480     const NonTypeTemplateParmDecl *NTTP =
4481         dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4482     return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4483   }
4484 
4485   case TemplateArgument::Template:
4486     const TemplateTemplateParmDecl *TTP =
4487         dyn_cast_or_null<TemplateTemplateParmDecl>(
4488             Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4489     return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4490   }
4491   llvm_unreachable("unexpected kind of template argument");
4492 }
4493 
isSameAsPrimaryTemplate(TemplateParameterList * Params,ArrayRef<TemplateArgument> Args)4494 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4495                                     ArrayRef<TemplateArgument> Args) {
4496   if (Params->size() != Args.size())
4497     return false;
4498 
4499   unsigned Depth = Params->getDepth();
4500 
4501   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4502     TemplateArgument Arg = Args[I];
4503 
4504     // If the parameter is a pack expansion, the argument must be a pack
4505     // whose only element is a pack expansion.
4506     if (Params->getParam(I)->isParameterPack()) {
4507       if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4508           !Arg.pack_begin()->isPackExpansion())
4509         return false;
4510       Arg = Arg.pack_begin()->getPackExpansionPattern();
4511     }
4512 
4513     if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4514       return false;
4515   }
4516 
4517   return true;
4518 }
4519 
4520 template<typename PartialSpecDecl>
checkMoreSpecializedThanPrimary(Sema & S,PartialSpecDecl * Partial)4521 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4522   if (Partial->getDeclContext()->isDependentContext())
4523     return;
4524 
4525   // FIXME: Get the TDK from deduction in order to provide better diagnostics
4526   // for non-substitution-failure issues?
4527   TemplateDeductionInfo Info(Partial->getLocation());
4528   if (S.isMoreSpecializedThanPrimary(Partial, Info))
4529     return;
4530 
4531   auto *Template = Partial->getSpecializedTemplate();
4532   S.Diag(Partial->getLocation(),
4533          diag::ext_partial_spec_not_more_specialized_than_primary)
4534       << isa<VarTemplateDecl>(Template);
4535 
4536   if (Info.hasSFINAEDiagnostic()) {
4537     PartialDiagnosticAt Diag = {SourceLocation(),
4538                                 PartialDiagnostic::NullDiagnostic()};
4539     Info.takeSFINAEDiagnostic(Diag);
4540     SmallString<128> SFINAEArgString;
4541     Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4542     S.Diag(Diag.first,
4543            diag::note_partial_spec_not_more_specialized_than_primary)
4544       << SFINAEArgString;
4545   }
4546 
4547   S.NoteTemplateLocation(*Template);
4548   SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4549   Template->getAssociatedConstraints(TemplateAC);
4550   Partial->getAssociatedConstraints(PartialAC);
4551   S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4552                                                   TemplateAC);
4553 }
4554 
4555 static void
noteNonDeducibleParameters(Sema & S,TemplateParameterList * TemplateParams,const llvm::SmallBitVector & DeducibleParams)4556 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4557                            const llvm::SmallBitVector &DeducibleParams) {
4558   for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4559     if (!DeducibleParams[I]) {
4560       NamedDecl *Param = TemplateParams->getParam(I);
4561       if (Param->getDeclName())
4562         S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4563             << Param->getDeclName();
4564       else
4565         S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4566             << "(anonymous)";
4567     }
4568   }
4569 }
4570 
4571 
4572 template<typename PartialSpecDecl>
checkTemplatePartialSpecialization(Sema & S,PartialSpecDecl * Partial)4573 static void checkTemplatePartialSpecialization(Sema &S,
4574                                                PartialSpecDecl *Partial) {
4575   // C++1z [temp.class.spec]p8: (DR1495)
4576   //   - The specialization shall be more specialized than the primary
4577   //     template (14.5.5.2).
4578   checkMoreSpecializedThanPrimary(S, Partial);
4579 
4580   // C++ [temp.class.spec]p8: (DR1315)
4581   //   - Each template-parameter shall appear at least once in the
4582   //     template-id outside a non-deduced context.
4583   // C++1z [temp.class.spec.match]p3 (P0127R2)
4584   //   If the template arguments of a partial specialization cannot be
4585   //   deduced because of the structure of its template-parameter-list
4586   //   and the template-id, the program is ill-formed.
4587   auto *TemplateParams = Partial->getTemplateParameters();
4588   llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4589   S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4590                                TemplateParams->getDepth(), DeducibleParams);
4591 
4592   if (!DeducibleParams.all()) {
4593     unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4594     S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4595       << isa<VarTemplatePartialSpecializationDecl>(Partial)
4596       << (NumNonDeducible > 1)
4597       << SourceRange(Partial->getLocation(),
4598                      Partial->getTemplateArgsAsWritten()->RAngleLoc);
4599     noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4600   }
4601 }
4602 
CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl * Partial)4603 void Sema::CheckTemplatePartialSpecialization(
4604     ClassTemplatePartialSpecializationDecl *Partial) {
4605   checkTemplatePartialSpecialization(*this, Partial);
4606 }
4607 
CheckTemplatePartialSpecialization(VarTemplatePartialSpecializationDecl * Partial)4608 void Sema::CheckTemplatePartialSpecialization(
4609     VarTemplatePartialSpecializationDecl *Partial) {
4610   checkTemplatePartialSpecialization(*this, Partial);
4611 }
4612 
CheckDeductionGuideTemplate(FunctionTemplateDecl * TD)4613 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4614   // C++1z [temp.param]p11:
4615   //   A template parameter of a deduction guide template that does not have a
4616   //   default-argument shall be deducible from the parameter-type-list of the
4617   //   deduction guide template.
4618   auto *TemplateParams = TD->getTemplateParameters();
4619   llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4620   MarkDeducedTemplateParameters(TD, DeducibleParams);
4621   for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4622     // A parameter pack is deducible (to an empty pack).
4623     auto *Param = TemplateParams->getParam(I);
4624     if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4625       DeducibleParams[I] = true;
4626   }
4627 
4628   if (!DeducibleParams.all()) {
4629     unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4630     Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4631       << (NumNonDeducible > 1);
4632     noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4633   }
4634 }
4635 
ActOnVarTemplateSpecialization(Scope * S,Declarator & D,TypeSourceInfo * DI,SourceLocation TemplateKWLoc,TemplateParameterList * TemplateParams,StorageClass SC,bool IsPartialSpecialization)4636 DeclResult Sema::ActOnVarTemplateSpecialization(
4637     Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
4638     TemplateParameterList *TemplateParams, StorageClass SC,
4639     bool IsPartialSpecialization) {
4640   // D must be variable template id.
4641   assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4642          "Variable template specialization is declared with a template id.");
4643 
4644   TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4645   TemplateArgumentListInfo TemplateArgs =
4646       makeTemplateArgumentListInfo(*this, *TemplateId);
4647   SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4648   SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4649   SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4650 
4651   TemplateName Name = TemplateId->Template.get();
4652 
4653   // The template-id must name a variable template.
4654   VarTemplateDecl *VarTemplate =
4655       dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4656   if (!VarTemplate) {
4657     NamedDecl *FnTemplate;
4658     if (auto *OTS = Name.getAsOverloadedTemplate())
4659       FnTemplate = *OTS->begin();
4660     else
4661       FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4662     if (FnTemplate)
4663       return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4664                << FnTemplate->getDeclName();
4665     return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4666              << IsPartialSpecialization;
4667   }
4668 
4669   // Check for unexpanded parameter packs in any of the template arguments.
4670   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4671     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4672                                         IsPartialSpecialization
4673                                             ? UPPC_PartialSpecialization
4674                                             : UPPC_ExplicitSpecialization))
4675       return true;
4676 
4677   // Check that the template argument list is well-formed for this
4678   // template.
4679   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4680   if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4681                                 false, SugaredConverted, CanonicalConverted,
4682                                 /*UpdateArgsWithConversions=*/true))
4683     return true;
4684 
4685   // Find the variable template (partial) specialization declaration that
4686   // corresponds to these arguments.
4687   if (IsPartialSpecialization) {
4688     if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4689                                                TemplateArgs.size(),
4690                                                CanonicalConverted))
4691       return true;
4692 
4693     // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4694     // also do them during instantiation.
4695     if (!Name.isDependent() &&
4696         !TemplateSpecializationType::anyDependentTemplateArguments(
4697             TemplateArgs, CanonicalConverted)) {
4698       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4699           << VarTemplate->getDeclName();
4700       IsPartialSpecialization = false;
4701     }
4702 
4703     if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4704                                 CanonicalConverted) &&
4705         (!Context.getLangOpts().CPlusPlus20 ||
4706          !TemplateParams->hasAssociatedConstraints())) {
4707       // C++ [temp.class.spec]p9b3:
4708       //
4709       //   -- The argument list of the specialization shall not be identical
4710       //      to the implicit argument list of the primary template.
4711       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4712         << /*variable template*/ 1
4713         << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4714         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4715       // FIXME: Recover from this by treating the declaration as a redeclaration
4716       // of the primary template.
4717       return true;
4718     }
4719   }
4720 
4721   void *InsertPos = nullptr;
4722   VarTemplateSpecializationDecl *PrevDecl = nullptr;
4723 
4724   if (IsPartialSpecialization)
4725     PrevDecl = VarTemplate->findPartialSpecialization(
4726         CanonicalConverted, TemplateParams, InsertPos);
4727   else
4728     PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4729 
4730   VarTemplateSpecializationDecl *Specialization = nullptr;
4731 
4732   // Check whether we can declare a variable template specialization in
4733   // the current scope.
4734   if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4735                                        TemplateNameLoc,
4736                                        IsPartialSpecialization))
4737     return true;
4738 
4739   if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4740     // Since the only prior variable template specialization with these
4741     // arguments was referenced but not declared,  reuse that
4742     // declaration node as our own, updating its source location and
4743     // the list of outer template parameters to reflect our new declaration.
4744     Specialization = PrevDecl;
4745     Specialization->setLocation(TemplateNameLoc);
4746     PrevDecl = nullptr;
4747   } else if (IsPartialSpecialization) {
4748     // Create a new class template partial specialization declaration node.
4749     VarTemplatePartialSpecializationDecl *PrevPartial =
4750         cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4751     VarTemplatePartialSpecializationDecl *Partial =
4752         VarTemplatePartialSpecializationDecl::Create(
4753             Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4754             TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4755             CanonicalConverted, TemplateArgs);
4756 
4757     if (!PrevPartial)
4758       VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4759     Specialization = Partial;
4760 
4761     // If we are providing an explicit specialization of a member variable
4762     // template specialization, make a note of that.
4763     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4764       PrevPartial->setMemberSpecialization();
4765 
4766     CheckTemplatePartialSpecialization(Partial);
4767   } else {
4768     // Create a new class template specialization declaration node for
4769     // this explicit specialization or friend declaration.
4770     Specialization = VarTemplateSpecializationDecl::Create(
4771         Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4772         VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4773     Specialization->setTemplateArgsInfo(TemplateArgs);
4774 
4775     if (!PrevDecl)
4776       VarTemplate->AddSpecialization(Specialization, InsertPos);
4777   }
4778 
4779   // C++ [temp.expl.spec]p6:
4780   //   If a template, a member template or the member of a class template is
4781   //   explicitly specialized then that specialization shall be declared
4782   //   before the first use of that specialization that would cause an implicit
4783   //   instantiation to take place, in every translation unit in which such a
4784   //   use occurs; no diagnostic is required.
4785   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4786     bool Okay = false;
4787     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4788       // Is there any previous explicit specialization declaration?
4789       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4790         Okay = true;
4791         break;
4792       }
4793     }
4794 
4795     if (!Okay) {
4796       SourceRange Range(TemplateNameLoc, RAngleLoc);
4797       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4798           << Name << Range;
4799 
4800       Diag(PrevDecl->getPointOfInstantiation(),
4801            diag::note_instantiation_required_here)
4802           << (PrevDecl->getTemplateSpecializationKind() !=
4803               TSK_ImplicitInstantiation);
4804       return true;
4805     }
4806   }
4807 
4808   Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4809   Specialization->setLexicalDeclContext(CurContext);
4810 
4811   // Add the specialization into its lexical context, so that it can
4812   // be seen when iterating through the list of declarations in that
4813   // context. However, specializations are not found by name lookup.
4814   CurContext->addDecl(Specialization);
4815 
4816   // Note that this is an explicit specialization.
4817   Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4818 
4819   if (PrevDecl) {
4820     // Check that this isn't a redefinition of this specialization,
4821     // merging with previous declarations.
4822     LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
4823                           forRedeclarationInCurContext());
4824     PrevSpec.addDecl(PrevDecl);
4825     D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
4826   } else if (Specialization->isStaticDataMember() &&
4827              Specialization->isOutOfLine()) {
4828     Specialization->setAccess(VarTemplate->getAccess());
4829   }
4830 
4831   return Specialization;
4832 }
4833 
4834 namespace {
4835 /// A partial specialization whose template arguments have matched
4836 /// a given template-id.
4837 struct PartialSpecMatchResult {
4838   VarTemplatePartialSpecializationDecl *Partial;
4839   TemplateArgumentList *Args;
4840 };
4841 } // end anonymous namespace
4842 
4843 DeclResult
CheckVarTemplateId(VarTemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation TemplateNameLoc,const TemplateArgumentListInfo & TemplateArgs)4844 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4845                          SourceLocation TemplateNameLoc,
4846                          const TemplateArgumentListInfo &TemplateArgs) {
4847   assert(Template && "A variable template id without template?");
4848 
4849   // Check that the template argument list is well-formed for this template.
4850   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4851   if (CheckTemplateArgumentList(
4852           Template, TemplateNameLoc,
4853           const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4854           SugaredConverted, CanonicalConverted,
4855           /*UpdateArgsWithConversions=*/true))
4856     return true;
4857 
4858   // Produce a placeholder value if the specialization is dependent.
4859   if (Template->getDeclContext()->isDependentContext() ||
4860       TemplateSpecializationType::anyDependentTemplateArguments(
4861           TemplateArgs, CanonicalConverted))
4862     return DeclResult();
4863 
4864   // Find the variable template specialization declaration that
4865   // corresponds to these arguments.
4866   void *InsertPos = nullptr;
4867   if (VarTemplateSpecializationDecl *Spec =
4868           Template->findSpecialization(CanonicalConverted, InsertPos)) {
4869     checkSpecializationReachability(TemplateNameLoc, Spec);
4870     // If we already have a variable template specialization, return it.
4871     return Spec;
4872   }
4873 
4874   // This is the first time we have referenced this variable template
4875   // specialization. Create the canonical declaration and add it to
4876   // the set of specializations, based on the closest partial specialization
4877   // that it represents. That is,
4878   VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4879   TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
4880                                        CanonicalConverted);
4881   TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4882   bool AmbiguousPartialSpec = false;
4883   typedef PartialSpecMatchResult MatchResult;
4884   SmallVector<MatchResult, 4> Matched;
4885   SourceLocation PointOfInstantiation = TemplateNameLoc;
4886   TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4887                                             /*ForTakingAddress=*/false);
4888 
4889   // 1. Attempt to find the closest partial specialization that this
4890   // specializes, if any.
4891   // TODO: Unify with InstantiateClassTemplateSpecialization()?
4892   //       Perhaps better after unification of DeduceTemplateArguments() and
4893   //       getMoreSpecializedPartialSpecialization().
4894   SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4895   Template->getPartialSpecializations(PartialSpecs);
4896 
4897   for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4898     VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4899     TemplateDeductionInfo Info(FailedCandidates.getLocation());
4900 
4901     if (TemplateDeductionResult Result =
4902             DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4903       // Store the failed-deduction information for use in diagnostics, later.
4904       // TODO: Actually use the failed-deduction info?
4905       FailedCandidates.addCandidate().set(
4906           DeclAccessPair::make(Template, AS_public), Partial,
4907           MakeDeductionFailureInfo(Context, Result, Info));
4908       (void)Result;
4909     } else {
4910       Matched.push_back(PartialSpecMatchResult());
4911       Matched.back().Partial = Partial;
4912       Matched.back().Args = Info.takeCanonical();
4913     }
4914   }
4915 
4916   if (Matched.size() >= 1) {
4917     SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4918     if (Matched.size() == 1) {
4919       //   -- If exactly one matching specialization is found, the
4920       //      instantiation is generated from that specialization.
4921       // We don't need to do anything for this.
4922     } else {
4923       //   -- If more than one matching specialization is found, the
4924       //      partial order rules (14.5.4.2) are used to determine
4925       //      whether one of the specializations is more specialized
4926       //      than the others. If none of the specializations is more
4927       //      specialized than all of the other matching
4928       //      specializations, then the use of the variable template is
4929       //      ambiguous and the program is ill-formed.
4930       for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4931                                                  PEnd = Matched.end();
4932            P != PEnd; ++P) {
4933         if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4934                                                     PointOfInstantiation) ==
4935             P->Partial)
4936           Best = P;
4937       }
4938 
4939       // Determine if the best partial specialization is more specialized than
4940       // the others.
4941       for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4942                                                  PEnd = Matched.end();
4943            P != PEnd; ++P) {
4944         if (P != Best && getMoreSpecializedPartialSpecialization(
4945                              P->Partial, Best->Partial,
4946                              PointOfInstantiation) != Best->Partial) {
4947           AmbiguousPartialSpec = true;
4948           break;
4949         }
4950       }
4951     }
4952 
4953     // Instantiate using the best variable template partial specialization.
4954     InstantiationPattern = Best->Partial;
4955     InstantiationArgs = Best->Args;
4956   } else {
4957     //   -- If no match is found, the instantiation is generated
4958     //      from the primary template.
4959     // InstantiationPattern = Template->getTemplatedDecl();
4960   }
4961 
4962   // 2. Create the canonical declaration.
4963   // Note that we do not instantiate a definition until we see an odr-use
4964   // in DoMarkVarDeclReferenced().
4965   // FIXME: LateAttrs et al.?
4966   VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4967       Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4968       CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4969   if (!Decl)
4970     return true;
4971 
4972   if (AmbiguousPartialSpec) {
4973     // Partial ordering did not produce a clear winner. Complain.
4974     Decl->setInvalidDecl();
4975     Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4976         << Decl;
4977 
4978     // Print the matching partial specializations.
4979     for (MatchResult P : Matched)
4980       Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4981           << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4982                                              *P.Args);
4983     return true;
4984   }
4985 
4986   if (VarTemplatePartialSpecializationDecl *D =
4987           dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4988     Decl->setInstantiationOf(D, InstantiationArgs);
4989 
4990   checkSpecializationReachability(TemplateNameLoc, Decl);
4991 
4992   assert(Decl && "No variable template specialization?");
4993   return Decl;
4994 }
4995 
4996 ExprResult
CheckVarTemplateId(const CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,VarTemplateDecl * Template,SourceLocation TemplateLoc,const TemplateArgumentListInfo * TemplateArgs)4997 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4998                          const DeclarationNameInfo &NameInfo,
4999                          VarTemplateDecl *Template, SourceLocation TemplateLoc,
5000                          const TemplateArgumentListInfo *TemplateArgs) {
5001 
5002   DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
5003                                        *TemplateArgs);
5004   if (Decl.isInvalid())
5005     return ExprError();
5006 
5007   if (!Decl.get())
5008     return ExprResult();
5009 
5010   VarDecl *Var = cast<VarDecl>(Decl.get());
5011   if (!Var->getTemplateSpecializationKind())
5012     Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
5013                                        NameInfo.getLoc());
5014 
5015   // Build an ordinary singleton decl ref.
5016   return BuildDeclarationNameExpr(SS, NameInfo, Var,
5017                                   /*FoundD=*/nullptr, TemplateArgs);
5018 }
5019 
diagnoseMissingTemplateArguments(TemplateName Name,SourceLocation Loc)5020 void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
5021                                             SourceLocation Loc) {
5022   Diag(Loc, diag::err_template_missing_args)
5023     << (int)getTemplateNameKindForDiagnostics(Name) << Name;
5024   if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
5025     NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
5026   }
5027 }
5028 
5029 ExprResult
CheckConceptTemplateId(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & ConceptNameInfo,NamedDecl * FoundDecl,ConceptDecl * NamedConcept,const TemplateArgumentListInfo * TemplateArgs)5030 Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
5031                              SourceLocation TemplateKWLoc,
5032                              const DeclarationNameInfo &ConceptNameInfo,
5033                              NamedDecl *FoundDecl,
5034                              ConceptDecl *NamedConcept,
5035                              const TemplateArgumentListInfo *TemplateArgs) {
5036   assert(NamedConcept && "A concept template id without a template?");
5037 
5038   llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5039   if (CheckTemplateArgumentList(
5040           NamedConcept, ConceptNameInfo.getLoc(),
5041           const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
5042           /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
5043           /*UpdateArgsWithConversions=*/false))
5044     return ExprError();
5045 
5046   auto *CSD = ImplicitConceptSpecializationDecl::Create(
5047       Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
5048       CanonicalConverted);
5049   ConstraintSatisfaction Satisfaction;
5050   bool AreArgsDependent =
5051       TemplateSpecializationType::anyDependentTemplateArguments(
5052           *TemplateArgs, CanonicalConverted);
5053   MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
5054                                        /*Final=*/false);
5055   LocalInstantiationScope Scope(*this);
5056 
5057   EnterExpressionEvaluationContext EECtx{
5058       *this, ExpressionEvaluationContext::ConstantEvaluated, CSD};
5059 
5060   if (!AreArgsDependent &&
5061       CheckConstraintSatisfaction(
5062           NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
5063           SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
5064                       TemplateArgs->getRAngleLoc()),
5065           Satisfaction))
5066     return ExprError();
5067   auto *CL = ConceptReference::Create(
5068       Context,
5069       SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
5070       TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
5071       ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs));
5072   return ConceptSpecializationExpr::Create(
5073       Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
5074 }
5075 
BuildTemplateIdExpr(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,LookupResult & R,bool RequiresADL,const TemplateArgumentListInfo * TemplateArgs)5076 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
5077                                      SourceLocation TemplateKWLoc,
5078                                      LookupResult &R,
5079                                      bool RequiresADL,
5080                                  const TemplateArgumentListInfo *TemplateArgs) {
5081   // FIXME: Can we do any checking at this point? I guess we could check the
5082   // template arguments that we have against the template name, if the template
5083   // name refers to a single template. That's not a terribly common case,
5084   // though.
5085   // foo<int> could identify a single function unambiguously
5086   // This approach does NOT work, since f<int>(1);
5087   // gets resolved prior to resorting to overload resolution
5088   // i.e., template<class T> void f(double);
5089   //       vs template<class T, class U> void f(U);
5090 
5091   // These should be filtered out by our callers.
5092   assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
5093 
5094   // Non-function templates require a template argument list.
5095   if (auto *TD = R.getAsSingle<TemplateDecl>()) {
5096     if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
5097       diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
5098       return ExprError();
5099     }
5100   }
5101   bool KnownDependent = false;
5102   // In C++1y, check variable template ids.
5103   if (R.getAsSingle<VarTemplateDecl>()) {
5104     ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(),
5105                                         R.getAsSingle<VarTemplateDecl>(),
5106                                         TemplateKWLoc, TemplateArgs);
5107     if (Res.isInvalid() || Res.isUsable())
5108       return Res;
5109     // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
5110     KnownDependent = true;
5111   }
5112 
5113   if (R.getAsSingle<ConceptDecl>()) {
5114     return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
5115                                   R.getFoundDecl(),
5116                                   R.getAsSingle<ConceptDecl>(), TemplateArgs);
5117   }
5118 
5119   // We don't want lookup warnings at this point.
5120   R.suppressDiagnostics();
5121 
5122   UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
5123       Context, R.getNamingClass(), SS.getWithLocInContext(Context),
5124       TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5125       R.begin(), R.end(), KnownDependent);
5126 
5127   return ULE;
5128 }
5129 
5130 // We actually only call this from template instantiation.
5131 ExprResult
BuildQualifiedTemplateIdExpr(CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * TemplateArgs)5132 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5133                                    SourceLocation TemplateKWLoc,
5134                                    const DeclarationNameInfo &NameInfo,
5135                              const TemplateArgumentListInfo *TemplateArgs) {
5136 
5137   assert(TemplateArgs || TemplateKWLoc.isValid());
5138   DeclContext *DC;
5139   if (!(DC = computeDeclContext(SS, false)) ||
5140       DC->isDependentContext() ||
5141       RequireCompleteDeclContext(SS, DC))
5142     return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5143 
5144   bool MemberOfUnknownSpecialization;
5145   LookupResult R(*this, NameInfo, LookupOrdinaryName);
5146   if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
5147                          /*Entering*/false, MemberOfUnknownSpecialization,
5148                          TemplateKWLoc))
5149     return ExprError();
5150 
5151   if (R.isAmbiguous())
5152     return ExprError();
5153 
5154   if (R.empty()) {
5155     Diag(NameInfo.getLoc(), diag::err_no_member)
5156       << NameInfo.getName() << DC << SS.getRange();
5157     return ExprError();
5158   }
5159 
5160   auto DiagnoseTypeTemplateDecl = [&](TemplateDecl *Temp,
5161                                       bool isTypeAliasTemplateDecl) {
5162     Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
5163         << SS.getScopeRep() << NameInfo.getName().getAsString() << SS.getRange()
5164         << isTypeAliasTemplateDecl;
5165     Diag(Temp->getLocation(), diag::note_referenced_type_template) << 0;
5166     return ExprError();
5167   };
5168 
5169   if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>())
5170     return DiagnoseTypeTemplateDecl(Temp, false);
5171 
5172   if (TypeAliasTemplateDecl *Temp = R.getAsSingle<TypeAliasTemplateDecl>())
5173     return DiagnoseTypeTemplateDecl(Temp, true);
5174 
5175   return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
5176 }
5177 
5178 /// Form a template name from a name that is syntactically required to name a
5179 /// template, either due to use of the 'template' keyword or because a name in
5180 /// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
5181 ///
5182 /// This action forms a template name given the name of the template and its
5183 /// optional scope specifier. This is used when the 'template' keyword is used
5184 /// or when the parsing context unambiguously treats a following '<' as
5185 /// introducing a template argument list. Note that this may produce a
5186 /// non-dependent template name if we can perform the lookup now and identify
5187 /// the named template.
5188 ///
5189 /// For example, given "x.MetaFun::template apply", the scope specifier
5190 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
5191 /// of the "template" keyword, and "apply" is the \p Name.
ActOnTemplateName(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const UnqualifiedId & Name,ParsedType ObjectType,bool EnteringContext,TemplateTy & Result,bool AllowInjectedClassName)5192 TemplateNameKind Sema::ActOnTemplateName(Scope *S,
5193                                          CXXScopeSpec &SS,
5194                                          SourceLocation TemplateKWLoc,
5195                                          const UnqualifiedId &Name,
5196                                          ParsedType ObjectType,
5197                                          bool EnteringContext,
5198                                          TemplateTy &Result,
5199                                          bool AllowInjectedClassName) {
5200   if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5201     Diag(TemplateKWLoc,
5202          getLangOpts().CPlusPlus11 ?
5203            diag::warn_cxx98_compat_template_outside_of_template :
5204            diag::ext_template_outside_of_template)
5205       << FixItHint::CreateRemoval(TemplateKWLoc);
5206 
5207   if (SS.isInvalid())
5208     return TNK_Non_template;
5209 
5210   // Figure out where isTemplateName is going to look.
5211   DeclContext *LookupCtx = nullptr;
5212   if (SS.isNotEmpty())
5213     LookupCtx = computeDeclContext(SS, EnteringContext);
5214   else if (ObjectType)
5215     LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5216 
5217   // C++0x [temp.names]p5:
5218   //   If a name prefixed by the keyword template is not the name of
5219   //   a template, the program is ill-formed. [Note: the keyword
5220   //   template may not be applied to non-template members of class
5221   //   templates. -end note ] [ Note: as is the case with the
5222   //   typename prefix, the template prefix is allowed in cases
5223   //   where it is not strictly necessary; i.e., when the
5224   //   nested-name-specifier or the expression on the left of the ->
5225   //   or . is not dependent on a template-parameter, or the use
5226   //   does not appear in the scope of a template. -end note]
5227   //
5228   // Note: C++03 was more strict here, because it banned the use of
5229   // the "template" keyword prior to a template-name that was not a
5230   // dependent name. C++ DR468 relaxed this requirement (the
5231   // "template" keyword is now permitted). We follow the C++0x
5232   // rules, even in C++03 mode with a warning, retroactively applying the DR.
5233   bool MemberOfUnknownSpecialization;
5234   TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5235                                         ObjectType, EnteringContext, Result,
5236                                         MemberOfUnknownSpecialization);
5237   if (TNK != TNK_Non_template) {
5238     // We resolved this to a (non-dependent) template name. Return it.
5239     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5240     if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5241         Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5242         Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5243       // C++14 [class.qual]p2:
5244       //   In a lookup in which function names are not ignored and the
5245       //   nested-name-specifier nominates a class C, if the name specified
5246       //   [...] is the injected-class-name of C, [...] the name is instead
5247       //   considered to name the constructor
5248       //
5249       // We don't get here if naming the constructor would be valid, so we
5250       // just reject immediately and recover by treating the
5251       // injected-class-name as naming the template.
5252       Diag(Name.getBeginLoc(),
5253            diag::ext_out_of_line_qualified_id_type_names_constructor)
5254           << Name.Identifier
5255           << 0 /*injected-class-name used as template name*/
5256           << TemplateKWLoc.isValid();
5257     }
5258     return TNK;
5259   }
5260 
5261   if (!MemberOfUnknownSpecialization) {
5262     // Didn't find a template name, and the lookup wasn't dependent.
5263     // Do the lookup again to determine if this is a "nothing found" case or
5264     // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5265     // need to do this.
5266     DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
5267     LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5268                    LookupOrdinaryName);
5269     bool MOUS;
5270     // Tell LookupTemplateName that we require a template so that it diagnoses
5271     // cases where it finds a non-template.
5272     RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5273                                    ? RequiredTemplateKind(TemplateKWLoc)
5274                                    : TemplateNameIsRequired;
5275     if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS,
5276                             RTK, nullptr, /*AllowTypoCorrection=*/false) &&
5277         !R.isAmbiguous()) {
5278       if (LookupCtx)
5279         Diag(Name.getBeginLoc(), diag::err_no_member)
5280             << DNI.getName() << LookupCtx << SS.getRange();
5281       else
5282         Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5283             << DNI.getName() << SS.getRange();
5284     }
5285     return TNK_Non_template;
5286   }
5287 
5288   NestedNameSpecifier *Qualifier = SS.getScopeRep();
5289 
5290   switch (Name.getKind()) {
5291   case UnqualifiedIdKind::IK_Identifier:
5292     Result = TemplateTy::make(
5293         Context.getDependentTemplateName(Qualifier, Name.Identifier));
5294     return TNK_Dependent_template_name;
5295 
5296   case UnqualifiedIdKind::IK_OperatorFunctionId:
5297     Result = TemplateTy::make(Context.getDependentTemplateName(
5298         Qualifier, Name.OperatorFunctionId.Operator));
5299     return TNK_Function_template;
5300 
5301   case UnqualifiedIdKind::IK_LiteralOperatorId:
5302     // This is a kind of template name, but can never occur in a dependent
5303     // scope (literal operators can only be declared at namespace scope).
5304     break;
5305 
5306   default:
5307     break;
5308   }
5309 
5310   // This name cannot possibly name a dependent template. Diagnose this now
5311   // rather than building a dependent template name that can never be valid.
5312   Diag(Name.getBeginLoc(),
5313        diag::err_template_kw_refers_to_dependent_non_template)
5314       << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5315       << TemplateKWLoc.isValid() << TemplateKWLoc;
5316   return TNK_Non_template;
5317 }
5318 
CheckTemplateTypeArgument(TemplateTypeParmDecl * Param,TemplateArgumentLoc & AL,SmallVectorImpl<TemplateArgument> & SugaredConverted,SmallVectorImpl<TemplateArgument> & CanonicalConverted)5319 bool Sema::CheckTemplateTypeArgument(
5320     TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
5321     SmallVectorImpl<TemplateArgument> &SugaredConverted,
5322     SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5323   const TemplateArgument &Arg = AL.getArgument();
5324   QualType ArgType;
5325   TypeSourceInfo *TSI = nullptr;
5326 
5327   // Check template type parameter.
5328   switch(Arg.getKind()) {
5329   case TemplateArgument::Type:
5330     // C++ [temp.arg.type]p1:
5331     //   A template-argument for a template-parameter which is a
5332     //   type shall be a type-id.
5333     ArgType = Arg.getAsType();
5334     TSI = AL.getTypeSourceInfo();
5335     break;
5336   case TemplateArgument::Template:
5337   case TemplateArgument::TemplateExpansion: {
5338     // We have a template type parameter but the template argument
5339     // is a template without any arguments.
5340     SourceRange SR = AL.getSourceRange();
5341     TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5342     diagnoseMissingTemplateArguments(Name, SR.getEnd());
5343     return true;
5344   }
5345   case TemplateArgument::Expression: {
5346     // We have a template type parameter but the template argument is an
5347     // expression; see if maybe it is missing the "typename" keyword.
5348     CXXScopeSpec SS;
5349     DeclarationNameInfo NameInfo;
5350 
5351    if (DependentScopeDeclRefExpr *ArgExpr =
5352                dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5353       SS.Adopt(ArgExpr->getQualifierLoc());
5354       NameInfo = ArgExpr->getNameInfo();
5355     } else if (CXXDependentScopeMemberExpr *ArgExpr =
5356                dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5357       if (ArgExpr->isImplicitAccess()) {
5358         SS.Adopt(ArgExpr->getQualifierLoc());
5359         NameInfo = ArgExpr->getMemberNameInfo();
5360       }
5361     }
5362 
5363     if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5364       LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5365       LookupParsedName(Result, CurScope, &SS);
5366 
5367       if (Result.getAsSingle<TypeDecl>() ||
5368           Result.getResultKind() ==
5369               LookupResult::NotFoundInCurrentInstantiation) {
5370         assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5371         // Suggest that the user add 'typename' before the NNS.
5372         SourceLocation Loc = AL.getSourceRange().getBegin();
5373         Diag(Loc, getLangOpts().MSVCCompat
5374                       ? diag::ext_ms_template_type_arg_missing_typename
5375                       : diag::err_template_arg_must_be_type_suggest)
5376             << FixItHint::CreateInsertion(Loc, "typename ");
5377         NoteTemplateParameterLocation(*Param);
5378 
5379         // Recover by synthesizing a type using the location information that we
5380         // already have.
5381         ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::Typename,
5382                                                SS.getScopeRep(), II);
5383         TypeLocBuilder TLB;
5384         DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
5385         TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5386         TL.setQualifierLoc(SS.getWithLocInContext(Context));
5387         TL.setNameLoc(NameInfo.getLoc());
5388         TSI = TLB.getTypeSourceInfo(Context, ArgType);
5389 
5390         // Overwrite our input TemplateArgumentLoc so that we can recover
5391         // properly.
5392         AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5393                                  TemplateArgumentLocInfo(TSI));
5394 
5395         break;
5396       }
5397     }
5398     // fallthrough
5399     [[fallthrough]];
5400   }
5401   default: {
5402     // We have a template type parameter but the template argument
5403     // is not a type.
5404     SourceRange SR = AL.getSourceRange();
5405     Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5406     NoteTemplateParameterLocation(*Param);
5407 
5408     return true;
5409   }
5410   }
5411 
5412   if (CheckTemplateArgument(TSI))
5413     return true;
5414 
5415   // Objective-C ARC:
5416   //   If an explicitly-specified template argument type is a lifetime type
5417   //   with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5418   if (getLangOpts().ObjCAutoRefCount &&
5419       ArgType->isObjCLifetimeType() &&
5420       !ArgType.getObjCLifetime()) {
5421     Qualifiers Qs;
5422     Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5423     ArgType = Context.getQualifiedType(ArgType, Qs);
5424   }
5425 
5426   SugaredConverted.push_back(TemplateArgument(ArgType));
5427   CanonicalConverted.push_back(
5428       TemplateArgument(Context.getCanonicalType(ArgType)));
5429   return false;
5430 }
5431 
5432 /// Substitute template arguments into the default template argument for
5433 /// the given template type parameter.
5434 ///
5435 /// \param SemaRef the semantic analysis object for which we are performing
5436 /// the substitution.
5437 ///
5438 /// \param Template the template that we are synthesizing template arguments
5439 /// for.
5440 ///
5441 /// \param TemplateLoc the location of the template name that started the
5442 /// template-id we are checking.
5443 ///
5444 /// \param RAngleLoc the location of the right angle bracket ('>') that
5445 /// terminates the template-id.
5446 ///
5447 /// \param Param the template template parameter whose default we are
5448 /// substituting into.
5449 ///
5450 /// \param Converted the list of template arguments provided for template
5451 /// parameters that precede \p Param in the template parameter list.
5452 /// \returns the substituted template argument, or NULL if an error occurred.
SubstDefaultTemplateArgument(Sema & SemaRef,TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,TemplateTypeParmDecl * Param,ArrayRef<TemplateArgument> SugaredConverted,ArrayRef<TemplateArgument> CanonicalConverted)5453 static TypeSourceInfo *SubstDefaultTemplateArgument(
5454     Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5455     SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5456     ArrayRef<TemplateArgument> SugaredConverted,
5457     ArrayRef<TemplateArgument> CanonicalConverted) {
5458   TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
5459 
5460   // If the argument type is dependent, instantiate it now based
5461   // on the previously-computed template arguments.
5462   if (ArgType->getType()->isInstantiationDependentType()) {
5463     Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5464                                      SugaredConverted,
5465                                      SourceRange(TemplateLoc, RAngleLoc));
5466     if (Inst.isInvalid())
5467       return nullptr;
5468 
5469     // Only substitute for the innermost template argument list.
5470     MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5471                                                     /*Final=*/true);
5472     for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5473       TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5474 
5475     bool ForLambdaCallOperator = false;
5476     if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5477       ForLambdaCallOperator = Rec->isLambda();
5478     Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5479                                    !ForLambdaCallOperator);
5480     ArgType =
5481         SemaRef.SubstType(ArgType, TemplateArgLists,
5482                           Param->getDefaultArgumentLoc(), Param->getDeclName());
5483   }
5484 
5485   return ArgType;
5486 }
5487 
5488 /// Substitute template arguments into the default template argument for
5489 /// the given non-type template parameter.
5490 ///
5491 /// \param SemaRef the semantic analysis object for which we are performing
5492 /// the substitution.
5493 ///
5494 /// \param Template the template that we are synthesizing template arguments
5495 /// for.
5496 ///
5497 /// \param TemplateLoc the location of the template name that started the
5498 /// template-id we are checking.
5499 ///
5500 /// \param RAngleLoc the location of the right angle bracket ('>') that
5501 /// terminates the template-id.
5502 ///
5503 /// \param Param the non-type template parameter whose default we are
5504 /// substituting into.
5505 ///
5506 /// \param Converted the list of template arguments provided for template
5507 /// parameters that precede \p Param in the template parameter list.
5508 ///
5509 /// \returns the substituted template argument, or NULL if an error occurred.
SubstDefaultTemplateArgument(Sema & SemaRef,TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,NonTypeTemplateParmDecl * Param,ArrayRef<TemplateArgument> SugaredConverted,ArrayRef<TemplateArgument> CanonicalConverted)5510 static ExprResult SubstDefaultTemplateArgument(
5511     Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5512     SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5513     ArrayRef<TemplateArgument> SugaredConverted,
5514     ArrayRef<TemplateArgument> CanonicalConverted) {
5515   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5516                                    SugaredConverted,
5517                                    SourceRange(TemplateLoc, RAngleLoc));
5518   if (Inst.isInvalid())
5519     return ExprError();
5520 
5521   // Only substitute for the innermost template argument list.
5522   MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5523                                                   /*Final=*/true);
5524   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5525     TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5526 
5527   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5528   EnterExpressionEvaluationContext ConstantEvaluated(
5529       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5530   return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
5531 }
5532 
5533 /// Substitute template arguments into the default template argument for
5534 /// the given template template parameter.
5535 ///
5536 /// \param SemaRef the semantic analysis object for which we are performing
5537 /// the substitution.
5538 ///
5539 /// \param Template the template that we are synthesizing template arguments
5540 /// for.
5541 ///
5542 /// \param TemplateLoc the location of the template name that started the
5543 /// template-id we are checking.
5544 ///
5545 /// \param RAngleLoc the location of the right angle bracket ('>') that
5546 /// terminates the template-id.
5547 ///
5548 /// \param Param the template template parameter whose default we are
5549 /// substituting into.
5550 ///
5551 /// \param Converted the list of template arguments provided for template
5552 /// parameters that precede \p Param in the template parameter list.
5553 ///
5554 /// \param QualifierLoc Will be set to the nested-name-specifier (with
5555 /// source-location information) that precedes the template name.
5556 ///
5557 /// \returns the substituted template argument, or NULL if an error occurred.
SubstDefaultTemplateArgument(Sema & SemaRef,TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,TemplateTemplateParmDecl * Param,ArrayRef<TemplateArgument> SugaredConverted,ArrayRef<TemplateArgument> CanonicalConverted,NestedNameSpecifierLoc & QualifierLoc)5558 static TemplateName SubstDefaultTemplateArgument(
5559     Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5560     SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
5561     ArrayRef<TemplateArgument> SugaredConverted,
5562     ArrayRef<TemplateArgument> CanonicalConverted,
5563     NestedNameSpecifierLoc &QualifierLoc) {
5564   Sema::InstantiatingTemplate Inst(
5565       SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5566       SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5567   if (Inst.isInvalid())
5568     return TemplateName();
5569 
5570   // Only substitute for the innermost template argument list.
5571   MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5572                                                   /*Final=*/true);
5573   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5574     TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5575 
5576   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5577   // Substitute into the nested-name-specifier first,
5578   QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5579   if (QualifierLoc) {
5580     QualifierLoc =
5581         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
5582     if (!QualifierLoc)
5583       return TemplateName();
5584   }
5585 
5586   return SemaRef.SubstTemplateName(
5587              QualifierLoc,
5588              Param->getDefaultArgument().getArgument().getAsTemplate(),
5589              Param->getDefaultArgument().getTemplateNameLoc(),
5590              TemplateArgLists);
5591 }
5592 
5593 /// If the given template parameter has a default template
5594 /// argument, substitute into that default template argument and
5595 /// return the corresponding template argument.
SubstDefaultTemplateArgumentIfAvailable(TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,Decl * Param,ArrayRef<TemplateArgument> SugaredConverted,ArrayRef<TemplateArgument> CanonicalConverted,bool & HasDefaultArg)5596 TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5597     TemplateDecl *Template, SourceLocation TemplateLoc,
5598     SourceLocation RAngleLoc, Decl *Param,
5599     ArrayRef<TemplateArgument> SugaredConverted,
5600     ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5601   HasDefaultArg = false;
5602 
5603   if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5604     if (!hasReachableDefaultArgument(TypeParm))
5605       return TemplateArgumentLoc();
5606 
5607     HasDefaultArg = true;
5608     TypeSourceInfo *DI = SubstDefaultTemplateArgument(
5609         *this, Template, TemplateLoc, RAngleLoc, TypeParm, SugaredConverted,
5610         CanonicalConverted);
5611     if (DI)
5612       return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
5613 
5614     return TemplateArgumentLoc();
5615   }
5616 
5617   if (NonTypeTemplateParmDecl *NonTypeParm
5618         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5619     if (!hasReachableDefaultArgument(NonTypeParm))
5620       return TemplateArgumentLoc();
5621 
5622     HasDefaultArg = true;
5623     ExprResult Arg = SubstDefaultTemplateArgument(
5624         *this, Template, TemplateLoc, RAngleLoc, NonTypeParm, SugaredConverted,
5625         CanonicalConverted);
5626     if (Arg.isInvalid())
5627       return TemplateArgumentLoc();
5628 
5629     Expr *ArgE = Arg.getAs<Expr>();
5630     return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
5631   }
5632 
5633   TemplateTemplateParmDecl *TempTempParm
5634     = cast<TemplateTemplateParmDecl>(Param);
5635   if (!hasReachableDefaultArgument(TempTempParm))
5636     return TemplateArgumentLoc();
5637 
5638   HasDefaultArg = true;
5639   NestedNameSpecifierLoc QualifierLoc;
5640   TemplateName TName = SubstDefaultTemplateArgument(
5641       *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
5642       CanonicalConverted, QualifierLoc);
5643   if (TName.isNull())
5644     return TemplateArgumentLoc();
5645 
5646   return TemplateArgumentLoc(
5647       Context, TemplateArgument(TName),
5648       TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
5649       TempTempParm->getDefaultArgument().getTemplateNameLoc());
5650 }
5651 
5652 /// Convert a template-argument that we parsed as a type into a template, if
5653 /// possible. C++ permits injected-class-names to perform dual service as
5654 /// template template arguments and as template type arguments.
5655 static TemplateArgumentLoc
convertTypeTemplateArgumentToTemplate(ASTContext & Context,TypeLoc TLoc)5656 convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5657   // Extract and step over any surrounding nested-name-specifier.
5658   NestedNameSpecifierLoc QualLoc;
5659   if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5660     if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
5661       return TemplateArgumentLoc();
5662 
5663     QualLoc = ETLoc.getQualifierLoc();
5664     TLoc = ETLoc.getNamedTypeLoc();
5665   }
5666   // If this type was written as an injected-class-name, it can be used as a
5667   // template template argument.
5668   if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5669     return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5670                                QualLoc, InjLoc.getNameLoc());
5671 
5672   // If this type was written as an injected-class-name, it may have been
5673   // converted to a RecordType during instantiation. If the RecordType is
5674   // *not* wrapped in a TemplateSpecializationType and denotes a class
5675   // template specialization, it must have come from an injected-class-name.
5676   if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5677     if (auto *CTSD =
5678             dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5679       return TemplateArgumentLoc(Context,
5680                                  TemplateName(CTSD->getSpecializedTemplate()),
5681                                  QualLoc, RecLoc.getNameLoc());
5682 
5683   return TemplateArgumentLoc();
5684 }
5685 
5686 /// Check that the given template argument corresponds to the given
5687 /// template parameter.
5688 ///
5689 /// \param Param The template parameter against which the argument will be
5690 /// checked.
5691 ///
5692 /// \param Arg The template argument, which may be updated due to conversions.
5693 ///
5694 /// \param Template The template in which the template argument resides.
5695 ///
5696 /// \param TemplateLoc The location of the template name for the template
5697 /// whose argument list we're matching.
5698 ///
5699 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
5700 /// the template argument list.
5701 ///
5702 /// \param ArgumentPackIndex The index into the argument pack where this
5703 /// argument will be placed. Only valid if the parameter is a parameter pack.
5704 ///
5705 /// \param Converted The checked, converted argument will be added to the
5706 /// end of this small vector.
5707 ///
5708 /// \param CTAK Describes how we arrived at this particular template argument:
5709 /// explicitly written, deduced, etc.
5710 ///
5711 /// \returns true on error, false otherwise.
CheckTemplateArgument(NamedDecl * Param,TemplateArgumentLoc & Arg,NamedDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,unsigned ArgumentPackIndex,SmallVectorImpl<TemplateArgument> & SugaredConverted,SmallVectorImpl<TemplateArgument> & CanonicalConverted,CheckTemplateArgumentKind CTAK)5712 bool Sema::CheckTemplateArgument(
5713     NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
5714     SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5715     unsigned ArgumentPackIndex,
5716     SmallVectorImpl<TemplateArgument> &SugaredConverted,
5717     SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5718     CheckTemplateArgumentKind CTAK) {
5719   // Check template type parameters.
5720   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5721     return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
5722                                      CanonicalConverted);
5723 
5724   // Check non-type template parameters.
5725   if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5726     // Do substitution on the type of the non-type template parameter
5727     // with the template arguments we've seen thus far.  But if the
5728     // template has a dependent context then we cannot substitute yet.
5729     QualType NTTPType = NTTP->getType();
5730     if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5731       NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5732 
5733     if (NTTPType->isInstantiationDependentType() &&
5734         !isa<TemplateTemplateParmDecl>(Template) &&
5735         !Template->getDeclContext()->isDependentContext()) {
5736       // Do substitution on the type of the non-type template parameter.
5737       InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5738                                  SugaredConverted,
5739                                  SourceRange(TemplateLoc, RAngleLoc));
5740       if (Inst.isInvalid())
5741         return true;
5742 
5743       MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
5744                                            /*Final=*/true);
5745       // If the parameter is a pack expansion, expand this slice of the pack.
5746       if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5747         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
5748                                                            ArgumentPackIndex);
5749         NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5750                              NTTP->getDeclName());
5751       } else {
5752         NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5753                              NTTP->getDeclName());
5754       }
5755 
5756       // If that worked, check the non-type template parameter type
5757       // for validity.
5758       if (!NTTPType.isNull())
5759         NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5760                                                      NTTP->getLocation());
5761       if (NTTPType.isNull())
5762         return true;
5763     }
5764 
5765     switch (Arg.getArgument().getKind()) {
5766     case TemplateArgument::Null:
5767       llvm_unreachable("Should never see a NULL template argument here");
5768 
5769     case TemplateArgument::Expression: {
5770       Expr *E = Arg.getArgument().getAsExpr();
5771       TemplateArgument SugaredResult, CanonicalResult;
5772       unsigned CurSFINAEErrors = NumSFINAEErrors;
5773       ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
5774                                              CanonicalResult, CTAK);
5775       if (Res.isInvalid())
5776         return true;
5777       // If the current template argument causes an error, give up now.
5778       if (CurSFINAEErrors < NumSFINAEErrors)
5779         return true;
5780 
5781       // If the resulting expression is new, then use it in place of the
5782       // old expression in the template argument.
5783       if (Res.get() != E) {
5784         TemplateArgument TA(Res.get());
5785         Arg = TemplateArgumentLoc(TA, Res.get());
5786       }
5787 
5788       SugaredConverted.push_back(SugaredResult);
5789       CanonicalConverted.push_back(CanonicalResult);
5790       break;
5791     }
5792 
5793     case TemplateArgument::Declaration:
5794     case TemplateArgument::Integral:
5795     case TemplateArgument::StructuralValue:
5796     case TemplateArgument::NullPtr:
5797       // We've already checked this template argument, so just copy
5798       // it to the list of converted arguments.
5799       SugaredConverted.push_back(Arg.getArgument());
5800       CanonicalConverted.push_back(
5801           Context.getCanonicalTemplateArgument(Arg.getArgument()));
5802       break;
5803 
5804     case TemplateArgument::Template:
5805     case TemplateArgument::TemplateExpansion:
5806       // We were given a template template argument. It may not be ill-formed;
5807       // see below.
5808       if (DependentTemplateName *DTN
5809             = Arg.getArgument().getAsTemplateOrTemplatePattern()
5810                                               .getAsDependentTemplateName()) {
5811         // We have a template argument such as \c T::template X, which we
5812         // parsed as a template template argument. However, since we now
5813         // know that we need a non-type template argument, convert this
5814         // template name into an expression.
5815 
5816         DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5817                                      Arg.getTemplateNameLoc());
5818 
5819         CXXScopeSpec SS;
5820         SS.Adopt(Arg.getTemplateQualifierLoc());
5821         // FIXME: the template-template arg was a DependentTemplateName,
5822         // so it was provided with a template keyword. However, its source
5823         // location is not stored in the template argument structure.
5824         SourceLocation TemplateKWLoc;
5825         ExprResult E = DependentScopeDeclRefExpr::Create(
5826             Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5827             nullptr);
5828 
5829         // If we parsed the template argument as a pack expansion, create a
5830         // pack expansion expression.
5831         if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
5832           E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5833           if (E.isInvalid())
5834             return true;
5835         }
5836 
5837         TemplateArgument SugaredResult, CanonicalResult;
5838         E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
5839                                   CanonicalResult, CTAK_Specified);
5840         if (E.isInvalid())
5841           return true;
5842 
5843         SugaredConverted.push_back(SugaredResult);
5844         CanonicalConverted.push_back(CanonicalResult);
5845         break;
5846       }
5847 
5848       // We have a template argument that actually does refer to a class
5849       // template, alias template, or template template parameter, and
5850       // therefore cannot be a non-type template argument.
5851       Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5852         << Arg.getSourceRange();
5853       NoteTemplateParameterLocation(*Param);
5854 
5855       return true;
5856 
5857     case TemplateArgument::Type: {
5858       // We have a non-type template parameter but the template
5859       // argument is a type.
5860 
5861       // C++ [temp.arg]p2:
5862       //   In a template-argument, an ambiguity between a type-id and
5863       //   an expression is resolved to a type-id, regardless of the
5864       //   form of the corresponding template-parameter.
5865       //
5866       // We warn specifically about this case, since it can be rather
5867       // confusing for users.
5868       QualType T = Arg.getArgument().getAsType();
5869       SourceRange SR = Arg.getSourceRange();
5870       if (T->isFunctionType())
5871         Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5872       else
5873         Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5874       NoteTemplateParameterLocation(*Param);
5875       return true;
5876     }
5877 
5878     case TemplateArgument::Pack:
5879       llvm_unreachable("Caller must expand template argument packs");
5880     }
5881 
5882     return false;
5883   }
5884 
5885 
5886   // Check template template parameters.
5887   TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5888 
5889   TemplateParameterList *Params = TempParm->getTemplateParameters();
5890   if (TempParm->isExpandedParameterPack())
5891     Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5892 
5893   // Substitute into the template parameter list of the template
5894   // template parameter, since previously-supplied template arguments
5895   // may appear within the template template parameter.
5896   //
5897   // FIXME: Skip this if the parameters aren't instantiation-dependent.
5898   {
5899     // Set up a template instantiation context.
5900     LocalInstantiationScope Scope(*this);
5901     InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5902                                SugaredConverted,
5903                                SourceRange(TemplateLoc, RAngleLoc));
5904     if (Inst.isInvalid())
5905       return true;
5906 
5907     Params =
5908         SubstTemplateParams(Params, CurContext,
5909                             MultiLevelTemplateArgumentList(
5910                                 Template, SugaredConverted, /*Final=*/true),
5911                             /*EvaluateConstraints=*/false);
5912     if (!Params)
5913       return true;
5914   }
5915 
5916   // C++1z [temp.local]p1: (DR1004)
5917   //   When [the injected-class-name] is used [...] as a template-argument for
5918   //   a template template-parameter [...] it refers to the class template
5919   //   itself.
5920   if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5921     TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5922         Context, Arg.getTypeSourceInfo()->getTypeLoc());
5923     if (!ConvertedArg.getArgument().isNull())
5924       Arg = ConvertedArg;
5925   }
5926 
5927   switch (Arg.getArgument().getKind()) {
5928   case TemplateArgument::Null:
5929     llvm_unreachable("Should never see a NULL template argument here");
5930 
5931   case TemplateArgument::Template:
5932   case TemplateArgument::TemplateExpansion:
5933     if (CheckTemplateTemplateArgument(TempParm, Params, Arg))
5934       return true;
5935 
5936     SugaredConverted.push_back(Arg.getArgument());
5937     CanonicalConverted.push_back(
5938         Context.getCanonicalTemplateArgument(Arg.getArgument()));
5939     break;
5940 
5941   case TemplateArgument::Expression:
5942   case TemplateArgument::Type:
5943     // We have a template template parameter but the template
5944     // argument does not refer to a template.
5945     Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5946       << getLangOpts().CPlusPlus11;
5947     return true;
5948 
5949   case TemplateArgument::Declaration:
5950   case TemplateArgument::Integral:
5951   case TemplateArgument::StructuralValue:
5952   case TemplateArgument::NullPtr:
5953     llvm_unreachable("non-type argument with template template parameter");
5954 
5955   case TemplateArgument::Pack:
5956     llvm_unreachable("Caller must expand template argument packs");
5957   }
5958 
5959   return false;
5960 }
5961 
5962 /// Diagnose a missing template argument.
5963 template<typename TemplateParmDecl>
diagnoseMissingArgument(Sema & S,SourceLocation Loc,TemplateDecl * TD,const TemplateParmDecl * D,TemplateArgumentListInfo & Args)5964 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5965                                     TemplateDecl *TD,
5966                                     const TemplateParmDecl *D,
5967                                     TemplateArgumentListInfo &Args) {
5968   // Dig out the most recent declaration of the template parameter; there may be
5969   // declarations of the template that are more recent than TD.
5970   D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5971                                  ->getTemplateParameters()
5972                                  ->getParam(D->getIndex()));
5973 
5974   // If there's a default argument that's not reachable, diagnose that we're
5975   // missing a module import.
5976   llvm::SmallVector<Module*, 8> Modules;
5977   if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5978     S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5979                             D->getDefaultArgumentLoc(), Modules,
5980                             Sema::MissingImportKind::DefaultArgument,
5981                             /*Recover*/true);
5982     return true;
5983   }
5984 
5985   // FIXME: If there's a more recent default argument that *is* visible,
5986   // diagnose that it was declared too late.
5987 
5988   TemplateParameterList *Params = TD->getTemplateParameters();
5989 
5990   S.Diag(Loc, diag::err_template_arg_list_different_arity)
5991     << /*not enough args*/0
5992     << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5993     << TD;
5994   S.NoteTemplateLocation(*TD, Params->getSourceRange());
5995   return true;
5996 }
5997 
5998 /// Check that the given template argument list is well-formed
5999 /// for specializing the given template.
CheckTemplateArgumentList(TemplateDecl * Template,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs,bool PartialTemplateArgs,SmallVectorImpl<TemplateArgument> & SugaredConverted,SmallVectorImpl<TemplateArgument> & CanonicalConverted,bool UpdateArgsWithConversions,bool * ConstraintsNotSatisfied)6000 bool Sema::CheckTemplateArgumentList(
6001     TemplateDecl *Template, SourceLocation TemplateLoc,
6002     TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
6003     SmallVectorImpl<TemplateArgument> &SugaredConverted,
6004     SmallVectorImpl<TemplateArgument> &CanonicalConverted,
6005     bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
6006 
6007   if (ConstraintsNotSatisfied)
6008     *ConstraintsNotSatisfied = false;
6009 
6010   // Make a copy of the template arguments for processing.  Only make the
6011   // changes at the end when successful in matching the arguments to the
6012   // template.
6013   TemplateArgumentListInfo NewArgs = TemplateArgs;
6014 
6015   TemplateParameterList *Params = GetTemplateParameterList(Template);
6016 
6017   SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
6018 
6019   // C++ [temp.arg]p1:
6020   //   [...] The type and form of each template-argument specified in
6021   //   a template-id shall match the type and form specified for the
6022   //   corresponding parameter declared by the template in its
6023   //   template-parameter-list.
6024   bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
6025   SmallVector<TemplateArgument, 2> SugaredArgumentPack;
6026   SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
6027   unsigned ArgIdx = 0, NumArgs = NewArgs.size();
6028   LocalInstantiationScope InstScope(*this, true);
6029   for (TemplateParameterList::iterator Param = Params->begin(),
6030                                        ParamEnd = Params->end();
6031        Param != ParamEnd; /* increment in loop */) {
6032     // If we have an expanded parameter pack, make sure we don't have too
6033     // many arguments.
6034     if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
6035       if (*Expansions == SugaredArgumentPack.size()) {
6036         // We're done with this parameter pack. Pack up its arguments and add
6037         // them to the list.
6038         SugaredConverted.push_back(
6039             TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6040         SugaredArgumentPack.clear();
6041 
6042         CanonicalConverted.push_back(
6043             TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6044         CanonicalArgumentPack.clear();
6045 
6046         // This argument is assigned to the next parameter.
6047         ++Param;
6048         continue;
6049       } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
6050         // Not enough arguments for this parameter pack.
6051         Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6052           << /*not enough args*/0
6053           << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
6054           << Template;
6055         NoteTemplateLocation(*Template, Params->getSourceRange());
6056         return true;
6057       }
6058     }
6059 
6060     if (ArgIdx < NumArgs) {
6061       // Check the template argument we were given.
6062       if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
6063                                 RAngleLoc, SugaredArgumentPack.size(),
6064                                 SugaredConverted, CanonicalConverted,
6065                                 CTAK_Specified))
6066         return true;
6067 
6068       CanonicalConverted.back().setIsDefaulted(
6069           clang::isSubstitutedDefaultArgument(
6070               Context, NewArgs[ArgIdx].getArgument(), *Param,
6071               CanonicalConverted, Params->getDepth()));
6072 
6073       bool PackExpansionIntoNonPack =
6074           NewArgs[ArgIdx].getArgument().isPackExpansion() &&
6075           (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
6076       if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) ||
6077                                        isa<ConceptDecl>(Template))) {
6078         // Core issue 1430: we have a pack expansion as an argument to an
6079         // alias template, and it's not part of a parameter pack. This
6080         // can't be canonicalized, so reject it now.
6081         // As for concepts - we cannot normalize constraints where this
6082         // situation exists.
6083         Diag(NewArgs[ArgIdx].getLocation(),
6084              diag::err_template_expansion_into_fixed_list)
6085           << (isa<ConceptDecl>(Template) ? 1 : 0)
6086           << NewArgs[ArgIdx].getSourceRange();
6087         NoteTemplateParameterLocation(**Param);
6088         return true;
6089       }
6090 
6091       // We're now done with this argument.
6092       ++ArgIdx;
6093 
6094       if ((*Param)->isTemplateParameterPack()) {
6095         // The template parameter was a template parameter pack, so take the
6096         // deduced argument and place it on the argument pack. Note that we
6097         // stay on the same template parameter so that we can deduce more
6098         // arguments.
6099         SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
6100         CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
6101       } else {
6102         // Move to the next template parameter.
6103         ++Param;
6104       }
6105 
6106       // If we just saw a pack expansion into a non-pack, then directly convert
6107       // the remaining arguments, because we don't know what parameters they'll
6108       // match up with.
6109       if (PackExpansionIntoNonPack) {
6110         if (!SugaredArgumentPack.empty()) {
6111           // If we were part way through filling in an expanded parameter pack,
6112           // fall back to just producing individual arguments.
6113           SugaredConverted.insert(SugaredConverted.end(),
6114                                   SugaredArgumentPack.begin(),
6115                                   SugaredArgumentPack.end());
6116           SugaredArgumentPack.clear();
6117 
6118           CanonicalConverted.insert(CanonicalConverted.end(),
6119                                     CanonicalArgumentPack.begin(),
6120                                     CanonicalArgumentPack.end());
6121           CanonicalArgumentPack.clear();
6122         }
6123 
6124         while (ArgIdx < NumArgs) {
6125           const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6126           SugaredConverted.push_back(Arg);
6127           CanonicalConverted.push_back(
6128               Context.getCanonicalTemplateArgument(Arg));
6129           ++ArgIdx;
6130         }
6131 
6132         return false;
6133       }
6134 
6135       continue;
6136     }
6137 
6138     // If we're checking a partial template argument list, we're done.
6139     if (PartialTemplateArgs) {
6140       if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6141         SugaredConverted.push_back(
6142             TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6143         CanonicalConverted.push_back(
6144             TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6145       }
6146       return false;
6147     }
6148 
6149     // If we have a template parameter pack with no more corresponding
6150     // arguments, just break out now and we'll fill in the argument pack below.
6151     if ((*Param)->isTemplateParameterPack()) {
6152       assert(!getExpandedPackSize(*Param) &&
6153              "Should have dealt with this already");
6154 
6155       // A non-expanded parameter pack before the end of the parameter list
6156       // only occurs for an ill-formed template parameter list, unless we've
6157       // got a partial argument list for a function template, so just bail out.
6158       if (Param + 1 != ParamEnd) {
6159         assert(
6160             (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6161             "Concept templates must have parameter packs at the end.");
6162         return true;
6163       }
6164 
6165       SugaredConverted.push_back(
6166           TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6167       SugaredArgumentPack.clear();
6168 
6169       CanonicalConverted.push_back(
6170           TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6171       CanonicalArgumentPack.clear();
6172 
6173       ++Param;
6174       continue;
6175     }
6176 
6177     // Check whether we have a default argument.
6178     TemplateArgumentLoc Arg;
6179 
6180     // Retrieve the default template argument from the template
6181     // parameter. For each kind of template parameter, we substitute the
6182     // template arguments provided thus far and any "outer" template arguments
6183     // (when the template parameter was part of a nested template) into
6184     // the default argument.
6185     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
6186       if (!hasReachableDefaultArgument(TTP))
6187         return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6188                                        NewArgs);
6189 
6190       TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(
6191           *this, Template, TemplateLoc, RAngleLoc, TTP, SugaredConverted,
6192           CanonicalConverted);
6193       if (!ArgType)
6194         return true;
6195 
6196       Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
6197                                 ArgType);
6198     } else if (NonTypeTemplateParmDecl *NTTP
6199                  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
6200       if (!hasReachableDefaultArgument(NTTP))
6201         return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6202                                        NewArgs);
6203 
6204       ExprResult E = SubstDefaultTemplateArgument(
6205           *this, Template, TemplateLoc, RAngleLoc, NTTP, SugaredConverted,
6206           CanonicalConverted);
6207       if (E.isInvalid())
6208         return true;
6209 
6210       Expr *Ex = E.getAs<Expr>();
6211       Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
6212     } else {
6213       TemplateTemplateParmDecl *TempParm
6214         = cast<TemplateTemplateParmDecl>(*Param);
6215 
6216       if (!hasReachableDefaultArgument(TempParm))
6217         return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
6218                                        NewArgs);
6219 
6220       NestedNameSpecifierLoc QualifierLoc;
6221       TemplateName Name = SubstDefaultTemplateArgument(
6222           *this, Template, TemplateLoc, RAngleLoc, TempParm, SugaredConverted,
6223           CanonicalConverted, QualifierLoc);
6224       if (Name.isNull())
6225         return true;
6226 
6227       Arg = TemplateArgumentLoc(
6228           Context, TemplateArgument(Name), QualifierLoc,
6229           TempParm->getDefaultArgument().getTemplateNameLoc());
6230     }
6231 
6232     // Introduce an instantiation record that describes where we are using
6233     // the default template argument. We're not actually instantiating a
6234     // template here, we just create this object to put a note into the
6235     // context stack.
6236     InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6237                                SugaredConverted,
6238                                SourceRange(TemplateLoc, RAngleLoc));
6239     if (Inst.isInvalid())
6240       return true;
6241 
6242     // Check the default template argument.
6243     if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6244                               SugaredConverted, CanonicalConverted,
6245                               CTAK_Specified))
6246       return true;
6247 
6248     CanonicalConverted.back().setIsDefaulted(true);
6249 
6250     // Core issue 150 (assumed resolution): if this is a template template
6251     // parameter, keep track of the default template arguments from the
6252     // template definition.
6253     if (isTemplateTemplateParameter)
6254       NewArgs.addArgument(Arg);
6255 
6256     // Move to the next template parameter and argument.
6257     ++Param;
6258     ++ArgIdx;
6259   }
6260 
6261   // If we're performing a partial argument substitution, allow any trailing
6262   // pack expansions; they might be empty. This can happen even if
6263   // PartialTemplateArgs is false (the list of arguments is complete but
6264   // still dependent).
6265   if (ArgIdx < NumArgs && CurrentInstantiationScope &&
6266       CurrentInstantiationScope->getPartiallySubstitutedPack()) {
6267     while (ArgIdx < NumArgs &&
6268            NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6269       const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6270       SugaredConverted.push_back(Arg);
6271       CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
6272     }
6273   }
6274 
6275   // If we have any leftover arguments, then there were too many arguments.
6276   // Complain and fail.
6277   if (ArgIdx < NumArgs) {
6278     Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6279         << /*too many args*/1
6280         << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
6281         << Template
6282         << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6283     NoteTemplateLocation(*Template, Params->getSourceRange());
6284     return true;
6285   }
6286 
6287   // No problems found with the new argument list, propagate changes back
6288   // to caller.
6289   if (UpdateArgsWithConversions)
6290     TemplateArgs = std::move(NewArgs);
6291 
6292   if (!PartialTemplateArgs) {
6293     TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
6294                                            CanonicalConverted);
6295     // Setup the context/ThisScope for the case where we are needing to
6296     // re-instantiate constraints outside of normal instantiation.
6297     DeclContext *NewContext = Template->getDeclContext();
6298 
6299     // If this template is in a template, make sure we extract the templated
6300     // decl.
6301     if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6302       NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6303     auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6304 
6305     Qualifiers ThisQuals;
6306     if (const auto *Method =
6307             dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6308       ThisQuals = Method->getMethodQualifiers();
6309 
6310     ContextRAII Context(*this, NewContext);
6311     CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
6312 
6313     MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6314         Template, NewContext, /*Final=*/false, &StackTemplateArgs,
6315         /*RelativeToPrimary=*/true,
6316         /*Pattern=*/nullptr,
6317         /*ForConceptInstantiation=*/true);
6318     if (EnsureTemplateArgumentListConstraints(
6319             Template, MLTAL,
6320             SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6321       if (ConstraintsNotSatisfied)
6322         *ConstraintsNotSatisfied = true;
6323       return true;
6324     }
6325   }
6326 
6327   return false;
6328 }
6329 
6330 namespace {
6331   class UnnamedLocalNoLinkageFinder
6332     : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6333   {
6334     Sema &S;
6335     SourceRange SR;
6336 
6337     typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6338 
6339   public:
UnnamedLocalNoLinkageFinder(Sema & S,SourceRange SR)6340     UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6341 
Visit(QualType T)6342     bool Visit(QualType T) {
6343       return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6344     }
6345 
6346 #define TYPE(Class, Parent) \
6347     bool Visit##Class##Type(const Class##Type *);
6348 #define ABSTRACT_TYPE(Class, Parent) \
6349     bool Visit##Class##Type(const Class##Type *) { return false; }
6350 #define NON_CANONICAL_TYPE(Class, Parent) \
6351     bool Visit##Class##Type(const Class##Type *) { return false; }
6352 #include "clang/AST/TypeNodes.inc"
6353 
6354     bool VisitTagDecl(const TagDecl *Tag);
6355     bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
6356   };
6357 } // end anonymous namespace
6358 
VisitBuiltinType(const BuiltinType *)6359 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6360   return false;
6361 }
6362 
VisitComplexType(const ComplexType * T)6363 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6364   return Visit(T->getElementType());
6365 }
6366 
VisitPointerType(const PointerType * T)6367 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6368   return Visit(T->getPointeeType());
6369 }
6370 
VisitBlockPointerType(const BlockPointerType * T)6371 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6372                                                     const BlockPointerType* T) {
6373   return Visit(T->getPointeeType());
6374 }
6375 
VisitLValueReferenceType(const LValueReferenceType * T)6376 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6377                                                 const LValueReferenceType* T) {
6378   return Visit(T->getPointeeType());
6379 }
6380 
VisitRValueReferenceType(const RValueReferenceType * T)6381 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6382                                                 const RValueReferenceType* T) {
6383   return Visit(T->getPointeeType());
6384 }
6385 
VisitMemberPointerType(const MemberPointerType * T)6386 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6387                                                   const MemberPointerType* T) {
6388   return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
6389 }
6390 
VisitConstantArrayType(const ConstantArrayType * T)6391 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6392                                                   const ConstantArrayType* T) {
6393   return Visit(T->getElementType());
6394 }
6395 
VisitIncompleteArrayType(const IncompleteArrayType * T)6396 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6397                                                  const IncompleteArrayType* T) {
6398   return Visit(T->getElementType());
6399 }
6400 
VisitVariableArrayType(const VariableArrayType * T)6401 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6402                                                    const VariableArrayType* T) {
6403   return Visit(T->getElementType());
6404 }
6405 
VisitDependentSizedArrayType(const DependentSizedArrayType * T)6406 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6407                                             const DependentSizedArrayType* T) {
6408   return Visit(T->getElementType());
6409 }
6410 
VisitDependentSizedExtVectorType(const DependentSizedExtVectorType * T)6411 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6412                                          const DependentSizedExtVectorType* T) {
6413   return Visit(T->getElementType());
6414 }
6415 
VisitDependentSizedMatrixType(const DependentSizedMatrixType * T)6416 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6417     const DependentSizedMatrixType *T) {
6418   return Visit(T->getElementType());
6419 }
6420 
VisitDependentAddressSpaceType(const DependentAddressSpaceType * T)6421 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6422     const DependentAddressSpaceType *T) {
6423   return Visit(T->getPointeeType());
6424 }
6425 
VisitVectorType(const VectorType * T)6426 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6427   return Visit(T->getElementType());
6428 }
6429 
VisitDependentVectorType(const DependentVectorType * T)6430 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6431     const DependentVectorType *T) {
6432   return Visit(T->getElementType());
6433 }
6434 
VisitExtVectorType(const ExtVectorType * T)6435 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6436   return Visit(T->getElementType());
6437 }
6438 
VisitConstantMatrixType(const ConstantMatrixType * T)6439 bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6440     const ConstantMatrixType *T) {
6441   return Visit(T->getElementType());
6442 }
6443 
VisitFunctionProtoType(const FunctionProtoType * T)6444 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6445                                                   const FunctionProtoType* T) {
6446   for (const auto &A : T->param_types()) {
6447     if (Visit(A))
6448       return true;
6449   }
6450 
6451   return Visit(T->getReturnType());
6452 }
6453 
VisitFunctionNoProtoType(const FunctionNoProtoType * T)6454 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6455                                                const FunctionNoProtoType* T) {
6456   return Visit(T->getReturnType());
6457 }
6458 
VisitUnresolvedUsingType(const UnresolvedUsingType *)6459 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6460                                                   const UnresolvedUsingType*) {
6461   return false;
6462 }
6463 
VisitTypeOfExprType(const TypeOfExprType *)6464 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6465   return false;
6466 }
6467 
VisitTypeOfType(const TypeOfType * T)6468 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6469   return Visit(T->getUnmodifiedType());
6470 }
6471 
VisitDecltypeType(const DecltypeType *)6472 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6473   return false;
6474 }
6475 
VisitUnaryTransformType(const UnaryTransformType *)6476 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6477                                                     const UnaryTransformType*) {
6478   return false;
6479 }
6480 
VisitAutoType(const AutoType * T)6481 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6482   return Visit(T->getDeducedType());
6483 }
6484 
VisitDeducedTemplateSpecializationType(const DeducedTemplateSpecializationType * T)6485 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6486     const DeducedTemplateSpecializationType *T) {
6487   return Visit(T->getDeducedType());
6488 }
6489 
VisitRecordType(const RecordType * T)6490 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6491   return VisitTagDecl(T->getDecl());
6492 }
6493 
VisitEnumType(const EnumType * T)6494 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6495   return VisitTagDecl(T->getDecl());
6496 }
6497 
VisitTemplateTypeParmType(const TemplateTypeParmType *)6498 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6499                                                  const TemplateTypeParmType*) {
6500   return false;
6501 }
6502 
VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *)6503 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6504                                         const SubstTemplateTypeParmPackType *) {
6505   return false;
6506 }
6507 
VisitTemplateSpecializationType(const TemplateSpecializationType *)6508 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6509                                             const TemplateSpecializationType*) {
6510   return false;
6511 }
6512 
VisitInjectedClassNameType(const InjectedClassNameType * T)6513 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6514                                               const InjectedClassNameType* T) {
6515   return VisitTagDecl(T->getDecl());
6516 }
6517 
VisitDependentNameType(const DependentNameType * T)6518 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6519                                                    const DependentNameType* T) {
6520   return VisitNestedNameSpecifier(T->getQualifier());
6521 }
6522 
VisitDependentTemplateSpecializationType(const DependentTemplateSpecializationType * T)6523 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6524                                  const DependentTemplateSpecializationType* T) {
6525   if (auto *Q = T->getQualifier())
6526     return VisitNestedNameSpecifier(Q);
6527   return false;
6528 }
6529 
VisitPackExpansionType(const PackExpansionType * T)6530 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6531                                                    const PackExpansionType* T) {
6532   return Visit(T->getPattern());
6533 }
6534 
VisitObjCObjectType(const ObjCObjectType *)6535 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6536   return false;
6537 }
6538 
VisitObjCInterfaceType(const ObjCInterfaceType *)6539 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6540                                                    const ObjCInterfaceType *) {
6541   return false;
6542 }
6543 
VisitObjCObjectPointerType(const ObjCObjectPointerType *)6544 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6545                                                 const ObjCObjectPointerType *) {
6546   return false;
6547 }
6548 
VisitAtomicType(const AtomicType * T)6549 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6550   return Visit(T->getValueType());
6551 }
6552 
VisitPipeType(const PipeType * T)6553 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6554   return false;
6555 }
6556 
VisitBitIntType(const BitIntType * T)6557 bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6558   return false;
6559 }
6560 
VisitDependentBitIntType(const DependentBitIntType * T)6561 bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6562     const DependentBitIntType *T) {
6563   return false;
6564 }
6565 
VisitTagDecl(const TagDecl * Tag)6566 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6567   if (Tag->getDeclContext()->isFunctionOrMethod()) {
6568     S.Diag(SR.getBegin(),
6569            S.getLangOpts().CPlusPlus11 ?
6570              diag::warn_cxx98_compat_template_arg_local_type :
6571              diag::ext_template_arg_local_type)
6572       << S.Context.getTypeDeclType(Tag) << SR;
6573     return true;
6574   }
6575 
6576   if (!Tag->hasNameForLinkage()) {
6577     S.Diag(SR.getBegin(),
6578            S.getLangOpts().CPlusPlus11 ?
6579              diag::warn_cxx98_compat_template_arg_unnamed_type :
6580              diag::ext_template_arg_unnamed_type) << SR;
6581     S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6582     return true;
6583   }
6584 
6585   return false;
6586 }
6587 
VisitNestedNameSpecifier(NestedNameSpecifier * NNS)6588 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6589                                                     NestedNameSpecifier *NNS) {
6590   assert(NNS);
6591   if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
6592     return true;
6593 
6594   switch (NNS->getKind()) {
6595   case NestedNameSpecifier::Identifier:
6596   case NestedNameSpecifier::Namespace:
6597   case NestedNameSpecifier::NamespaceAlias:
6598   case NestedNameSpecifier::Global:
6599   case NestedNameSpecifier::Super:
6600     return false;
6601 
6602   case NestedNameSpecifier::TypeSpec:
6603   case NestedNameSpecifier::TypeSpecWithTemplate:
6604     return Visit(QualType(NNS->getAsType(), 0));
6605   }
6606   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6607 }
6608 
6609 /// Check a template argument against its corresponding
6610 /// template type parameter.
6611 ///
6612 /// This routine implements the semantics of C++ [temp.arg.type]. It
6613 /// returns true if an error occurred, and false otherwise.
CheckTemplateArgument(TypeSourceInfo * ArgInfo)6614 bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6615   assert(ArgInfo && "invalid TypeSourceInfo");
6616   QualType Arg = ArgInfo->getType();
6617   SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6618   QualType CanonArg = Context.getCanonicalType(Arg);
6619 
6620   if (CanonArg->isVariablyModifiedType()) {
6621     return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6622   } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6623     return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6624   }
6625 
6626   // C++03 [temp.arg.type]p2:
6627   //   A local type, a type with no linkage, an unnamed type or a type
6628   //   compounded from any of these types shall not be used as a
6629   //   template-argument for a template type-parameter.
6630   //
6631   // C++11 allows these, and even in C++03 we allow them as an extension with
6632   // a warning.
6633   if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6634     UnnamedLocalNoLinkageFinder Finder(*this, SR);
6635     (void)Finder.Visit(CanonArg);
6636   }
6637 
6638   return false;
6639 }
6640 
6641 enum NullPointerValueKind {
6642   NPV_NotNullPointer,
6643   NPV_NullPointer,
6644   NPV_Error
6645 };
6646 
6647 /// Determine whether the given template argument is a null pointer
6648 /// value of the appropriate type.
6649 static NullPointerValueKind
isNullPointerValueTemplateArgument(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * Arg,Decl * Entity=nullptr)6650 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
6651                                    QualType ParamType, Expr *Arg,
6652                                    Decl *Entity = nullptr) {
6653   if (Arg->isValueDependent() || Arg->isTypeDependent())
6654     return NPV_NotNullPointer;
6655 
6656   // dllimport'd entities aren't constant but are available inside of template
6657   // arguments.
6658   if (Entity && Entity->hasAttr<DLLImportAttr>())
6659     return NPV_NotNullPointer;
6660 
6661   if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6662     llvm_unreachable(
6663         "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6664 
6665   if (!S.getLangOpts().CPlusPlus11)
6666     return NPV_NotNullPointer;
6667 
6668   // Determine whether we have a constant expression.
6669   ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
6670   if (ArgRV.isInvalid())
6671     return NPV_Error;
6672   Arg = ArgRV.get();
6673 
6674   Expr::EvalResult EvalResult;
6675   SmallVector<PartialDiagnosticAt, 8> Notes;
6676   EvalResult.Diag = &Notes;
6677   if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6678       EvalResult.HasSideEffects) {
6679     SourceLocation DiagLoc = Arg->getExprLoc();
6680 
6681     // If our only note is the usual "invalid subexpression" note, just point
6682     // the caret at its location rather than producing an essentially
6683     // redundant note.
6684     if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6685         diag::note_invalid_subexpr_in_const_expr) {
6686       DiagLoc = Notes[0].first;
6687       Notes.clear();
6688     }
6689 
6690     S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6691       << Arg->getType() << Arg->getSourceRange();
6692     for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6693       S.Diag(Notes[I].first, Notes[I].second);
6694 
6695     S.NoteTemplateParameterLocation(*Param);
6696     return NPV_Error;
6697   }
6698 
6699   // C++11 [temp.arg.nontype]p1:
6700   //   - an address constant expression of type std::nullptr_t
6701   if (Arg->getType()->isNullPtrType())
6702     return NPV_NullPointer;
6703 
6704   //   - a constant expression that evaluates to a null pointer value (4.10); or
6705   //   - a constant expression that evaluates to a null member pointer value
6706   //     (4.11); or
6707   if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6708       (EvalResult.Val.isMemberPointer() &&
6709        !EvalResult.Val.getMemberPointerDecl())) {
6710     // If our expression has an appropriate type, we've succeeded.
6711     bool ObjCLifetimeConversion;
6712     if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6713         S.IsQualificationConversion(Arg->getType(), ParamType, false,
6714                                      ObjCLifetimeConversion))
6715       return NPV_NullPointer;
6716 
6717     // The types didn't match, but we know we got a null pointer; complain,
6718     // then recover as if the types were correct.
6719     S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6720       << Arg->getType() << ParamType << Arg->getSourceRange();
6721     S.NoteTemplateParameterLocation(*Param);
6722     return NPV_NullPointer;
6723   }
6724 
6725   if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6726     // We found a pointer that isn't null, but doesn't refer to an object.
6727     // We could just return NPV_NotNullPointer, but we can print a better
6728     // message with the information we have here.
6729     S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6730       << EvalResult.Val.getAsString(S.Context, ParamType);
6731     S.NoteTemplateParameterLocation(*Param);
6732     return NPV_Error;
6733   }
6734 
6735   // If we don't have a null pointer value, but we do have a NULL pointer
6736   // constant, suggest a cast to the appropriate type.
6737   if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
6738     std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6739     S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6740         << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6741         << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
6742                                       ")");
6743     S.NoteTemplateParameterLocation(*Param);
6744     return NPV_NullPointer;
6745   }
6746 
6747   // FIXME: If we ever want to support general, address-constant expressions
6748   // as non-type template arguments, we should return the ExprResult here to
6749   // be interpreted by the caller.
6750   return NPV_NotNullPointer;
6751 }
6752 
6753 /// Checks whether the given template argument is compatible with its
6754 /// template parameter.
CheckTemplateArgumentIsCompatibleWithParameter(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * ArgIn,Expr * Arg,QualType ArgType)6755 static bool CheckTemplateArgumentIsCompatibleWithParameter(
6756     Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6757     Expr *Arg, QualType ArgType) {
6758   bool ObjCLifetimeConversion;
6759   if (ParamType->isPointerType() &&
6760       !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6761       S.IsQualificationConversion(ArgType, ParamType, false,
6762                                   ObjCLifetimeConversion)) {
6763     // For pointer-to-object types, qualification conversions are
6764     // permitted.
6765   } else {
6766     if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6767       if (!ParamRef->getPointeeType()->isFunctionType()) {
6768         // C++ [temp.arg.nontype]p5b3:
6769         //   For a non-type template-parameter of type reference to
6770         //   object, no conversions apply. The type referred to by the
6771         //   reference may be more cv-qualified than the (otherwise
6772         //   identical) type of the template- argument. The
6773         //   template-parameter is bound directly to the
6774         //   template-argument, which shall be an lvalue.
6775 
6776         // FIXME: Other qualifiers?
6777         unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6778         unsigned ArgQuals = ArgType.getCVRQualifiers();
6779 
6780         if ((ParamQuals | ArgQuals) != ParamQuals) {
6781           S.Diag(Arg->getBeginLoc(),
6782                  diag::err_template_arg_ref_bind_ignores_quals)
6783               << ParamType << Arg->getType() << Arg->getSourceRange();
6784           S.NoteTemplateParameterLocation(*Param);
6785           return true;
6786         }
6787       }
6788     }
6789 
6790     // At this point, the template argument refers to an object or
6791     // function with external linkage. We now need to check whether the
6792     // argument and parameter types are compatible.
6793     if (!S.Context.hasSameUnqualifiedType(ArgType,
6794                                           ParamType.getNonReferenceType())) {
6795       // We can't perform this conversion or binding.
6796       if (ParamType->isReferenceType())
6797         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6798             << ParamType << ArgIn->getType() << Arg->getSourceRange();
6799       else
6800         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6801             << ArgIn->getType() << ParamType << Arg->getSourceRange();
6802       S.NoteTemplateParameterLocation(*Param);
6803       return true;
6804     }
6805   }
6806 
6807   return false;
6808 }
6809 
6810 /// Checks whether the given template argument is the address
6811 /// of an object or function according to C++ [temp.arg.nontype]p1.
CheckTemplateArgumentAddressOfObjectOrFunction(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * ArgIn,TemplateArgument & SugaredConverted,TemplateArgument & CanonicalConverted)6812 static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6813     Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6814     TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6815   bool Invalid = false;
6816   Expr *Arg = ArgIn;
6817   QualType ArgType = Arg->getType();
6818 
6819   bool AddressTaken = false;
6820   SourceLocation AddrOpLoc;
6821   if (S.getLangOpts().MicrosoftExt) {
6822     // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6823     // dereference and address-of operators.
6824     Arg = Arg->IgnoreParenCasts();
6825 
6826     bool ExtWarnMSTemplateArg = false;
6827     UnaryOperatorKind FirstOpKind;
6828     SourceLocation FirstOpLoc;
6829     while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6830       UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6831       if (UnOpKind == UO_Deref)
6832         ExtWarnMSTemplateArg = true;
6833       if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6834         Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6835         if (!AddrOpLoc.isValid()) {
6836           FirstOpKind = UnOpKind;
6837           FirstOpLoc = UnOp->getOperatorLoc();
6838         }
6839       } else
6840         break;
6841     }
6842     if (FirstOpLoc.isValid()) {
6843       if (ExtWarnMSTemplateArg)
6844         S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6845             << ArgIn->getSourceRange();
6846 
6847       if (FirstOpKind == UO_AddrOf)
6848         AddressTaken = true;
6849       else if (Arg->getType()->isPointerType()) {
6850         // We cannot let pointers get dereferenced here, that is obviously not a
6851         // constant expression.
6852         assert(FirstOpKind == UO_Deref);
6853         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6854             << Arg->getSourceRange();
6855       }
6856     }
6857   } else {
6858     // See through any implicit casts we added to fix the type.
6859     Arg = Arg->IgnoreImpCasts();
6860 
6861     // C++ [temp.arg.nontype]p1:
6862     //
6863     //   A template-argument for a non-type, non-template
6864     //   template-parameter shall be one of: [...]
6865     //
6866     //     -- the address of an object or function with external
6867     //        linkage, including function templates and function
6868     //        template-ids but excluding non-static class members,
6869     //        expressed as & id-expression where the & is optional if
6870     //        the name refers to a function or array, or if the
6871     //        corresponding template-parameter is a reference; or
6872 
6873     // In C++98/03 mode, give an extension warning on any extra parentheses.
6874     // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6875     bool ExtraParens = false;
6876     while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6877       if (!Invalid && !ExtraParens) {
6878         S.Diag(Arg->getBeginLoc(),
6879                S.getLangOpts().CPlusPlus11
6880                    ? diag::warn_cxx98_compat_template_arg_extra_parens
6881                    : diag::ext_template_arg_extra_parens)
6882             << Arg->getSourceRange();
6883         ExtraParens = true;
6884       }
6885 
6886       Arg = Parens->getSubExpr();
6887     }
6888 
6889     while (SubstNonTypeTemplateParmExpr *subst =
6890                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6891       Arg = subst->getReplacement()->IgnoreImpCasts();
6892 
6893     if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6894       if (UnOp->getOpcode() == UO_AddrOf) {
6895         Arg = UnOp->getSubExpr();
6896         AddressTaken = true;
6897         AddrOpLoc = UnOp->getOperatorLoc();
6898       }
6899     }
6900 
6901     while (SubstNonTypeTemplateParmExpr *subst =
6902                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6903       Arg = subst->getReplacement()->IgnoreImpCasts();
6904   }
6905 
6906   ValueDecl *Entity = nullptr;
6907   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6908     Entity = DRE->getDecl();
6909   else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6910     Entity = CUE->getGuidDecl();
6911 
6912   // If our parameter has pointer type, check for a null template value.
6913   if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6914     switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6915                                                Entity)) {
6916     case NPV_NullPointer:
6917       S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6918       SugaredConverted = TemplateArgument(ParamType,
6919                                           /*isNullPtr=*/true);
6920       CanonicalConverted =
6921           TemplateArgument(S.Context.getCanonicalType(ParamType),
6922                            /*isNullPtr=*/true);
6923       return false;
6924 
6925     case NPV_Error:
6926       return true;
6927 
6928     case NPV_NotNullPointer:
6929       break;
6930     }
6931   }
6932 
6933   // Stop checking the precise nature of the argument if it is value dependent,
6934   // it should be checked when instantiated.
6935   if (Arg->isValueDependent()) {
6936     SugaredConverted = TemplateArgument(ArgIn);
6937     CanonicalConverted =
6938         S.Context.getCanonicalTemplateArgument(SugaredConverted);
6939     return false;
6940   }
6941 
6942   if (!Entity) {
6943     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6944         << Arg->getSourceRange();
6945     S.NoteTemplateParameterLocation(*Param);
6946     return true;
6947   }
6948 
6949   // Cannot refer to non-static data members
6950   if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6951     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6952         << Entity << Arg->getSourceRange();
6953     S.NoteTemplateParameterLocation(*Param);
6954     return true;
6955   }
6956 
6957   // Cannot refer to non-static member functions
6958   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6959     if (!Method->isStatic()) {
6960       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6961           << Method << Arg->getSourceRange();
6962       S.NoteTemplateParameterLocation(*Param);
6963       return true;
6964     }
6965   }
6966 
6967   FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6968   VarDecl *Var = dyn_cast<VarDecl>(Entity);
6969   MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6970 
6971   // A non-type template argument must refer to an object or function.
6972   if (!Func && !Var && !Guid) {
6973     // We found something, but we don't know specifically what it is.
6974     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6975         << Arg->getSourceRange();
6976     S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6977     return true;
6978   }
6979 
6980   // Address / reference template args must have external linkage in C++98.
6981   if (Entity->getFormalLinkage() == Linkage::Internal) {
6982     S.Diag(Arg->getBeginLoc(),
6983            S.getLangOpts().CPlusPlus11
6984                ? diag::warn_cxx98_compat_template_arg_object_internal
6985                : diag::ext_template_arg_object_internal)
6986         << !Func << Entity << Arg->getSourceRange();
6987     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6988       << !Func;
6989   } else if (!Entity->hasLinkage()) {
6990     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6991         << !Func << Entity << Arg->getSourceRange();
6992     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6993       << !Func;
6994     return true;
6995   }
6996 
6997   if (Var) {
6998     // A value of reference type is not an object.
6999     if (Var->getType()->isReferenceType()) {
7000       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
7001           << Var->getType() << Arg->getSourceRange();
7002       S.NoteTemplateParameterLocation(*Param);
7003       return true;
7004     }
7005 
7006     // A template argument must have static storage duration.
7007     if (Var->getTLSKind()) {
7008       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
7009           << Arg->getSourceRange();
7010       S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
7011       return true;
7012     }
7013   }
7014 
7015   if (AddressTaken && ParamType->isReferenceType()) {
7016     // If we originally had an address-of operator, but the
7017     // parameter has reference type, complain and (if things look
7018     // like they will work) drop the address-of operator.
7019     if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
7020                                           ParamType.getNonReferenceType())) {
7021       S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7022         << ParamType;
7023       S.NoteTemplateParameterLocation(*Param);
7024       return true;
7025     }
7026 
7027     S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7028       << ParamType
7029       << FixItHint::CreateRemoval(AddrOpLoc);
7030     S.NoteTemplateParameterLocation(*Param);
7031 
7032     ArgType = Entity->getType();
7033   }
7034 
7035   // If the template parameter has pointer type, either we must have taken the
7036   // address or the argument must decay to a pointer.
7037   if (!AddressTaken && ParamType->isPointerType()) {
7038     if (Func) {
7039       // Function-to-pointer decay.
7040       ArgType = S.Context.getPointerType(Func->getType());
7041     } else if (Entity->getType()->isArrayType()) {
7042       // Array-to-pointer decay.
7043       ArgType = S.Context.getArrayDecayedType(Entity->getType());
7044     } else {
7045       // If the template parameter has pointer type but the address of
7046       // this object was not taken, complain and (possibly) recover by
7047       // taking the address of the entity.
7048       ArgType = S.Context.getPointerType(Entity->getType());
7049       if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
7050         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7051           << ParamType;
7052         S.NoteTemplateParameterLocation(*Param);
7053         return true;
7054       }
7055 
7056       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7057         << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
7058 
7059       S.NoteTemplateParameterLocation(*Param);
7060     }
7061   }
7062 
7063   if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7064                                                      Arg, ArgType))
7065     return true;
7066 
7067   // Create the template argument.
7068   SugaredConverted = TemplateArgument(Entity, ParamType);
7069   CanonicalConverted =
7070       TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
7071                        S.Context.getCanonicalType(ParamType));
7072   S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
7073   return false;
7074 }
7075 
7076 /// Checks whether the given template argument is a pointer to
7077 /// member constant according to C++ [temp.arg.nontype]p1.
7078 static bool
CheckTemplateArgumentPointerToMember(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * & ResultArg,TemplateArgument & SugaredConverted,TemplateArgument & CanonicalConverted)7079 CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param,
7080                                      QualType ParamType, Expr *&ResultArg,
7081                                      TemplateArgument &SugaredConverted,
7082                                      TemplateArgument &CanonicalConverted) {
7083   bool Invalid = false;
7084 
7085   Expr *Arg = ResultArg;
7086   bool ObjCLifetimeConversion;
7087 
7088   // C++ [temp.arg.nontype]p1:
7089   //
7090   //   A template-argument for a non-type, non-template
7091   //   template-parameter shall be one of: [...]
7092   //
7093   //     -- a pointer to member expressed as described in 5.3.1.
7094   DeclRefExpr *DRE = nullptr;
7095 
7096   // In C++98/03 mode, give an extension warning on any extra parentheses.
7097   // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7098   bool ExtraParens = false;
7099   while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7100     if (!Invalid && !ExtraParens) {
7101       S.Diag(Arg->getBeginLoc(),
7102              S.getLangOpts().CPlusPlus11
7103                  ? diag::warn_cxx98_compat_template_arg_extra_parens
7104                  : diag::ext_template_arg_extra_parens)
7105           << Arg->getSourceRange();
7106       ExtraParens = true;
7107     }
7108 
7109     Arg = Parens->getSubExpr();
7110   }
7111 
7112   while (SubstNonTypeTemplateParmExpr *subst =
7113            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7114     Arg = subst->getReplacement()->IgnoreImpCasts();
7115 
7116   // A pointer-to-member constant written &Class::member.
7117   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7118     if (UnOp->getOpcode() == UO_AddrOf) {
7119       DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7120       if (DRE && !DRE->getQualifier())
7121         DRE = nullptr;
7122     }
7123   }
7124   // A constant of pointer-to-member type.
7125   else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7126     ValueDecl *VD = DRE->getDecl();
7127     if (VD->getType()->isMemberPointerType()) {
7128       if (isa<NonTypeTemplateParmDecl>(VD)) {
7129         if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7130           SugaredConverted = TemplateArgument(Arg);
7131           CanonicalConverted =
7132               S.Context.getCanonicalTemplateArgument(SugaredConverted);
7133         } else {
7134           SugaredConverted = TemplateArgument(VD, ParamType);
7135           CanonicalConverted =
7136               TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7137                                S.Context.getCanonicalType(ParamType));
7138         }
7139         return Invalid;
7140       }
7141     }
7142 
7143     DRE = nullptr;
7144   }
7145 
7146   ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7147 
7148   // Check for a null pointer value.
7149   switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7150                                              Entity)) {
7151   case NPV_Error:
7152     return true;
7153   case NPV_NullPointer:
7154     S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7155     SugaredConverted = TemplateArgument(ParamType,
7156                                         /*isNullPtr*/ true);
7157     CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7158                                           /*isNullPtr*/ true);
7159     return false;
7160   case NPV_NotNullPointer:
7161     break;
7162   }
7163 
7164   if (S.IsQualificationConversion(ResultArg->getType(),
7165                                   ParamType.getNonReferenceType(), false,
7166                                   ObjCLifetimeConversion)) {
7167     ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7168                                     ResultArg->getValueKind())
7169                     .get();
7170   } else if (!S.Context.hasSameUnqualifiedType(
7171                  ResultArg->getType(), ParamType.getNonReferenceType())) {
7172     // We can't perform this conversion.
7173     S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7174         << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7175     S.NoteTemplateParameterLocation(*Param);
7176     return true;
7177   }
7178 
7179   if (!DRE)
7180     return S.Diag(Arg->getBeginLoc(),
7181                   diag::err_template_arg_not_pointer_to_member_form)
7182            << Arg->getSourceRange();
7183 
7184   if (isa<FieldDecl>(DRE->getDecl()) ||
7185       isa<IndirectFieldDecl>(DRE->getDecl()) ||
7186       isa<CXXMethodDecl>(DRE->getDecl())) {
7187     assert((isa<FieldDecl>(DRE->getDecl()) ||
7188             isa<IndirectFieldDecl>(DRE->getDecl()) ||
7189             cast<CXXMethodDecl>(DRE->getDecl())
7190                 ->isImplicitObjectMemberFunction()) &&
7191            "Only non-static member pointers can make it here");
7192 
7193     // Okay: this is the address of a non-static member, and therefore
7194     // a member pointer constant.
7195     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7196       SugaredConverted = TemplateArgument(Arg);
7197       CanonicalConverted =
7198           S.Context.getCanonicalTemplateArgument(SugaredConverted);
7199     } else {
7200       ValueDecl *D = DRE->getDecl();
7201       SugaredConverted = TemplateArgument(D, ParamType);
7202       CanonicalConverted =
7203           TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
7204                            S.Context.getCanonicalType(ParamType));
7205     }
7206     return Invalid;
7207   }
7208 
7209   // We found something else, but we don't know specifically what it is.
7210   S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7211       << Arg->getSourceRange();
7212   S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7213   return true;
7214 }
7215 
7216 /// Check a template argument against its corresponding
7217 /// non-type template parameter.
7218 ///
7219 /// This routine implements the semantics of C++ [temp.arg.nontype].
7220 /// If an error occurred, it returns ExprError(); otherwise, it
7221 /// returns the converted template argument. \p ParamType is the
7222 /// type of the non-type template parameter after it has been instantiated.
CheckTemplateArgument(NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * Arg,TemplateArgument & SugaredConverted,TemplateArgument & CanonicalConverted,CheckTemplateArgumentKind CTAK)7223 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
7224                                        QualType ParamType, Expr *Arg,
7225                                        TemplateArgument &SugaredConverted,
7226                                        TemplateArgument &CanonicalConverted,
7227                                        CheckTemplateArgumentKind CTAK) {
7228   SourceLocation StartLoc = Arg->getBeginLoc();
7229 
7230   // If the parameter type somehow involves auto, deduce the type now.
7231   DeducedType *DeducedT = ParamType->getContainedDeducedType();
7232   if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
7233     // During template argument deduction, we allow 'decltype(auto)' to
7234     // match an arbitrary dependent argument.
7235     // FIXME: The language rules don't say what happens in this case.
7236     // FIXME: We get an opaque dependent type out of decltype(auto) if the
7237     // expression is merely instantiation-dependent; is this enough?
7238     if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
7239       auto *AT = dyn_cast<AutoType>(DeducedT);
7240       if (AT && AT->isDecltypeAuto()) {
7241         SugaredConverted = TemplateArgument(Arg);
7242         CanonicalConverted = TemplateArgument(
7243             Context.getCanonicalTemplateArgument(SugaredConverted));
7244         return Arg;
7245       }
7246     }
7247 
7248     // When checking a deduced template argument, deduce from its type even if
7249     // the type is dependent, in order to check the types of non-type template
7250     // arguments line up properly in partial ordering.
7251     Expr *DeductionArg = Arg;
7252     if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
7253       DeductionArg = PE->getPattern();
7254     TypeSourceInfo *TSI =
7255         Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7256     if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
7257       InitializedEntity Entity =
7258           InitializedEntity::InitializeTemplateParameter(ParamType, Param);
7259       InitializationKind Kind = InitializationKind::CreateForInit(
7260           DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7261       Expr *Inits[1] = {DeductionArg};
7262       ParamType =
7263           DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
7264       if (ParamType.isNull())
7265         return ExprError();
7266     } else {
7267       TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7268                                  Param->getDepth() + 1);
7269       ParamType = QualType();
7270       TemplateDeductionResult Result =
7271           DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7272                          /*DependentDeduction=*/true,
7273                          // We do not check constraints right now because the
7274                          // immediately-declared constraint of the auto type is
7275                          // also an associated constraint, and will be checked
7276                          // along with the other associated constraints after
7277                          // checking the template argument list.
7278                          /*IgnoreConstraints=*/true);
7279       if (Result == TDK_AlreadyDiagnosed) {
7280         if (ParamType.isNull())
7281           return ExprError();
7282       } else if (Result != TDK_Success) {
7283         Diag(Arg->getExprLoc(),
7284              diag::err_non_type_template_parm_type_deduction_failure)
7285             << Param->getDeclName() << Param->getType() << Arg->getType()
7286             << Arg->getSourceRange();
7287         NoteTemplateParameterLocation(*Param);
7288         return ExprError();
7289       }
7290     }
7291     // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7292     // an error. The error message normally references the parameter
7293     // declaration, but here we'll pass the argument location because that's
7294     // where the parameter type is deduced.
7295     ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7296     if (ParamType.isNull()) {
7297       NoteTemplateParameterLocation(*Param);
7298       return ExprError();
7299     }
7300   }
7301 
7302   // We should have already dropped all cv-qualifiers by now.
7303   assert(!ParamType.hasQualifiers() &&
7304          "non-type template parameter type cannot be qualified");
7305 
7306   // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7307   if (CTAK == CTAK_Deduced &&
7308       (ParamType->isReferenceType()
7309            ? !Context.hasSameType(ParamType.getNonReferenceType(),
7310                                   Arg->getType())
7311            : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
7312     // FIXME: If either type is dependent, we skip the check. This isn't
7313     // correct, since during deduction we're supposed to have replaced each
7314     // template parameter with some unique (non-dependent) placeholder.
7315     // FIXME: If the argument type contains 'auto', we carry on and fail the
7316     // type check in order to force specific types to be more specialized than
7317     // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
7318     // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
7319     if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
7320         !Arg->getType()->getContainedDeducedType()) {
7321       SugaredConverted = TemplateArgument(Arg);
7322       CanonicalConverted = TemplateArgument(
7323           Context.getCanonicalTemplateArgument(SugaredConverted));
7324       return Arg;
7325     }
7326     // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7327     // we should actually be checking the type of the template argument in P,
7328     // not the type of the template argument deduced from A, against the
7329     // template parameter type.
7330     Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7331       << Arg->getType()
7332       << ParamType.getUnqualifiedType();
7333     NoteTemplateParameterLocation(*Param);
7334     return ExprError();
7335   }
7336 
7337   // If either the parameter has a dependent type or the argument is
7338   // type-dependent, there's nothing we can check now.
7339   if (ParamType->isDependentType() || Arg->isTypeDependent()) {
7340     // Force the argument to the type of the parameter to maintain invariants.
7341     auto *PE = dyn_cast<PackExpansionExpr>(Arg);
7342     if (PE)
7343       Arg = PE->getPattern();
7344     ExprResult E = ImpCastExprToType(
7345         Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7346         ParamType->isLValueReferenceType()   ? VK_LValue
7347         : ParamType->isRValueReferenceType() ? VK_XValue
7348                                              : VK_PRValue);
7349     if (E.isInvalid())
7350       return ExprError();
7351     if (PE) {
7352       // Recreate a pack expansion if we unwrapped one.
7353       E = new (Context)
7354           PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
7355                             PE->getNumExpansions());
7356     }
7357     SugaredConverted = TemplateArgument(E.get());
7358     CanonicalConverted = TemplateArgument(
7359         Context.getCanonicalTemplateArgument(SugaredConverted));
7360     return E;
7361   }
7362 
7363   QualType CanonParamType = Context.getCanonicalType(ParamType);
7364   // Avoid making a copy when initializing a template parameter of class type
7365   // from a template parameter object of the same type. This is going beyond
7366   // the standard, but is required for soundness: in
7367   //   template<A a> struct X { X *p; X<a> *q; };
7368   // ... we need p and q to have the same type.
7369   //
7370   // Similarly, don't inject a call to a copy constructor when initializing
7371   // from a template parameter of the same type.
7372   Expr *InnerArg = Arg->IgnoreParenImpCasts();
7373   if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7374       Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7375     NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7376     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7377 
7378       SugaredConverted = TemplateArgument(TPO, ParamType);
7379       CanonicalConverted =
7380           TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
7381       return Arg;
7382     }
7383     if (isa<NonTypeTemplateParmDecl>(ND)) {
7384       SugaredConverted = TemplateArgument(Arg);
7385       CanonicalConverted =
7386           Context.getCanonicalTemplateArgument(SugaredConverted);
7387       return Arg;
7388     }
7389   }
7390 
7391   // The initialization of the parameter from the argument is
7392   // a constant-evaluated context.
7393   EnterExpressionEvaluationContext ConstantEvaluated(
7394       *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7395 
7396   bool IsConvertedConstantExpression = true;
7397   if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) {
7398     InitializationKind Kind = InitializationKind::CreateForInit(
7399         Arg->getBeginLoc(), /*DirectInit=*/false, Arg);
7400     Expr *Inits[1] = {Arg};
7401     InitializedEntity Entity =
7402         InitializedEntity::InitializeTemplateParameter(ParamType, Param);
7403     InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7404     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7405     if (Result.isInvalid() || !Result.get())
7406       return ExprError();
7407     Result = ActOnConstantExpression(Result.get());
7408     if (Result.isInvalid() || !Result.get())
7409       return ExprError();
7410     Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7411                               /*DiscardedValue=*/false,
7412                               /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
7413               .get();
7414     IsConvertedConstantExpression = false;
7415   }
7416 
7417   if (getLangOpts().CPlusPlus17) {
7418     // C++17 [temp.arg.nontype]p1:
7419     //   A template-argument for a non-type template parameter shall be
7420     //   a converted constant expression of the type of the template-parameter.
7421     APValue Value;
7422     ExprResult ArgResult;
7423     if (IsConvertedConstantExpression) {
7424       ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
7425                                                    CCEK_TemplateArg, Param);
7426       if (ArgResult.isInvalid())
7427         return ExprError();
7428     } else {
7429       ArgResult = Arg;
7430     }
7431 
7432     // For a value-dependent argument, CheckConvertedConstantExpression is
7433     // permitted (and expected) to be unable to determine a value.
7434     if (ArgResult.get()->isValueDependent()) {
7435       SugaredConverted = TemplateArgument(ArgResult.get());
7436       CanonicalConverted =
7437           Context.getCanonicalTemplateArgument(SugaredConverted);
7438       return ArgResult;
7439     }
7440 
7441     APValue PreNarrowingValue;
7442     ArgResult = EvaluateConvertedConstantExpression(
7443         ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/
7444         false, PreNarrowingValue);
7445     if (ArgResult.isInvalid())
7446       return ExprError();
7447 
7448     if (Value.isLValue()) {
7449       APValue::LValueBase Base = Value.getLValueBase();
7450       auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7451       //   For a non-type template-parameter of pointer or reference type,
7452       //   the value of the constant expression shall not refer to
7453       assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
7454              ParamType->isNullPtrType());
7455       // -- a temporary object
7456       // -- a string literal
7457       // -- the result of a typeid expression, or
7458       // -- a predefined __func__ variable
7459       if (Base &&
7460           (!VD ||
7461            isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
7462         Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7463             << Arg->getSourceRange();
7464         return ExprError();
7465       }
7466 
7467       if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7468           VD->getType()->isArrayType() &&
7469           Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7470           !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7471         SugaredConverted = TemplateArgument(VD, ParamType);
7472         CanonicalConverted = TemplateArgument(
7473             cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType);
7474         return ArgResult.get();
7475       }
7476 
7477       // -- a subobject [until C++20]
7478       if (!getLangOpts().CPlusPlus20) {
7479         if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7480             Value.isLValueOnePastTheEnd()) {
7481           Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7482               << Value.getAsString(Context, ParamType);
7483           return ExprError();
7484         }
7485         assert((VD || !ParamType->isReferenceType()) &&
7486                "null reference should not be a constant expression");
7487         assert((!VD || !ParamType->isNullPtrType()) &&
7488                "non-null value of type nullptr_t?");
7489       }
7490     }
7491 
7492     if (Value.isAddrLabelDiff())
7493       return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7494 
7495     SugaredConverted = TemplateArgument(Context, ParamType, Value);
7496     CanonicalConverted = TemplateArgument(Context, CanonParamType, Value);
7497     return ArgResult.get();
7498   }
7499 
7500   // C++ [temp.arg.nontype]p5:
7501   //   The following conversions are performed on each expression used
7502   //   as a non-type template-argument. If a non-type
7503   //   template-argument cannot be converted to the type of the
7504   //   corresponding template-parameter then the program is
7505   //   ill-formed.
7506   if (ParamType->isIntegralOrEnumerationType()) {
7507     // C++11:
7508     //   -- for a non-type template-parameter of integral or
7509     //      enumeration type, conversions permitted in a converted
7510     //      constant expression are applied.
7511     //
7512     // C++98:
7513     //   -- for a non-type template-parameter of integral or
7514     //      enumeration type, integral promotions (4.5) and integral
7515     //      conversions (4.7) are applied.
7516 
7517     if (getLangOpts().CPlusPlus11) {
7518       // C++ [temp.arg.nontype]p1:
7519       //   A template-argument for a non-type, non-template template-parameter
7520       //   shall be one of:
7521       //
7522       //     -- for a non-type template-parameter of integral or enumeration
7523       //        type, a converted constant expression of the type of the
7524       //        template-parameter; or
7525       llvm::APSInt Value;
7526       ExprResult ArgResult =
7527         CheckConvertedConstantExpression(Arg, ParamType, Value,
7528                                          CCEK_TemplateArg);
7529       if (ArgResult.isInvalid())
7530         return ExprError();
7531 
7532       // We can't check arbitrary value-dependent arguments.
7533       if (ArgResult.get()->isValueDependent()) {
7534         SugaredConverted = TemplateArgument(ArgResult.get());
7535         CanonicalConverted =
7536             Context.getCanonicalTemplateArgument(SugaredConverted);
7537         return ArgResult;
7538       }
7539 
7540       // Widen the argument value to sizeof(parameter type). This is almost
7541       // always a no-op, except when the parameter type is bool. In
7542       // that case, this may extend the argument from 1 bit to 8 bits.
7543       QualType IntegerType = ParamType;
7544       if (const EnumType *Enum = IntegerType->getAs<EnumType>())
7545         IntegerType = Enum->getDecl()->getIntegerType();
7546       Value = Value.extOrTrunc(IntegerType->isBitIntType()
7547                                    ? Context.getIntWidth(IntegerType)
7548                                    : Context.getTypeSize(IntegerType));
7549 
7550       SugaredConverted = TemplateArgument(Context, Value, ParamType);
7551       CanonicalConverted =
7552           TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7553       return ArgResult;
7554     }
7555 
7556     ExprResult ArgResult = DefaultLvalueConversion(Arg);
7557     if (ArgResult.isInvalid())
7558       return ExprError();
7559     Arg = ArgResult.get();
7560 
7561     QualType ArgType = Arg->getType();
7562 
7563     // C++ [temp.arg.nontype]p1:
7564     //   A template-argument for a non-type, non-template
7565     //   template-parameter shall be one of:
7566     //
7567     //     -- an integral constant-expression of integral or enumeration
7568     //        type; or
7569     //     -- the name of a non-type template-parameter; or
7570     llvm::APSInt Value;
7571     if (!ArgType->isIntegralOrEnumerationType()) {
7572       Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7573           << ArgType << Arg->getSourceRange();
7574       NoteTemplateParameterLocation(*Param);
7575       return ExprError();
7576     } else if (!Arg->isValueDependent()) {
7577       class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7578         QualType T;
7579 
7580       public:
7581         TmplArgICEDiagnoser(QualType T) : T(T) { }
7582 
7583         SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7584                                              SourceLocation Loc) override {
7585           return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7586         }
7587       } Diagnoser(ArgType);
7588 
7589       Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7590       if (!Arg)
7591         return ExprError();
7592     }
7593 
7594     // From here on out, all we care about is the unqualified form
7595     // of the argument type.
7596     ArgType = ArgType.getUnqualifiedType();
7597 
7598     // Try to convert the argument to the parameter's type.
7599     if (Context.hasSameType(ParamType, ArgType)) {
7600       // Okay: no conversion necessary
7601     } else if (ParamType->isBooleanType()) {
7602       // This is an integral-to-boolean conversion.
7603       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7604     } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7605                !ParamType->isEnumeralType()) {
7606       // This is an integral promotion or conversion.
7607       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7608     } else {
7609       // We can't perform this conversion.
7610       Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7611           << Arg->getType() << ParamType << Arg->getSourceRange();
7612       NoteTemplateParameterLocation(*Param);
7613       return ExprError();
7614     }
7615 
7616     // Add the value of this argument to the list of converted
7617     // arguments. We use the bitwidth and signedness of the template
7618     // parameter.
7619     if (Arg->isValueDependent()) {
7620       // The argument is value-dependent. Create a new
7621       // TemplateArgument with the converted expression.
7622       SugaredConverted = TemplateArgument(Arg);
7623       CanonicalConverted =
7624           Context.getCanonicalTemplateArgument(SugaredConverted);
7625       return Arg;
7626     }
7627 
7628     QualType IntegerType = ParamType;
7629     if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
7630       IntegerType = Enum->getDecl()->getIntegerType();
7631     }
7632 
7633     if (ParamType->isBooleanType()) {
7634       // Value must be zero or one.
7635       Value = Value != 0;
7636       unsigned AllowedBits = Context.getTypeSize(IntegerType);
7637       if (Value.getBitWidth() != AllowedBits)
7638         Value = Value.extOrTrunc(AllowedBits);
7639       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7640     } else {
7641       llvm::APSInt OldValue = Value;
7642 
7643       // Coerce the template argument's value to the value it will have
7644       // based on the template parameter's type.
7645       unsigned AllowedBits = IntegerType->isBitIntType()
7646                                  ? Context.getIntWidth(IntegerType)
7647                                  : Context.getTypeSize(IntegerType);
7648       if (Value.getBitWidth() != AllowedBits)
7649         Value = Value.extOrTrunc(AllowedBits);
7650       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7651 
7652       // Complain if an unsigned parameter received a negative value.
7653       if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7654           (OldValue.isSigned() && OldValue.isNegative())) {
7655         Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7656             << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7657             << Arg->getSourceRange();
7658         NoteTemplateParameterLocation(*Param);
7659       }
7660 
7661       // Complain if we overflowed the template parameter's type.
7662       unsigned RequiredBits;
7663       if (IntegerType->isUnsignedIntegerOrEnumerationType())
7664         RequiredBits = OldValue.getActiveBits();
7665       else if (OldValue.isUnsigned())
7666         RequiredBits = OldValue.getActiveBits() + 1;
7667       else
7668         RequiredBits = OldValue.getSignificantBits();
7669       if (RequiredBits > AllowedBits) {
7670         Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7671             << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7672             << Arg->getSourceRange();
7673         NoteTemplateParameterLocation(*Param);
7674       }
7675     }
7676 
7677     QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7678     SugaredConverted = TemplateArgument(Context, Value, T);
7679     CanonicalConverted =
7680         TemplateArgument(Context, Value, Context.getCanonicalType(T));
7681     return Arg;
7682   }
7683 
7684   QualType ArgType = Arg->getType();
7685   DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7686 
7687   // Handle pointer-to-function, reference-to-function, and
7688   // pointer-to-member-function all in (roughly) the same way.
7689   if (// -- For a non-type template-parameter of type pointer to
7690       //    function, only the function-to-pointer conversion (4.3) is
7691       //    applied. If the template-argument represents a set of
7692       //    overloaded functions (or a pointer to such), the matching
7693       //    function is selected from the set (13.4).
7694       (ParamType->isPointerType() &&
7695        ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7696       // -- For a non-type template-parameter of type reference to
7697       //    function, no conversions apply. If the template-argument
7698       //    represents a set of overloaded functions, the matching
7699       //    function is selected from the set (13.4).
7700       (ParamType->isReferenceType() &&
7701        ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7702       // -- For a non-type template-parameter of type pointer to
7703       //    member function, no conversions apply. If the
7704       //    template-argument represents a set of overloaded member
7705       //    functions, the matching member function is selected from
7706       //    the set (13.4).
7707       (ParamType->isMemberPointerType() &&
7708        ParamType->castAs<MemberPointerType>()->getPointeeType()
7709          ->isFunctionType())) {
7710 
7711     if (Arg->getType() == Context.OverloadTy) {
7712       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7713                                                                 true,
7714                                                                 FoundResult)) {
7715         if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7716           return ExprError();
7717 
7718         ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7719         if (Res.isInvalid())
7720           return ExprError();
7721         Arg = Res.get();
7722         ArgType = Arg->getType();
7723       } else
7724         return ExprError();
7725     }
7726 
7727     if (!ParamType->isMemberPointerType()) {
7728       if (CheckTemplateArgumentAddressOfObjectOrFunction(
7729               *this, Param, ParamType, Arg, SugaredConverted,
7730               CanonicalConverted))
7731         return ExprError();
7732       return Arg;
7733     }
7734 
7735     if (CheckTemplateArgumentPointerToMember(
7736             *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7737       return ExprError();
7738     return Arg;
7739   }
7740 
7741   if (ParamType->isPointerType()) {
7742     //   -- for a non-type template-parameter of type pointer to
7743     //      object, qualification conversions (4.4) and the
7744     //      array-to-pointer conversion (4.2) are applied.
7745     // C++0x also allows a value of std::nullptr_t.
7746     assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7747            "Only object pointers allowed here");
7748 
7749     if (CheckTemplateArgumentAddressOfObjectOrFunction(
7750             *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7751       return ExprError();
7752     return Arg;
7753   }
7754 
7755   if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7756     //   -- For a non-type template-parameter of type reference to
7757     //      object, no conversions apply. The type referred to by the
7758     //      reference may be more cv-qualified than the (otherwise
7759     //      identical) type of the template-argument. The
7760     //      template-parameter is bound directly to the
7761     //      template-argument, which must be an lvalue.
7762     assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7763            "Only object references allowed here");
7764 
7765     if (Arg->getType() == Context.OverloadTy) {
7766       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
7767                                                  ParamRefType->getPointeeType(),
7768                                                                 true,
7769                                                                 FoundResult)) {
7770         if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7771           return ExprError();
7772         ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7773         if (Res.isInvalid())
7774           return ExprError();
7775         Arg = Res.get();
7776         ArgType = Arg->getType();
7777       } else
7778         return ExprError();
7779     }
7780 
7781     if (CheckTemplateArgumentAddressOfObjectOrFunction(
7782             *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7783       return ExprError();
7784     return Arg;
7785   }
7786 
7787   // Deal with parameters of type std::nullptr_t.
7788   if (ParamType->isNullPtrType()) {
7789     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7790       SugaredConverted = TemplateArgument(Arg);
7791       CanonicalConverted =
7792           Context.getCanonicalTemplateArgument(SugaredConverted);
7793       return Arg;
7794     }
7795 
7796     switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7797     case NPV_NotNullPointer:
7798       Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7799         << Arg->getType() << ParamType;
7800       NoteTemplateParameterLocation(*Param);
7801       return ExprError();
7802 
7803     case NPV_Error:
7804       return ExprError();
7805 
7806     case NPV_NullPointer:
7807       Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7808       SugaredConverted = TemplateArgument(ParamType,
7809                                           /*isNullPtr=*/true);
7810       CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7811                                             /*isNullPtr=*/true);
7812       return Arg;
7813     }
7814   }
7815 
7816   //     -- For a non-type template-parameter of type pointer to data
7817   //        member, qualification conversions (4.4) are applied.
7818   assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7819 
7820   if (CheckTemplateArgumentPointerToMember(
7821           *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7822     return ExprError();
7823   return Arg;
7824 }
7825 
7826 static void DiagnoseTemplateParameterListArityMismatch(
7827     Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7828     Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7829 
7830 /// Check a template argument against its corresponding
7831 /// template template parameter.
7832 ///
7833 /// This routine implements the semantics of C++ [temp.arg.template].
7834 /// It returns true if an error occurred, and false otherwise.
CheckTemplateTemplateArgument(TemplateTemplateParmDecl * Param,TemplateParameterList * Params,TemplateArgumentLoc & Arg)7835 bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7836                                          TemplateParameterList *Params,
7837                                          TemplateArgumentLoc &Arg) {
7838   TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7839   TemplateDecl *Template = Name.getAsTemplateDecl();
7840   if (!Template) {
7841     // Any dependent template name is fine.
7842     assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7843     return false;
7844   }
7845 
7846   if (Template->isInvalidDecl())
7847     return true;
7848 
7849   // C++0x [temp.arg.template]p1:
7850   //   A template-argument for a template template-parameter shall be
7851   //   the name of a class template or an alias template, expressed as an
7852   //   id-expression. When the template-argument names a class template, only
7853   //   primary class templates are considered when matching the
7854   //   template template argument with the corresponding parameter;
7855   //   partial specializations are not considered even if their
7856   //   parameter lists match that of the template template parameter.
7857   //
7858   // Note that we also allow template template parameters here, which
7859   // will happen when we are dealing with, e.g., class template
7860   // partial specializations.
7861   if (!isa<ClassTemplateDecl>(Template) &&
7862       !isa<TemplateTemplateParmDecl>(Template) &&
7863       !isa<TypeAliasTemplateDecl>(Template) &&
7864       !isa<BuiltinTemplateDecl>(Template)) {
7865     assert(isa<FunctionTemplateDecl>(Template) &&
7866            "Only function templates are possible here");
7867     Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7868     Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7869       << Template;
7870   }
7871 
7872   // C++1z [temp.arg.template]p3: (DR 150)
7873   //   A template-argument matches a template template-parameter P when P
7874   //   is at least as specialized as the template-argument A.
7875   // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a
7876   //  defect report resolution from C++17 and shouldn't be introduced by
7877   //  concepts.
7878   if (getLangOpts().RelaxedTemplateTemplateArgs) {
7879     // Quick check for the common case:
7880     //   If P contains a parameter pack, then A [...] matches P if each of A's
7881     //   template parameters matches the corresponding template parameter in
7882     //   the template-parameter-list of P.
7883     if (TemplateParameterListsAreEqual(
7884             Template->getTemplateParameters(), Params, false,
7885             TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) &&
7886         // If the argument has no associated constraints, then the parameter is
7887         // definitely at least as specialized as the argument.
7888         // Otherwise - we need a more thorough check.
7889         !Template->hasAssociatedConstraints())
7890       return false;
7891 
7892     if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
7893                                                           Arg.getLocation())) {
7894       // P2113
7895       // C++20[temp.func.order]p2
7896       //   [...] If both deductions succeed, the partial ordering selects the
7897       // more constrained template (if one exists) as determined below.
7898       SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7899       Params->getAssociatedConstraints(ParamsAC);
7900       // C++2a[temp.arg.template]p3
7901       //   [...] In this comparison, if P is unconstrained, the constraints on A
7902       //   are not considered.
7903       if (ParamsAC.empty())
7904         return false;
7905 
7906       Template->getAssociatedConstraints(TemplateAC);
7907 
7908       bool IsParamAtLeastAsConstrained;
7909       if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7910                                  IsParamAtLeastAsConstrained))
7911         return true;
7912       if (!IsParamAtLeastAsConstrained) {
7913         Diag(Arg.getLocation(),
7914              diag::err_template_template_parameter_not_at_least_as_constrained)
7915             << Template << Param << Arg.getSourceRange();
7916         Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7917         Diag(Template->getLocation(), diag::note_entity_declared_at)
7918             << Template;
7919         MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7920                                                       TemplateAC);
7921         return true;
7922       }
7923       return false;
7924     }
7925     // FIXME: Produce better diagnostics for deduction failures.
7926   }
7927 
7928   return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
7929                                          Params,
7930                                          true,
7931                                          TPL_TemplateTemplateArgumentMatch,
7932                                          Arg.getLocation());
7933 }
7934 
noteLocation(Sema & S,const NamedDecl & Decl,unsigned HereDiagID,unsigned ExternalDiagID)7935 static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7936                                                 unsigned HereDiagID,
7937                                                 unsigned ExternalDiagID) {
7938   if (Decl.getLocation().isValid())
7939     return S.Diag(Decl.getLocation(), HereDiagID);
7940 
7941   SmallString<128> Str;
7942   llvm::raw_svector_ostream Out(Str);
7943   PrintingPolicy PP = S.getPrintingPolicy();
7944   PP.TerseOutput = 1;
7945   Decl.print(Out, PP);
7946   return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7947 }
7948 
NoteTemplateLocation(const NamedDecl & Decl,std::optional<SourceRange> ParamRange)7949 void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7950                                 std::optional<SourceRange> ParamRange) {
7951   SemaDiagnosticBuilder DB =
7952       noteLocation(*this, Decl, diag::note_template_decl_here,
7953                    diag::note_template_decl_external);
7954   if (ParamRange && ParamRange->isValid()) {
7955     assert(Decl.getLocation().isValid() &&
7956            "Parameter range has location when Decl does not");
7957     DB << *ParamRange;
7958   }
7959 }
7960 
NoteTemplateParameterLocation(const NamedDecl & Decl)7961 void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7962   noteLocation(*this, Decl, diag::note_template_param_here,
7963                diag::note_template_param_external);
7964 }
7965 
7966 /// Given a non-type template argument that refers to a
7967 /// declaration and the type of its corresponding non-type template
7968 /// parameter, produce an expression that properly refers to that
7969 /// declaration.
7970 ExprResult
BuildExpressionFromDeclTemplateArgument(const TemplateArgument & Arg,QualType ParamType,SourceLocation Loc)7971 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7972                                               QualType ParamType,
7973                                               SourceLocation Loc) {
7974   // C++ [temp.param]p8:
7975   //
7976   //   A non-type template-parameter of type "array of T" or
7977   //   "function returning T" is adjusted to be of type "pointer to
7978   //   T" or "pointer to function returning T", respectively.
7979   if (ParamType->isArrayType())
7980     ParamType = Context.getArrayDecayedType(ParamType);
7981   else if (ParamType->isFunctionType())
7982     ParamType = Context.getPointerType(ParamType);
7983 
7984   // For a NULL non-type template argument, return nullptr casted to the
7985   // parameter's type.
7986   if (Arg.getKind() == TemplateArgument::NullPtr) {
7987     return ImpCastExprToType(
7988              new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7989                              ParamType,
7990                              ParamType->getAs<MemberPointerType>()
7991                                ? CK_NullToMemberPointer
7992                                : CK_NullToPointer);
7993   }
7994   assert(Arg.getKind() == TemplateArgument::Declaration &&
7995          "Only declaration template arguments permitted here");
7996 
7997   ValueDecl *VD = Arg.getAsDecl();
7998 
7999   CXXScopeSpec SS;
8000   if (ParamType->isMemberPointerType()) {
8001     // If this is a pointer to member, we need to use a qualified name to
8002     // form a suitable pointer-to-member constant.
8003     assert(VD->getDeclContext()->isRecord() &&
8004            (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
8005             isa<IndirectFieldDecl>(VD)));
8006     QualType ClassType
8007       = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
8008     NestedNameSpecifier *Qualifier
8009       = NestedNameSpecifier::Create(Context, nullptr, false,
8010                                     ClassType.getTypePtr());
8011     SS.MakeTrivial(Context, Qualifier, Loc);
8012   }
8013 
8014   ExprResult RefExpr = BuildDeclarationNameExpr(
8015       SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8016   if (RefExpr.isInvalid())
8017     return ExprError();
8018 
8019   // For a pointer, the argument declaration is the pointee. Take its address.
8020   QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8021   if (ParamType->isPointerType() && !ElemT.isNull() &&
8022       Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
8023     // Decay an array argument if we want a pointer to its first element.
8024     RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
8025     if (RefExpr.isInvalid())
8026       return ExprError();
8027   } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8028     // For any other pointer, take the address (or form a pointer-to-member).
8029     RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
8030     if (RefExpr.isInvalid())
8031       return ExprError();
8032   } else if (ParamType->isRecordType()) {
8033     assert(isa<TemplateParamObjectDecl>(VD) &&
8034            "arg for class template param not a template parameter object");
8035     // No conversions apply in this case.
8036     return RefExpr;
8037   } else {
8038     assert(ParamType->isReferenceType() &&
8039            "unexpected type for decl template argument");
8040   }
8041 
8042   // At this point we should have the right value category.
8043   assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8044          "value kind mismatch for non-type template argument");
8045 
8046   // The type of the template parameter can differ from the type of the
8047   // argument in various ways; convert it now if necessary.
8048   QualType DestExprType = ParamType.getNonLValueExprType(Context);
8049   if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
8050     CastKind CK;
8051     QualType Ignored;
8052     if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
8053         IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
8054       CK = CK_NoOp;
8055     } else if (ParamType->isVoidPointerType() &&
8056                RefExpr.get()->getType()->isPointerType()) {
8057       CK = CK_BitCast;
8058     } else {
8059       // FIXME: Pointers to members can need conversion derived-to-base or
8060       // base-to-derived conversions. We currently don't retain enough
8061       // information to convert properly (we need to track a cast path or
8062       // subobject number in the template argument).
8063       llvm_unreachable(
8064           "unexpected conversion required for non-type template argument");
8065     }
8066     RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8067                                 RefExpr.get()->getValueKind());
8068   }
8069 
8070   return RefExpr;
8071 }
8072 
8073 /// Construct a new expression that refers to the given
8074 /// integral template argument with the given source-location
8075 /// information.
8076 ///
8077 /// This routine takes care of the mapping from an integral template
8078 /// argument (which may have any integral type) to the appropriate
8079 /// literal value.
BuildExpressionFromIntegralTemplateArgumentValue(Sema & S,QualType OrigT,const llvm::APSInt & Int,SourceLocation Loc)8080 static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
8081     Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8082   assert(OrigT->isIntegralOrEnumerationType());
8083 
8084   // If this is an enum type that we're instantiating, we need to use an integer
8085   // type the same size as the enumerator.  We don't want to build an
8086   // IntegerLiteral with enum type.  The integer type of an enum type can be of
8087   // any integral type with C++11 enum classes, make sure we create the right
8088   // type of literal for it.
8089   QualType T = OrigT;
8090   if (const EnumType *ET = OrigT->getAs<EnumType>())
8091     T = ET->getDecl()->getIntegerType();
8092 
8093   Expr *E;
8094   if (T->isAnyCharacterType()) {
8095     CharacterLiteralKind Kind;
8096     if (T->isWideCharType())
8097       Kind = CharacterLiteralKind::Wide;
8098     else if (T->isChar8Type() && S.getLangOpts().Char8)
8099       Kind = CharacterLiteralKind::UTF8;
8100     else if (T->isChar16Type())
8101       Kind = CharacterLiteralKind::UTF16;
8102     else if (T->isChar32Type())
8103       Kind = CharacterLiteralKind::UTF32;
8104     else
8105       Kind = CharacterLiteralKind::Ascii;
8106 
8107     E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8108   } else if (T->isBooleanType()) {
8109     E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8110   } else {
8111     E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8112   }
8113 
8114   if (OrigT->isEnumeralType()) {
8115     // FIXME: This is a hack. We need a better way to handle substituted
8116     // non-type template parameters.
8117     E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8118                                nullptr, S.CurFPFeatureOverrides(),
8119                                S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8120                                Loc, Loc);
8121   }
8122 
8123   return E;
8124 }
8125 
BuildExpressionFromNonTypeTemplateArgumentValue(Sema & S,QualType T,const APValue & Val,SourceLocation Loc)8126 static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
8127     Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8128   auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8129     auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8130     ILE->setType(T);
8131     return ILE;
8132   };
8133 
8134   switch (Val.getKind()) {
8135   case APValue::AddrLabelDiff:
8136     // This cannot occur in a template argument at all.
8137   case APValue::Array:
8138   case APValue::Struct:
8139   case APValue::Union:
8140     // These can only occur within a template parameter object, which is
8141     // represented as a TemplateArgument::Declaration.
8142     llvm_unreachable("unexpected template argument value");
8143 
8144   case APValue::Int:
8145     return BuildExpressionFromIntegralTemplateArgumentValue(S, T, Val.getInt(),
8146                                                             Loc);
8147 
8148   case APValue::Float:
8149     return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8150                                    T, Loc);
8151 
8152   case APValue::FixedPoint:
8153     return FixedPointLiteral::CreateFromRawInt(
8154         S.Context, Val.getFixedPoint().getValue(), T, Loc,
8155         Val.getFixedPoint().getScale());
8156 
8157   case APValue::ComplexInt: {
8158     QualType ElemT = T->castAs<ComplexType>()->getElementType();
8159     return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
8160                              S, ElemT, Val.getComplexIntReal(), Loc),
8161                          BuildExpressionFromIntegralTemplateArgumentValue(
8162                              S, ElemT, Val.getComplexIntImag(), Loc)});
8163   }
8164 
8165   case APValue::ComplexFloat: {
8166     QualType ElemT = T->castAs<ComplexType>()->getElementType();
8167     return MakeInitList(
8168         {FloatingLiteral::Create(S.Context, Val.getComplexFloatReal(), true,
8169                                  ElemT, Loc),
8170          FloatingLiteral::Create(S.Context, Val.getComplexFloatImag(), true,
8171                                  ElemT, Loc)});
8172   }
8173 
8174   case APValue::Vector: {
8175     QualType ElemT = T->castAs<VectorType>()->getElementType();
8176     llvm::SmallVector<Expr *, 8> Elts;
8177     for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8178       Elts.push_back(BuildExpressionFromNonTypeTemplateArgumentValue(
8179           S, ElemT, Val.getVectorElt(I), Loc));
8180     return MakeInitList(Elts);
8181   }
8182 
8183   case APValue::None:
8184   case APValue::Indeterminate:
8185     llvm_unreachable("Unexpected APValue kind.");
8186   case APValue::LValue:
8187   case APValue::MemberPointer:
8188     // There isn't necessarily a valid equivalent source-level syntax for
8189     // these; in particular, a naive lowering might violate access control.
8190     // So for now we lower to a ConstantExpr holding the value, wrapped around
8191     // an OpaqueValueExpr.
8192     // FIXME: We should have a better representation for this.
8193     ExprValueKind VK = VK_PRValue;
8194     if (T->isReferenceType()) {
8195       T = T->getPointeeType();
8196       VK = VK_LValue;
8197     }
8198     auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8199     return ConstantExpr::Create(S.Context, OVE, Val);
8200   }
8201   llvm_unreachable("Unhandled APValue::ValueKind enum");
8202 }
8203 
8204 ExprResult
BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument & Arg,SourceLocation Loc)8205 Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
8206                                                  SourceLocation Loc) {
8207   switch (Arg.getKind()) {
8208   case TemplateArgument::Null:
8209   case TemplateArgument::Type:
8210   case TemplateArgument::Template:
8211   case TemplateArgument::TemplateExpansion:
8212   case TemplateArgument::Pack:
8213     llvm_unreachable("not a non-type template argument");
8214 
8215   case TemplateArgument::Expression:
8216     return Arg.getAsExpr();
8217 
8218   case TemplateArgument::NullPtr:
8219   case TemplateArgument::Declaration:
8220     return BuildExpressionFromDeclTemplateArgument(
8221         Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8222 
8223   case TemplateArgument::Integral:
8224     return BuildExpressionFromIntegralTemplateArgumentValue(
8225         *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8226 
8227   case TemplateArgument::StructuralValue:
8228     return BuildExpressionFromNonTypeTemplateArgumentValue(
8229         *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8230   }
8231   llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8232 }
8233 
8234 /// Match two template parameters within template parameter lists.
MatchTemplateParameterKind(Sema & S,NamedDecl * New,const Sema::TemplateCompareNewDeclInfo & NewInstFrom,NamedDecl * Old,const NamedDecl * OldInstFrom,bool Complain,Sema::TemplateParameterListEqualKind Kind,SourceLocation TemplateArgLoc)8235 static bool MatchTemplateParameterKind(
8236     Sema &S, NamedDecl *New,
8237     const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8238     const NamedDecl *OldInstFrom, bool Complain,
8239     Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8240   // Check the actual kind (type, non-type, template).
8241   if (Old->getKind() != New->getKind()) {
8242     if (Complain) {
8243       unsigned NextDiag = diag::err_template_param_different_kind;
8244       if (TemplateArgLoc.isValid()) {
8245         S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8246         NextDiag = diag::note_template_param_different_kind;
8247       }
8248       S.Diag(New->getLocation(), NextDiag)
8249         << (Kind != Sema::TPL_TemplateMatch);
8250       S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8251         << (Kind != Sema::TPL_TemplateMatch);
8252     }
8253 
8254     return false;
8255   }
8256 
8257   // Check that both are parameter packs or neither are parameter packs.
8258   // However, if we are matching a template template argument to a
8259   // template template parameter, the template template parameter can have
8260   // a parameter pack where the template template argument does not.
8261   if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
8262       !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
8263         Old->isTemplateParameterPack())) {
8264     if (Complain) {
8265       unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8266       if (TemplateArgLoc.isValid()) {
8267         S.Diag(TemplateArgLoc,
8268              diag::err_template_arg_template_params_mismatch);
8269         NextDiag = diag::note_template_parameter_pack_non_pack;
8270       }
8271 
8272       unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8273                       : isa<NonTypeTemplateParmDecl>(New)? 1
8274                       : 2;
8275       S.Diag(New->getLocation(), NextDiag)
8276         << ParamKind << New->isParameterPack();
8277       S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8278         << ParamKind << Old->isParameterPack();
8279     }
8280 
8281     return false;
8282   }
8283 
8284   // For non-type template parameters, check the type of the parameter.
8285   if (NonTypeTemplateParmDecl *OldNTTP
8286                                     = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8287     NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
8288 
8289     // If we are matching a template template argument to a template
8290     // template parameter and one of the non-type template parameter types
8291     // is dependent, then we must wait until template instantiation time
8292     // to actually compare the arguments.
8293     if (Kind != Sema::TPL_TemplateTemplateArgumentMatch ||
8294         (!OldNTTP->getType()->isDependentType() &&
8295          !NewNTTP->getType()->isDependentType())) {
8296       // C++20 [temp.over.link]p6:
8297       //   Two [non-type] template-parameters are equivalent [if] they have
8298       //   equivalent types ignoring the use of type-constraints for
8299       //   placeholder types
8300       QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8301       QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8302       if (!S.Context.hasSameType(OldType, NewType)) {
8303         if (Complain) {
8304           unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8305           if (TemplateArgLoc.isValid()) {
8306             S.Diag(TemplateArgLoc,
8307                    diag::err_template_arg_template_params_mismatch);
8308             NextDiag = diag::note_template_nontype_parm_different_type;
8309           }
8310           S.Diag(NewNTTP->getLocation(), NextDiag)
8311             << NewNTTP->getType()
8312             << (Kind != Sema::TPL_TemplateMatch);
8313           S.Diag(OldNTTP->getLocation(),
8314                  diag::note_template_nontype_parm_prev_declaration)
8315             << OldNTTP->getType();
8316         }
8317 
8318         return false;
8319       }
8320     }
8321   }
8322   // For template template parameters, check the template parameter types.
8323   // The template parameter lists of template template
8324   // parameters must agree.
8325   else if (TemplateTemplateParmDecl *OldTTP =
8326                dyn_cast<TemplateTemplateParmDecl>(Old)) {
8327     TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
8328     if (!S.TemplateParameterListsAreEqual(
8329             NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8330             OldTTP->getTemplateParameters(), Complain,
8331             (Kind == Sema::TPL_TemplateMatch
8332                  ? Sema::TPL_TemplateTemplateParmMatch
8333                  : Kind),
8334             TemplateArgLoc))
8335       return false;
8336   }
8337 
8338   if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8339       Kind != Sema::TPL_TemplateTemplateArgumentMatch &&
8340       !isa<TemplateTemplateParmDecl>(Old)) {
8341     const Expr *NewC = nullptr, *OldC = nullptr;
8342 
8343     if (isa<TemplateTypeParmDecl>(New)) {
8344       if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8345         NewC = TC->getImmediatelyDeclaredConstraint();
8346       if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8347         OldC = TC->getImmediatelyDeclaredConstraint();
8348     } else if (isa<NonTypeTemplateParmDecl>(New)) {
8349       if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8350                               ->getPlaceholderTypeConstraint())
8351         NewC = E;
8352       if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8353                               ->getPlaceholderTypeConstraint())
8354         OldC = E;
8355     } else
8356       llvm_unreachable("unexpected template parameter type");
8357 
8358     auto Diagnose = [&] {
8359       S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8360            diag::err_template_different_type_constraint);
8361       S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8362            diag::note_template_prev_declaration) << /*declaration*/0;
8363     };
8364 
8365     if (!NewC != !OldC) {
8366       if (Complain)
8367         Diagnose();
8368       return false;
8369     }
8370 
8371     if (NewC) {
8372       if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8373                                            NewC)) {
8374         if (Complain)
8375           Diagnose();
8376         return false;
8377       }
8378     }
8379   }
8380 
8381   return true;
8382 }
8383 
8384 /// Diagnose a known arity mismatch when comparing template argument
8385 /// lists.
8386 static
DiagnoseTemplateParameterListArityMismatch(Sema & S,TemplateParameterList * New,TemplateParameterList * Old,Sema::TemplateParameterListEqualKind Kind,SourceLocation TemplateArgLoc)8387 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8388                                                 TemplateParameterList *New,
8389                                                 TemplateParameterList *Old,
8390                                       Sema::TemplateParameterListEqualKind Kind,
8391                                                 SourceLocation TemplateArgLoc) {
8392   unsigned NextDiag = diag::err_template_param_list_different_arity;
8393   if (TemplateArgLoc.isValid()) {
8394     S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8395     NextDiag = diag::note_template_param_list_different_arity;
8396   }
8397   S.Diag(New->getTemplateLoc(), NextDiag)
8398     << (New->size() > Old->size())
8399     << (Kind != Sema::TPL_TemplateMatch)
8400     << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8401   S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8402     << (Kind != Sema::TPL_TemplateMatch)
8403     << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8404 }
8405 
8406 /// Determine whether the given template parameter lists are
8407 /// equivalent.
8408 ///
8409 /// \param New  The new template parameter list, typically written in the
8410 /// source code as part of a new template declaration.
8411 ///
8412 /// \param Old  The old template parameter list, typically found via
8413 /// name lookup of the template declared with this template parameter
8414 /// list.
8415 ///
8416 /// \param Complain  If true, this routine will produce a diagnostic if
8417 /// the template parameter lists are not equivalent.
8418 ///
8419 /// \param Kind describes how we are to match the template parameter lists.
8420 ///
8421 /// \param TemplateArgLoc If this source location is valid, then we
8422 /// are actually checking the template parameter list of a template
8423 /// argument (New) against the template parameter list of its
8424 /// corresponding template template parameter (Old). We produce
8425 /// slightly different diagnostics in this scenario.
8426 ///
8427 /// \returns True if the template parameter lists are equal, false
8428 /// otherwise.
TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo & NewInstFrom,TemplateParameterList * New,const NamedDecl * OldInstFrom,TemplateParameterList * Old,bool Complain,TemplateParameterListEqualKind Kind,SourceLocation TemplateArgLoc)8429 bool Sema::TemplateParameterListsAreEqual(
8430     const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8431     const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8432     TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8433   if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
8434     if (Complain)
8435       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8436                                                  TemplateArgLoc);
8437 
8438     return false;
8439   }
8440 
8441   // C++0x [temp.arg.template]p3:
8442   //   A template-argument matches a template template-parameter (call it P)
8443   //   when each of the template parameters in the template-parameter-list of
8444   //   the template-argument's corresponding class template or alias template
8445   //   (call it A) matches the corresponding template parameter in the
8446   //   template-parameter-list of P. [...]
8447   TemplateParameterList::iterator NewParm = New->begin();
8448   TemplateParameterList::iterator NewParmEnd = New->end();
8449   for (TemplateParameterList::iterator OldParm = Old->begin(),
8450                                     OldParmEnd = Old->end();
8451        OldParm != OldParmEnd; ++OldParm) {
8452     if (Kind != TPL_TemplateTemplateArgumentMatch ||
8453         !(*OldParm)->isTemplateParameterPack()) {
8454       if (NewParm == NewParmEnd) {
8455         if (Complain)
8456           DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8457                                                      TemplateArgLoc);
8458 
8459         return false;
8460       }
8461 
8462       if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8463                                       OldInstFrom, Complain, Kind,
8464                                       TemplateArgLoc))
8465         return false;
8466 
8467       ++NewParm;
8468       continue;
8469     }
8470 
8471     // C++0x [temp.arg.template]p3:
8472     //   [...] When P's template- parameter-list contains a template parameter
8473     //   pack (14.5.3), the template parameter pack will match zero or more
8474     //   template parameters or template parameter packs in the
8475     //   template-parameter-list of A with the same type and form as the
8476     //   template parameter pack in P (ignoring whether those template
8477     //   parameters are template parameter packs).
8478     for (; NewParm != NewParmEnd; ++NewParm) {
8479       if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8480                                       OldInstFrom, Complain, Kind,
8481                                       TemplateArgLoc))
8482         return false;
8483     }
8484   }
8485 
8486   // Make sure we exhausted all of the arguments.
8487   if (NewParm != NewParmEnd) {
8488     if (Complain)
8489       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8490                                                  TemplateArgLoc);
8491 
8492     return false;
8493   }
8494 
8495   if (Kind != TPL_TemplateTemplateArgumentMatch &&
8496       Kind != TPL_TemplateParamsEquivalent) {
8497     const Expr *NewRC = New->getRequiresClause();
8498     const Expr *OldRC = Old->getRequiresClause();
8499 
8500     auto Diagnose = [&] {
8501       Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8502            diag::err_template_different_requires_clause);
8503       Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8504            diag::note_template_prev_declaration) << /*declaration*/0;
8505     };
8506 
8507     if (!NewRC != !OldRC) {
8508       if (Complain)
8509         Diagnose();
8510       return false;
8511     }
8512 
8513     if (NewRC) {
8514       if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8515                                          NewRC)) {
8516         if (Complain)
8517           Diagnose();
8518         return false;
8519       }
8520     }
8521   }
8522 
8523   return true;
8524 }
8525 
8526 /// Check whether a template can be declared within this scope.
8527 ///
8528 /// If the template declaration is valid in this scope, returns
8529 /// false. Otherwise, issues a diagnostic and returns true.
8530 bool
CheckTemplateDeclScope(Scope * S,TemplateParameterList * TemplateParams)8531 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8532   if (!S)
8533     return false;
8534 
8535   // Find the nearest enclosing declaration scope.
8536   while ((S->getFlags() & Scope::DeclScope) == 0 ||
8537          (S->getFlags() & Scope::TemplateParamScope) != 0)
8538     S = S->getParent();
8539 
8540   // C++ [temp.pre]p6: [P2096]
8541   //   A template, explicit specialization, or partial specialization shall not
8542   //   have C linkage.
8543   DeclContext *Ctx = S->getEntity();
8544   if (Ctx && Ctx->isExternCContext()) {
8545     Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
8546         << TemplateParams->getSourceRange();
8547     if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8548       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8549     return true;
8550   }
8551   Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8552 
8553   // C++ [temp]p2:
8554   //   A template-declaration can appear only as a namespace scope or
8555   //   class scope declaration.
8556   // C++ [temp.expl.spec]p3:
8557   //   An explicit specialization may be declared in any scope in which the
8558   //   corresponding primary template may be defined.
8559   // C++ [temp.class.spec]p6: [P2096]
8560   //   A partial specialization may be declared in any scope in which the
8561   //   corresponding primary template may be defined.
8562   if (Ctx) {
8563     if (Ctx->isFileContext())
8564       return false;
8565     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8566       // C++ [temp.mem]p2:
8567       //   A local class shall not have member templates.
8568       if (RD->isLocalClass())
8569         return Diag(TemplateParams->getTemplateLoc(),
8570                     diag::err_template_inside_local_class)
8571           << TemplateParams->getSourceRange();
8572       else
8573         return false;
8574     }
8575   }
8576 
8577   return Diag(TemplateParams->getTemplateLoc(),
8578               diag::err_template_outside_namespace_or_class_scope)
8579     << TemplateParams->getSourceRange();
8580 }
8581 
8582 /// Determine what kind of template specialization the given declaration
8583 /// is.
getTemplateSpecializationKind(Decl * D)8584 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8585   if (!D)
8586     return TSK_Undeclared;
8587 
8588   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8589     return Record->getTemplateSpecializationKind();
8590   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8591     return Function->getTemplateSpecializationKind();
8592   if (VarDecl *Var = dyn_cast<VarDecl>(D))
8593     return Var->getTemplateSpecializationKind();
8594 
8595   return TSK_Undeclared;
8596 }
8597 
8598 /// Check whether a specialization is well-formed in the current
8599 /// context.
8600 ///
8601 /// This routine determines whether a template specialization can be declared
8602 /// in the current context (C++ [temp.expl.spec]p2).
8603 ///
8604 /// \param S the semantic analysis object for which this check is being
8605 /// performed.
8606 ///
8607 /// \param Specialized the entity being specialized or instantiated, which
8608 /// may be a kind of template (class template, function template, etc.) or
8609 /// a member of a class template (member function, static data member,
8610 /// member class).
8611 ///
8612 /// \param PrevDecl the previous declaration of this entity, if any.
8613 ///
8614 /// \param Loc the location of the explicit specialization or instantiation of
8615 /// this entity.
8616 ///
8617 /// \param IsPartialSpecialization whether this is a partial specialization of
8618 /// a class template.
8619 ///
8620 /// \returns true if there was an error that we cannot recover from, false
8621 /// otherwise.
CheckTemplateSpecializationScope(Sema & S,NamedDecl * Specialized,NamedDecl * PrevDecl,SourceLocation Loc,bool IsPartialSpecialization)8622 static bool CheckTemplateSpecializationScope(Sema &S,
8623                                              NamedDecl *Specialized,
8624                                              NamedDecl *PrevDecl,
8625                                              SourceLocation Loc,
8626                                              bool IsPartialSpecialization) {
8627   // Keep these "kind" numbers in sync with the %select statements in the
8628   // various diagnostics emitted by this routine.
8629   int EntityKind = 0;
8630   if (isa<ClassTemplateDecl>(Specialized))
8631     EntityKind = IsPartialSpecialization? 1 : 0;
8632   else if (isa<VarTemplateDecl>(Specialized))
8633     EntityKind = IsPartialSpecialization ? 3 : 2;
8634   else if (isa<FunctionTemplateDecl>(Specialized))
8635     EntityKind = 4;
8636   else if (isa<CXXMethodDecl>(Specialized))
8637     EntityKind = 5;
8638   else if (isa<VarDecl>(Specialized))
8639     EntityKind = 6;
8640   else if (isa<RecordDecl>(Specialized))
8641     EntityKind = 7;
8642   else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8643     EntityKind = 8;
8644   else {
8645     S.Diag(Loc, diag::err_template_spec_unknown_kind)
8646       << S.getLangOpts().CPlusPlus11;
8647     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8648     return true;
8649   }
8650 
8651   // C++ [temp.expl.spec]p2:
8652   //   An explicit specialization may be declared in any scope in which
8653   //   the corresponding primary template may be defined.
8654   if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8655     S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8656       << Specialized;
8657     return true;
8658   }
8659 
8660   // C++ [temp.class.spec]p6:
8661   //   A class template partial specialization may be declared in any
8662   //   scope in which the primary template may be defined.
8663   DeclContext *SpecializedContext =
8664       Specialized->getDeclContext()->getRedeclContext();
8665   DeclContext *DC = S.CurContext->getRedeclContext();
8666 
8667   // Make sure that this redeclaration (or definition) occurs in the same
8668   // scope or an enclosing namespace.
8669   if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8670                             : DC->Equals(SpecializedContext))) {
8671     if (isa<TranslationUnitDecl>(SpecializedContext))
8672       S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8673         << EntityKind << Specialized;
8674     else {
8675       auto *ND = cast<NamedDecl>(SpecializedContext);
8676       int Diag = diag::err_template_spec_redecl_out_of_scope;
8677       if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8678         Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8679       S.Diag(Loc, Diag) << EntityKind << Specialized
8680                         << ND << isa<CXXRecordDecl>(ND);
8681     }
8682 
8683     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8684 
8685     // Don't allow specializing in the wrong class during error recovery.
8686     // Otherwise, things can go horribly wrong.
8687     if (DC->isRecord())
8688       return true;
8689   }
8690 
8691   return false;
8692 }
8693 
findTemplateParameterInType(unsigned Depth,Expr * E)8694 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8695   if (!E->isTypeDependent())
8696     return SourceLocation();
8697   DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8698   Checker.TraverseStmt(E);
8699   if (Checker.MatchLoc.isInvalid())
8700     return E->getSourceRange();
8701   return Checker.MatchLoc;
8702 }
8703 
findTemplateParameter(unsigned Depth,TypeLoc TL)8704 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8705   if (!TL.getType()->isDependentType())
8706     return SourceLocation();
8707   DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8708   Checker.TraverseTypeLoc(TL);
8709   if (Checker.MatchLoc.isInvalid())
8710     return TL.getSourceRange();
8711   return Checker.MatchLoc;
8712 }
8713 
8714 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8715 /// that checks non-type template partial specialization arguments.
CheckNonTypeTemplatePartialSpecializationArgs(Sema & S,SourceLocation TemplateNameLoc,NonTypeTemplateParmDecl * Param,const TemplateArgument * Args,unsigned NumArgs,bool IsDefaultArgument)8716 static bool CheckNonTypeTemplatePartialSpecializationArgs(
8717     Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8718     const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8719   for (unsigned I = 0; I != NumArgs; ++I) {
8720     if (Args[I].getKind() == TemplateArgument::Pack) {
8721       if (CheckNonTypeTemplatePartialSpecializationArgs(
8722               S, TemplateNameLoc, Param, Args[I].pack_begin(),
8723               Args[I].pack_size(), IsDefaultArgument))
8724         return true;
8725 
8726       continue;
8727     }
8728 
8729     if (Args[I].getKind() != TemplateArgument::Expression)
8730       continue;
8731 
8732     Expr *ArgExpr = Args[I].getAsExpr();
8733 
8734     // We can have a pack expansion of any of the bullets below.
8735     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8736       ArgExpr = Expansion->getPattern();
8737 
8738     // Strip off any implicit casts we added as part of type checking.
8739     while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8740       ArgExpr = ICE->getSubExpr();
8741 
8742     // C++ [temp.class.spec]p8:
8743     //   A non-type argument is non-specialized if it is the name of a
8744     //   non-type parameter. All other non-type arguments are
8745     //   specialized.
8746     //
8747     // Below, we check the two conditions that only apply to
8748     // specialized non-type arguments, so skip any non-specialized
8749     // arguments.
8750     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8751       if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8752         continue;
8753 
8754     // C++ [temp.class.spec]p9:
8755     //   Within the argument list of a class template partial
8756     //   specialization, the following restrictions apply:
8757     //     -- A partially specialized non-type argument expression
8758     //        shall not involve a template parameter of the partial
8759     //        specialization except when the argument expression is a
8760     //        simple identifier.
8761     //     -- The type of a template parameter corresponding to a
8762     //        specialized non-type argument shall not be dependent on a
8763     //        parameter of the specialization.
8764     // DR1315 removes the first bullet, leaving an incoherent set of rules.
8765     // We implement a compromise between the original rules and DR1315:
8766     //     --  A specialized non-type template argument shall not be
8767     //         type-dependent and the corresponding template parameter
8768     //         shall have a non-dependent type.
8769     SourceRange ParamUseRange =
8770         findTemplateParameterInType(Param->getDepth(), ArgExpr);
8771     if (ParamUseRange.isValid()) {
8772       if (IsDefaultArgument) {
8773         S.Diag(TemplateNameLoc,
8774                diag::err_dependent_non_type_arg_in_partial_spec);
8775         S.Diag(ParamUseRange.getBegin(),
8776                diag::note_dependent_non_type_default_arg_in_partial_spec)
8777           << ParamUseRange;
8778       } else {
8779         S.Diag(ParamUseRange.getBegin(),
8780                diag::err_dependent_non_type_arg_in_partial_spec)
8781           << ParamUseRange;
8782       }
8783       return true;
8784     }
8785 
8786     ParamUseRange = findTemplateParameter(
8787         Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8788     if (ParamUseRange.isValid()) {
8789       S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8790              diag::err_dependent_typed_non_type_arg_in_partial_spec)
8791           << Param->getType();
8792       S.NoteTemplateParameterLocation(*Param);
8793       return true;
8794     }
8795   }
8796 
8797   return false;
8798 }
8799 
8800 /// Check the non-type template arguments of a class template
8801 /// partial specialization according to C++ [temp.class.spec]p9.
8802 ///
8803 /// \param TemplateNameLoc the location of the template name.
8804 /// \param PrimaryTemplate the template parameters of the primary class
8805 ///        template.
8806 /// \param NumExplicit the number of explicitly-specified template arguments.
8807 /// \param TemplateArgs the template arguments of the class template
8808 ///        partial specialization.
8809 ///
8810 /// \returns \c true if there was an error, \c false otherwise.
CheckTemplatePartialSpecializationArgs(SourceLocation TemplateNameLoc,TemplateDecl * PrimaryTemplate,unsigned NumExplicit,ArrayRef<TemplateArgument> TemplateArgs)8811 bool Sema::CheckTemplatePartialSpecializationArgs(
8812     SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8813     unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8814   // We have to be conservative when checking a template in a dependent
8815   // context.
8816   if (PrimaryTemplate->getDeclContext()->isDependentContext())
8817     return false;
8818 
8819   TemplateParameterList *TemplateParams =
8820       PrimaryTemplate->getTemplateParameters();
8821   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8822     NonTypeTemplateParmDecl *Param
8823       = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8824     if (!Param)
8825       continue;
8826 
8827     if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8828                                                       Param, &TemplateArgs[I],
8829                                                       1, I >= NumExplicit))
8830       return true;
8831   }
8832 
8833   return false;
8834 }
8835 
ActOnClassTemplateSpecialization(Scope * S,unsigned TagSpec,TagUseKind TUK,SourceLocation KWLoc,SourceLocation ModulePrivateLoc,CXXScopeSpec & SS,TemplateIdAnnotation & TemplateId,const ParsedAttributesView & Attr,MultiTemplateParamsArg TemplateParameterLists,SkipBodyInfo * SkipBody)8836 DeclResult Sema::ActOnClassTemplateSpecialization(
8837     Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8838     SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8839     TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8840     MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8841   assert(TUK != TUK_Reference && "References are not specializations");
8842 
8843   // NOTE: KWLoc is the location of the tag keyword. This will instead
8844   // store the location of the outermost template keyword in the declaration.
8845   SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
8846     ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
8847   SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8848   SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8849   SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8850 
8851   // Find the class template we're specializing
8852   TemplateName Name = TemplateId.Template.get();
8853   ClassTemplateDecl *ClassTemplate
8854     = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8855 
8856   if (!ClassTemplate) {
8857     Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8858       << (Name.getAsTemplateDecl() &&
8859           isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8860     return true;
8861   }
8862 
8863   bool isMemberSpecialization = false;
8864   bool isPartialSpecialization = false;
8865 
8866   // Check the validity of the template headers that introduce this
8867   // template.
8868   // FIXME: We probably shouldn't complain about these headers for
8869   // friend declarations.
8870   bool Invalid = false;
8871   TemplateParameterList *TemplateParams =
8872       MatchTemplateParametersToScopeSpecifier(
8873           KWLoc, TemplateNameLoc, SS, &TemplateId,
8874           TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
8875           Invalid);
8876   if (Invalid)
8877     return true;
8878 
8879   // Check that we can declare a template specialization here.
8880   if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8881     return true;
8882 
8883   if (TemplateParams && TemplateParams->size() > 0) {
8884     isPartialSpecialization = true;
8885 
8886     if (TUK == TUK_Friend) {
8887       Diag(KWLoc, diag::err_partial_specialization_friend)
8888         << SourceRange(LAngleLoc, RAngleLoc);
8889       return true;
8890     }
8891 
8892     // C++ [temp.class.spec]p10:
8893     //   The template parameter list of a specialization shall not
8894     //   contain default template argument values.
8895     for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8896       Decl *Param = TemplateParams->getParam(I);
8897       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8898         if (TTP->hasDefaultArgument()) {
8899           Diag(TTP->getDefaultArgumentLoc(),
8900                diag::err_default_arg_in_partial_spec);
8901           TTP->removeDefaultArgument();
8902         }
8903       } else if (NonTypeTemplateParmDecl *NTTP
8904                    = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8905         if (Expr *DefArg = NTTP->getDefaultArgument()) {
8906           Diag(NTTP->getDefaultArgumentLoc(),
8907                diag::err_default_arg_in_partial_spec)
8908             << DefArg->getSourceRange();
8909           NTTP->removeDefaultArgument();
8910         }
8911       } else {
8912         TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8913         if (TTP->hasDefaultArgument()) {
8914           Diag(TTP->getDefaultArgument().getLocation(),
8915                diag::err_default_arg_in_partial_spec)
8916             << TTP->getDefaultArgument().getSourceRange();
8917           TTP->removeDefaultArgument();
8918         }
8919       }
8920     }
8921   } else if (TemplateParams) {
8922     if (TUK == TUK_Friend)
8923       Diag(KWLoc, diag::err_template_spec_friend)
8924         << FixItHint::CreateRemoval(
8925                                 SourceRange(TemplateParams->getTemplateLoc(),
8926                                             TemplateParams->getRAngleLoc()))
8927         << SourceRange(LAngleLoc, RAngleLoc);
8928   } else {
8929     assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
8930   }
8931 
8932   // Check that the specialization uses the same tag kind as the
8933   // original template.
8934   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8935   assert(Kind != TagTypeKind::Enum &&
8936          "Invalid enum tag in class template spec!");
8937   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8938                                     Kind, TUK == TUK_Definition, KWLoc,
8939                                     ClassTemplate->getIdentifier())) {
8940     Diag(KWLoc, diag::err_use_with_wrong_tag)
8941       << ClassTemplate
8942       << FixItHint::CreateReplacement(KWLoc,
8943                             ClassTemplate->getTemplatedDecl()->getKindName());
8944     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8945          diag::note_previous_use);
8946     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8947   }
8948 
8949   // Translate the parser's template argument list in our AST format.
8950   TemplateArgumentListInfo TemplateArgs =
8951       makeTemplateArgumentListInfo(*this, TemplateId);
8952 
8953   // Check for unexpanded parameter packs in any of the template arguments.
8954   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8955     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8956                                         isPartialSpecialization
8957                                             ? UPPC_PartialSpecialization
8958                                             : UPPC_ExplicitSpecialization))
8959       return true;
8960 
8961   // Check that the template argument list is well-formed for this
8962   // template.
8963   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
8964   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8965                                 false, SugaredConverted, CanonicalConverted,
8966                                 /*UpdateArgsWithConversions=*/true))
8967     return true;
8968 
8969   // Find the class template (partial) specialization declaration that
8970   // corresponds to these arguments.
8971   if (isPartialSpecialization) {
8972     if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
8973                                                TemplateArgs.size(),
8974                                                CanonicalConverted))
8975       return true;
8976 
8977     // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8978     // also do it during instantiation.
8979     if (!Name.isDependent() &&
8980         !TemplateSpecializationType::anyDependentTemplateArguments(
8981             TemplateArgs, CanonicalConverted)) {
8982       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8983         << ClassTemplate->getDeclName();
8984       isPartialSpecialization = false;
8985     }
8986   }
8987 
8988   void *InsertPos = nullptr;
8989   ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8990 
8991   if (isPartialSpecialization)
8992     PrevDecl = ClassTemplate->findPartialSpecialization(
8993         CanonicalConverted, TemplateParams, InsertPos);
8994   else
8995     PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
8996 
8997   ClassTemplateSpecializationDecl *Specialization = nullptr;
8998 
8999   // Check whether we can declare a class template specialization in
9000   // the current scope.
9001   if (TUK != TUK_Friend &&
9002       CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
9003                                        TemplateNameLoc,
9004                                        isPartialSpecialization))
9005     return true;
9006 
9007   // The canonical type
9008   QualType CanonType;
9009   if (isPartialSpecialization) {
9010     // Build the canonical type that describes the converted template
9011     // arguments of the class template partial specialization.
9012     TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
9013     CanonType = Context.getTemplateSpecializationType(CanonTemplate,
9014                                                       CanonicalConverted);
9015 
9016     if (Context.hasSameType(CanonType,
9017                         ClassTemplate->getInjectedClassNameSpecialization()) &&
9018         (!Context.getLangOpts().CPlusPlus20 ||
9019          !TemplateParams->hasAssociatedConstraints())) {
9020       // C++ [temp.class.spec]p9b3:
9021       //
9022       //   -- The argument list of the specialization shall not be identical
9023       //      to the implicit argument list of the primary template.
9024       //
9025       // This rule has since been removed, because it's redundant given DR1495,
9026       // but we keep it because it produces better diagnostics and recovery.
9027       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
9028         << /*class template*/0 << (TUK == TUK_Definition)
9029         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
9030       return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
9031                                 ClassTemplate->getIdentifier(),
9032                                 TemplateNameLoc,
9033                                 Attr,
9034                                 TemplateParams,
9035                                 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
9036                                 /*FriendLoc*/SourceLocation(),
9037                                 TemplateParameterLists.size() - 1,
9038                                 TemplateParameterLists.data());
9039     }
9040 
9041     // Create a new class template partial specialization declaration node.
9042     ClassTemplatePartialSpecializationDecl *PrevPartial
9043       = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
9044     ClassTemplatePartialSpecializationDecl *Partial =
9045         ClassTemplatePartialSpecializationDecl::Create(
9046             Context, Kind, ClassTemplate->getDeclContext(), KWLoc,
9047             TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted,
9048             TemplateArgs, CanonType, PrevPartial);
9049     SetNestedNameSpecifier(*this, Partial, SS);
9050     if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9051       Partial->setTemplateParameterListsInfo(
9052           Context, TemplateParameterLists.drop_back(1));
9053     }
9054 
9055     if (!PrevPartial)
9056       ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
9057     Specialization = Partial;
9058 
9059     // If we are providing an explicit specialization of a member class
9060     // template specialization, make a note of that.
9061     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
9062       PrevPartial->setMemberSpecialization();
9063 
9064     CheckTemplatePartialSpecialization(Partial);
9065   } else {
9066     // Create a new class template specialization declaration node for
9067     // this explicit specialization or friend declaration.
9068     Specialization = ClassTemplateSpecializationDecl::Create(
9069         Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9070         ClassTemplate, CanonicalConverted, PrevDecl);
9071     SetNestedNameSpecifier(*this, Specialization, SS);
9072     if (TemplateParameterLists.size() > 0) {
9073       Specialization->setTemplateParameterListsInfo(Context,
9074                                                     TemplateParameterLists);
9075     }
9076 
9077     if (!PrevDecl)
9078       ClassTemplate->AddSpecialization(Specialization, InsertPos);
9079 
9080     if (CurContext->isDependentContext()) {
9081       TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
9082       CanonType = Context.getTemplateSpecializationType(CanonTemplate,
9083                                                         CanonicalConverted);
9084     } else {
9085       CanonType = Context.getTypeDeclType(Specialization);
9086     }
9087   }
9088 
9089   // C++ [temp.expl.spec]p6:
9090   //   If a template, a member template or the member of a class template is
9091   //   explicitly specialized then that specialization shall be declared
9092   //   before the first use of that specialization that would cause an implicit
9093   //   instantiation to take place, in every translation unit in which such a
9094   //   use occurs; no diagnostic is required.
9095   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9096     bool Okay = false;
9097     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9098       // Is there any previous explicit specialization declaration?
9099       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
9100         Okay = true;
9101         break;
9102       }
9103     }
9104 
9105     if (!Okay) {
9106       SourceRange Range(TemplateNameLoc, RAngleLoc);
9107       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9108         << Context.getTypeDeclType(Specialization) << Range;
9109 
9110       Diag(PrevDecl->getPointOfInstantiation(),
9111            diag::note_instantiation_required_here)
9112         << (PrevDecl->getTemplateSpecializationKind()
9113                                                 != TSK_ImplicitInstantiation);
9114       return true;
9115     }
9116   }
9117 
9118   // If this is not a friend, note that this is an explicit specialization.
9119   if (TUK != TUK_Friend)
9120     Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9121 
9122   // Check that this isn't a redefinition of this specialization.
9123   if (TUK == TUK_Definition) {
9124     RecordDecl *Def = Specialization->getDefinition();
9125     NamedDecl *Hidden = nullptr;
9126     if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
9127       SkipBody->ShouldSkip = true;
9128       SkipBody->Previous = Def;
9129       makeMergedDefinitionVisible(Hidden);
9130     } else if (Def) {
9131       SourceRange Range(TemplateNameLoc, RAngleLoc);
9132       Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9133       Diag(Def->getLocation(), diag::note_previous_definition);
9134       Specialization->setInvalidDecl();
9135       return true;
9136     }
9137   }
9138 
9139   ProcessDeclAttributeList(S, Specialization, Attr);
9140 
9141   // Add alignment attributes if necessary; these attributes are checked when
9142   // the ASTContext lays out the structure.
9143   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9144     AddAlignmentAttributesForRecord(Specialization);
9145     AddMsStructLayoutForRecord(Specialization);
9146   }
9147 
9148   if (ModulePrivateLoc.isValid())
9149     Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9150       << (isPartialSpecialization? 1 : 0)
9151       << FixItHint::CreateRemoval(ModulePrivateLoc);
9152 
9153   // Build the fully-sugared type for this class template
9154   // specialization as the user wrote in the specialization
9155   // itself. This means that we'll pretty-print the type retrieved
9156   // from the specialization's declaration the way that the user
9157   // actually wrote the specialization, rather than formatting the
9158   // name based on the "canonical" representation used to store the
9159   // template arguments in the specialization.
9160   TypeSourceInfo *WrittenTy
9161     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
9162                                                 TemplateArgs, CanonType);
9163   if (TUK != TUK_Friend) {
9164     Specialization->setTypeAsWritten(WrittenTy);
9165     Specialization->setTemplateKeywordLoc(TemplateKWLoc);
9166   }
9167 
9168   // C++ [temp.expl.spec]p9:
9169   //   A template explicit specialization is in the scope of the
9170   //   namespace in which the template was defined.
9171   //
9172   // We actually implement this paragraph where we set the semantic
9173   // context (in the creation of the ClassTemplateSpecializationDecl),
9174   // but we also maintain the lexical context where the actual
9175   // definition occurs.
9176   Specialization->setLexicalDeclContext(CurContext);
9177 
9178   // We may be starting the definition of this specialization.
9179   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
9180     Specialization->startDefinition();
9181 
9182   if (TUK == TUK_Friend) {
9183     FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
9184                                             TemplateNameLoc,
9185                                             WrittenTy,
9186                                             /*FIXME:*/KWLoc);
9187     Friend->setAccess(AS_public);
9188     CurContext->addDecl(Friend);
9189   } else {
9190     // Add the specialization into its lexical context, so that it can
9191     // be seen when iterating through the list of declarations in that
9192     // context. However, specializations are not found by name lookup.
9193     CurContext->addDecl(Specialization);
9194   }
9195 
9196   if (SkipBody && SkipBody->ShouldSkip)
9197     return SkipBody->Previous;
9198 
9199   return Specialization;
9200 }
9201 
ActOnTemplateDeclarator(Scope * S,MultiTemplateParamsArg TemplateParameterLists,Declarator & D)9202 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
9203                               MultiTemplateParamsArg TemplateParameterLists,
9204                                     Declarator &D) {
9205   Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9206   ActOnDocumentableDecl(NewDecl);
9207   return NewDecl;
9208 }
9209 
ActOnConceptDefinition(Scope * S,MultiTemplateParamsArg TemplateParameterLists,IdentifierInfo * Name,SourceLocation NameLoc,Expr * ConstraintExpr)9210 Decl *Sema::ActOnConceptDefinition(Scope *S,
9211                               MultiTemplateParamsArg TemplateParameterLists,
9212                                    IdentifierInfo *Name, SourceLocation NameLoc,
9213                                    Expr *ConstraintExpr) {
9214   DeclContext *DC = CurContext;
9215 
9216   if (!DC->getRedeclContext()->isFileContext()) {
9217     Diag(NameLoc,
9218       diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9219     return nullptr;
9220   }
9221 
9222   if (TemplateParameterLists.size() > 1) {
9223     Diag(NameLoc, diag::err_concept_extra_headers);
9224     return nullptr;
9225   }
9226 
9227   TemplateParameterList *Params = TemplateParameterLists.front();
9228 
9229   if (Params->size() == 0) {
9230     Diag(NameLoc, diag::err_concept_no_parameters);
9231     return nullptr;
9232   }
9233 
9234   // Ensure that the parameter pack, if present, is the last parameter in the
9235   // template.
9236   for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9237                                              ParamEnd = Params->end();
9238        ParamIt != ParamEnd; ++ParamIt) {
9239     Decl const *Param = *ParamIt;
9240     if (Param->isParameterPack()) {
9241       if (++ParamIt == ParamEnd)
9242         break;
9243       Diag(Param->getLocation(),
9244            diag::err_template_param_pack_must_be_last_template_parameter);
9245       return nullptr;
9246     }
9247   }
9248 
9249   if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
9250     return nullptr;
9251 
9252   ConceptDecl *NewDecl =
9253       ConceptDecl::Create(Context, DC, NameLoc, Name, Params, ConstraintExpr);
9254 
9255   if (NewDecl->hasAssociatedConstraints()) {
9256     // C++2a [temp.concept]p4:
9257     // A concept shall not have associated constraints.
9258     Diag(NameLoc, diag::err_concept_no_associated_constraints);
9259     NewDecl->setInvalidDecl();
9260   }
9261 
9262   // Check for conflicting previous declaration.
9263   DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
9264   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9265                         forRedeclarationInCurContext());
9266   LookupName(Previous, S);
9267   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
9268                        /*AllowInlineNamespace*/false);
9269   bool AddToScope = true;
9270   CheckConceptRedefinition(NewDecl, Previous, AddToScope);
9271 
9272   ActOnDocumentableDecl(NewDecl);
9273   if (AddToScope)
9274     PushOnScopeChains(NewDecl, S);
9275   return NewDecl;
9276 }
9277 
CheckConceptRedefinition(ConceptDecl * NewDecl,LookupResult & Previous,bool & AddToScope)9278 void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
9279                                     LookupResult &Previous, bool &AddToScope) {
9280   AddToScope = true;
9281 
9282   if (Previous.empty())
9283     return;
9284 
9285   auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9286   if (!OldConcept) {
9287     auto *Old = Previous.getRepresentativeDecl();
9288     Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9289         << NewDecl->getDeclName();
9290     notePreviousDefinition(Old, NewDecl->getLocation());
9291     AddToScope = false;
9292     return;
9293   }
9294   // Check if we can merge with a concept declaration.
9295   bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9296   if (!IsSame) {
9297     Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9298         << NewDecl->getDeclName();
9299     notePreviousDefinition(OldConcept, NewDecl->getLocation());
9300     AddToScope = false;
9301     return;
9302   }
9303   if (hasReachableDefinition(OldConcept) &&
9304       IsRedefinitionInModule(NewDecl, OldConcept)) {
9305     Diag(NewDecl->getLocation(), diag::err_redefinition)
9306         << NewDecl->getDeclName();
9307     notePreviousDefinition(OldConcept, NewDecl->getLocation());
9308     AddToScope = false;
9309     return;
9310   }
9311   if (!Previous.isSingleResult()) {
9312     // FIXME: we should produce an error in case of ambig and failed lookups.
9313     //        Other decls (e.g. namespaces) also have this shortcoming.
9314     return;
9315   }
9316   // We unwrap canonical decl late to check for module visibility.
9317   Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9318 }
9319 
9320 /// \brief Strips various properties off an implicit instantiation
9321 /// that has just been explicitly specialized.
StripImplicitInstantiation(NamedDecl * D,bool MinGW)9322 static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9323   if (MinGW || (isa<FunctionDecl>(D) &&
9324                 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9325     D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9326 
9327   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9328     FD->setInlineSpecified(false);
9329 }
9330 
9331 /// Compute the diagnostic location for an explicit instantiation
9332 //  declaration or definition.
DiagLocForExplicitInstantiation(NamedDecl * D,SourceLocation PointOfInstantiation)9333 static SourceLocation DiagLocForExplicitInstantiation(
9334     NamedDecl* D, SourceLocation PointOfInstantiation) {
9335   // Explicit instantiations following a specialization have no effect and
9336   // hence no PointOfInstantiation. In that case, walk decl backwards
9337   // until a valid name loc is found.
9338   SourceLocation PrevDiagLoc = PointOfInstantiation;
9339   for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9340        Prev = Prev->getPreviousDecl()) {
9341     PrevDiagLoc = Prev->getLocation();
9342   }
9343   assert(PrevDiagLoc.isValid() &&
9344          "Explicit instantiation without point of instantiation?");
9345   return PrevDiagLoc;
9346 }
9347 
9348 /// Diagnose cases where we have an explicit template specialization
9349 /// before/after an explicit template instantiation, producing diagnostics
9350 /// for those cases where they are required and determining whether the
9351 /// new specialization/instantiation will have any effect.
9352 ///
9353 /// \param NewLoc the location of the new explicit specialization or
9354 /// instantiation.
9355 ///
9356 /// \param NewTSK the kind of the new explicit specialization or instantiation.
9357 ///
9358 /// \param PrevDecl the previous declaration of the entity.
9359 ///
9360 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
9361 ///
9362 /// \param PrevPointOfInstantiation if valid, indicates where the previous
9363 /// declaration was instantiated (either implicitly or explicitly).
9364 ///
9365 /// \param HasNoEffect will be set to true to indicate that the new
9366 /// specialization or instantiation has no effect and should be ignored.
9367 ///
9368 /// \returns true if there was an error that should prevent the introduction of
9369 /// the new declaration into the AST, false otherwise.
9370 bool
CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,TemplateSpecializationKind NewTSK,NamedDecl * PrevDecl,TemplateSpecializationKind PrevTSK,SourceLocation PrevPointOfInstantiation,bool & HasNoEffect)9371 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9372                                              TemplateSpecializationKind NewTSK,
9373                                              NamedDecl *PrevDecl,
9374                                              TemplateSpecializationKind PrevTSK,
9375                                         SourceLocation PrevPointOfInstantiation,
9376                                              bool &HasNoEffect) {
9377   HasNoEffect = false;
9378 
9379   switch (NewTSK) {
9380   case TSK_Undeclared:
9381   case TSK_ImplicitInstantiation:
9382     assert(
9383         (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9384         "previous declaration must be implicit!");
9385     return false;
9386 
9387   case TSK_ExplicitSpecialization:
9388     switch (PrevTSK) {
9389     case TSK_Undeclared:
9390     case TSK_ExplicitSpecialization:
9391       // Okay, we're just specializing something that is either already
9392       // explicitly specialized or has merely been mentioned without any
9393       // instantiation.
9394       return false;
9395 
9396     case TSK_ImplicitInstantiation:
9397       if (PrevPointOfInstantiation.isInvalid()) {
9398         // The declaration itself has not actually been instantiated, so it is
9399         // still okay to specialize it.
9400         StripImplicitInstantiation(
9401             PrevDecl,
9402             Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
9403         return false;
9404       }
9405       // Fall through
9406       [[fallthrough]];
9407 
9408     case TSK_ExplicitInstantiationDeclaration:
9409     case TSK_ExplicitInstantiationDefinition:
9410       assert((PrevTSK == TSK_ImplicitInstantiation ||
9411               PrevPointOfInstantiation.isValid()) &&
9412              "Explicit instantiation without point of instantiation?");
9413 
9414       // C++ [temp.expl.spec]p6:
9415       //   If a template, a member template or the member of a class template
9416       //   is explicitly specialized then that specialization shall be declared
9417       //   before the first use of that specialization that would cause an
9418       //   implicit instantiation to take place, in every translation unit in
9419       //   which such a use occurs; no diagnostic is required.
9420       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9421         // Is there any previous explicit specialization declaration?
9422         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
9423           return false;
9424       }
9425 
9426       Diag(NewLoc, diag::err_specialization_after_instantiation)
9427         << PrevDecl;
9428       Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9429         << (PrevTSK != TSK_ImplicitInstantiation);
9430 
9431       return true;
9432     }
9433     llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9434 
9435   case TSK_ExplicitInstantiationDeclaration:
9436     switch (PrevTSK) {
9437     case TSK_ExplicitInstantiationDeclaration:
9438       // This explicit instantiation declaration is redundant (that's okay).
9439       HasNoEffect = true;
9440       return false;
9441 
9442     case TSK_Undeclared:
9443     case TSK_ImplicitInstantiation:
9444       // We're explicitly instantiating something that may have already been
9445       // implicitly instantiated; that's fine.
9446       return false;
9447 
9448     case TSK_ExplicitSpecialization:
9449       // C++0x [temp.explicit]p4:
9450       //   For a given set of template parameters, if an explicit instantiation
9451       //   of a template appears after a declaration of an explicit
9452       //   specialization for that template, the explicit instantiation has no
9453       //   effect.
9454       HasNoEffect = true;
9455       return false;
9456 
9457     case TSK_ExplicitInstantiationDefinition:
9458       // C++0x [temp.explicit]p10:
9459       //   If an entity is the subject of both an explicit instantiation
9460       //   declaration and an explicit instantiation definition in the same
9461       //   translation unit, the definition shall follow the declaration.
9462       Diag(NewLoc,
9463            diag::err_explicit_instantiation_declaration_after_definition);
9464 
9465       // Explicit instantiations following a specialization have no effect and
9466       // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9467       // until a valid name loc is found.
9468       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9469            diag::note_explicit_instantiation_definition_here);
9470       HasNoEffect = true;
9471       return false;
9472     }
9473     llvm_unreachable("Unexpected TemplateSpecializationKind!");
9474 
9475   case TSK_ExplicitInstantiationDefinition:
9476     switch (PrevTSK) {
9477     case TSK_Undeclared:
9478     case TSK_ImplicitInstantiation:
9479       // We're explicitly instantiating something that may have already been
9480       // implicitly instantiated; that's fine.
9481       return false;
9482 
9483     case TSK_ExplicitSpecialization:
9484       // C++ DR 259, C++0x [temp.explicit]p4:
9485       //   For a given set of template parameters, if an explicit
9486       //   instantiation of a template appears after a declaration of
9487       //   an explicit specialization for that template, the explicit
9488       //   instantiation has no effect.
9489       Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9490         << PrevDecl;
9491       Diag(PrevDecl->getLocation(),
9492            diag::note_previous_template_specialization);
9493       HasNoEffect = true;
9494       return false;
9495 
9496     case TSK_ExplicitInstantiationDeclaration:
9497       // We're explicitly instantiating a definition for something for which we
9498       // were previously asked to suppress instantiations. That's fine.
9499 
9500       // C++0x [temp.explicit]p4:
9501       //   For a given set of template parameters, if an explicit instantiation
9502       //   of a template appears after a declaration of an explicit
9503       //   specialization for that template, the explicit instantiation has no
9504       //   effect.
9505       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9506         // Is there any previous explicit specialization declaration?
9507         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
9508           HasNoEffect = true;
9509           break;
9510         }
9511       }
9512 
9513       return false;
9514 
9515     case TSK_ExplicitInstantiationDefinition:
9516       // C++0x [temp.spec]p5:
9517       //   For a given template and a given set of template-arguments,
9518       //     - an explicit instantiation definition shall appear at most once
9519       //       in a program,
9520 
9521       // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9522       Diag(NewLoc, (getLangOpts().MSVCCompat)
9523                        ? diag::ext_explicit_instantiation_duplicate
9524                        : diag::err_explicit_instantiation_duplicate)
9525           << PrevDecl;
9526       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9527            diag::note_previous_explicit_instantiation);
9528       HasNoEffect = true;
9529       return false;
9530     }
9531   }
9532 
9533   llvm_unreachable("Missing specialization/instantiation case?");
9534 }
9535 
9536 /// Perform semantic analysis for the given dependent function
9537 /// template specialization.
9538 ///
9539 /// The only possible way to get a dependent function template specialization
9540 /// is with a friend declaration, like so:
9541 ///
9542 /// \code
9543 ///   template \<class T> void foo(T);
9544 ///   template \<class T> class A {
9545 ///     friend void foo<>(T);
9546 ///   };
9547 /// \endcode
9548 ///
9549 /// There really isn't any useful analysis we can do here, so we
9550 /// just store the information.
CheckDependentFunctionTemplateSpecialization(FunctionDecl * FD,const TemplateArgumentListInfo * ExplicitTemplateArgs,LookupResult & Previous)9551 bool Sema::CheckDependentFunctionTemplateSpecialization(
9552     FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9553     LookupResult &Previous) {
9554   // Remove anything from Previous that isn't a function template in
9555   // the correct context.
9556   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9557   LookupResult::Filter F = Previous.makeFilter();
9558   enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9559   SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9560   while (F.hasNext()) {
9561     NamedDecl *D = F.next()->getUnderlyingDecl();
9562     if (!isa<FunctionTemplateDecl>(D)) {
9563       F.erase();
9564       DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9565       continue;
9566     }
9567 
9568     if (!FDLookupContext->InEnclosingNamespaceSetOf(
9569             D->getDeclContext()->getRedeclContext())) {
9570       F.erase();
9571       DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9572       continue;
9573     }
9574   }
9575   F.done();
9576 
9577   bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9578   if (Previous.empty()) {
9579     Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9580         << IsFriend;
9581     for (auto &P : DiscardedCandidates)
9582       Diag(P.second->getLocation(),
9583            diag::note_dependent_function_template_spec_discard_reason)
9584           << P.first << IsFriend;
9585     return true;
9586   }
9587 
9588   FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
9589                                          ExplicitTemplateArgs);
9590   return false;
9591 }
9592 
9593 /// Perform semantic analysis for the given function template
9594 /// specialization.
9595 ///
9596 /// This routine performs all of the semantic analysis required for an
9597 /// explicit function template specialization. On successful completion,
9598 /// the function declaration \p FD will become a function template
9599 /// specialization.
9600 ///
9601 /// \param FD the function declaration, which will be updated to become a
9602 /// function template specialization.
9603 ///
9604 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
9605 /// if any. Note that this may be valid info even when 0 arguments are
9606 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
9607 /// as it anyway contains info on the angle brackets locations.
9608 ///
9609 /// \param Previous the set of declarations that may be specialized by
9610 /// this function specialization.
9611 ///
9612 /// \param QualifiedFriend whether this is a lookup for a qualified friend
9613 /// declaration with no explicit template argument list that might be
9614 /// befriending a function template specialization.
CheckFunctionTemplateSpecialization(FunctionDecl * FD,TemplateArgumentListInfo * ExplicitTemplateArgs,LookupResult & Previous,bool QualifiedFriend)9615 bool Sema::CheckFunctionTemplateSpecialization(
9616     FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9617     LookupResult &Previous, bool QualifiedFriend) {
9618   // The set of function template specializations that could match this
9619   // explicit function template specialization.
9620   UnresolvedSet<8> Candidates;
9621   TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9622                                             /*ForTakingAddress=*/false);
9623 
9624   llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9625       ConvertedTemplateArgs;
9626 
9627   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9628   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9629          I != E; ++I) {
9630     NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9631     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9632       // Only consider templates found within the same semantic lookup scope as
9633       // FD.
9634       if (!FDLookupContext->InEnclosingNamespaceSetOf(
9635                                 Ovl->getDeclContext()->getRedeclContext()))
9636         continue;
9637 
9638       // When matching a constexpr member function template specialization
9639       // against the primary template, we don't yet know whether the
9640       // specialization has an implicit 'const' (because we don't know whether
9641       // it will be a static member function until we know which template it
9642       // specializes), so adjust it now assuming it specializes this template.
9643       QualType FT = FD->getType();
9644       if (FD->isConstexpr()) {
9645         CXXMethodDecl *OldMD =
9646           dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9647         if (OldMD && OldMD->isConst()) {
9648           const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9649           FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9650           EPI.TypeQuals.addConst();
9651           FT = Context.getFunctionType(FPT->getReturnType(),
9652                                        FPT->getParamTypes(), EPI);
9653         }
9654       }
9655 
9656       TemplateArgumentListInfo Args;
9657       if (ExplicitTemplateArgs)
9658         Args = *ExplicitTemplateArgs;
9659 
9660       // C++ [temp.expl.spec]p11:
9661       //   A trailing template-argument can be left unspecified in the
9662       //   template-id naming an explicit function template specialization
9663       //   provided it can be deduced from the function argument type.
9664       // Perform template argument deduction to determine whether we may be
9665       // specializing this template.
9666       // FIXME: It is somewhat wasteful to build
9667       TemplateDeductionInfo Info(FailedCandidates.getLocation());
9668       FunctionDecl *Specialization = nullptr;
9669       if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9670               cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9671               ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
9672               Info)) {
9673         // Template argument deduction failed; record why it failed, so
9674         // that we can provide nifty diagnostics.
9675         FailedCandidates.addCandidate().set(
9676             I.getPair(), FunTmpl->getTemplatedDecl(),
9677             MakeDeductionFailureInfo(Context, TDK, Info));
9678         (void)TDK;
9679         continue;
9680       }
9681 
9682       // Target attributes are part of the cuda function signature, so
9683       // the deduced template's cuda target must match that of the
9684       // specialization.  Given that C++ template deduction does not
9685       // take target attributes into account, we reject candidates
9686       // here that have a different target.
9687       if (LangOpts.CUDA &&
9688           IdentifyCUDATarget(Specialization,
9689                              /* IgnoreImplicitHDAttr = */ true) !=
9690               IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9691         FailedCandidates.addCandidate().set(
9692             I.getPair(), FunTmpl->getTemplatedDecl(),
9693             MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9694         continue;
9695       }
9696 
9697       // Record this candidate.
9698       if (ExplicitTemplateArgs)
9699         ConvertedTemplateArgs[Specialization] = std::move(Args);
9700       Candidates.addDecl(Specialization, I.getAccess());
9701     }
9702   }
9703 
9704   // For a qualified friend declaration (with no explicit marker to indicate
9705   // that a template specialization was intended), note all (template and
9706   // non-template) candidates.
9707   if (QualifiedFriend && Candidates.empty()) {
9708     Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9709         << FD->getDeclName() << FDLookupContext;
9710     // FIXME: We should form a single candidate list and diagnose all
9711     // candidates at once, to get proper sorting and limiting.
9712     for (auto *OldND : Previous) {
9713       if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9714         NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9715     }
9716     FailedCandidates.NoteCandidates(*this, FD->getLocation());
9717     return true;
9718   }
9719 
9720   // Find the most specialized function template.
9721   UnresolvedSetIterator Result = getMostSpecialized(
9722       Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9723       PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9724       PDiag(diag::err_function_template_spec_ambiguous)
9725           << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9726       PDiag(diag::note_function_template_spec_matched));
9727 
9728   if (Result == Candidates.end())
9729     return true;
9730 
9731   // Ignore access information;  it doesn't figure into redeclaration checking.
9732   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
9733 
9734   FunctionTemplateSpecializationInfo *SpecInfo
9735     = Specialization->getTemplateSpecializationInfo();
9736   assert(SpecInfo && "Function template specialization info missing?");
9737 
9738   // Note: do not overwrite location info if previous template
9739   // specialization kind was explicit.
9740   TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9741   if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9742     Specialization->setLocation(FD->getLocation());
9743     Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9744     // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9745     // function can differ from the template declaration with respect to
9746     // the constexpr specifier.
9747     // FIXME: We need an update record for this AST mutation.
9748     // FIXME: What if there are multiple such prior declarations (for instance,
9749     // from different modules)?
9750     Specialization->setConstexprKind(FD->getConstexprKind());
9751   }
9752 
9753   // FIXME: Check if the prior specialization has a point of instantiation.
9754   // If so, we have run afoul of .
9755 
9756   // If this is a friend declaration, then we're not really declaring
9757   // an explicit specialization.
9758   bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9759 
9760   // Check the scope of this explicit specialization.
9761   if (!isFriend &&
9762       CheckTemplateSpecializationScope(*this,
9763                                        Specialization->getPrimaryTemplate(),
9764                                        Specialization, FD->getLocation(),
9765                                        false))
9766     return true;
9767 
9768   // C++ [temp.expl.spec]p6:
9769   //   If a template, a member template or the member of a class template is
9770   //   explicitly specialized then that specialization shall be declared
9771   //   before the first use of that specialization that would cause an implicit
9772   //   instantiation to take place, in every translation unit in which such a
9773   //   use occurs; no diagnostic is required.
9774   bool HasNoEffect = false;
9775   if (!isFriend &&
9776       CheckSpecializationInstantiationRedecl(FD->getLocation(),
9777                                              TSK_ExplicitSpecialization,
9778                                              Specialization,
9779                                    SpecInfo->getTemplateSpecializationKind(),
9780                                          SpecInfo->getPointOfInstantiation(),
9781                                              HasNoEffect))
9782     return true;
9783 
9784   // Mark the prior declaration as an explicit specialization, so that later
9785   // clients know that this is an explicit specialization.
9786   if (!isFriend) {
9787     // Since explicit specializations do not inherit '=delete' from their
9788     // primary function template - check if the 'specialization' that was
9789     // implicitly generated (during template argument deduction for partial
9790     // ordering) from the most specialized of all the function templates that
9791     // 'FD' could have been specializing, has a 'deleted' definition.  If so,
9792     // first check that it was implicitly generated during template argument
9793     // deduction by making sure it wasn't referenced, and then reset the deleted
9794     // flag to not-deleted, so that we can inherit that information from 'FD'.
9795     if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9796         !Specialization->getCanonicalDecl()->isReferenced()) {
9797       // FIXME: This assert will not hold in the presence of modules.
9798       assert(
9799           Specialization->getCanonicalDecl() == Specialization &&
9800           "This must be the only existing declaration of this specialization");
9801       // FIXME: We need an update record for this AST mutation.
9802       Specialization->setDeletedAsWritten(false);
9803     }
9804     // FIXME: We need an update record for this AST mutation.
9805     SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9806     MarkUnusedFileScopedDecl(Specialization);
9807   }
9808 
9809   // Turn the given function declaration into a function template
9810   // specialization, with the template arguments from the previous
9811   // specialization.
9812   // Take copies of (semantic and syntactic) template argument lists.
9813   const TemplateArgumentList* TemplArgs = new (Context)
9814     TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
9815   FD->setFunctionTemplateSpecialization(
9816       Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9817       SpecInfo->getTemplateSpecializationKind(),
9818       ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9819 
9820   // A function template specialization inherits the target attributes
9821   // of its template.  (We require the attributes explicitly in the
9822   // code to match, but a template may have implicit attributes by
9823   // virtue e.g. of being constexpr, and it passes these implicit
9824   // attributes on to its specializations.)
9825   if (LangOpts.CUDA)
9826     inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
9827 
9828   // The "previous declaration" for this function template specialization is
9829   // the prior function template specialization.
9830   Previous.clear();
9831   Previous.addDecl(Specialization);
9832   return false;
9833 }
9834 
9835 /// Perform semantic analysis for the given non-template member
9836 /// specialization.
9837 ///
9838 /// This routine performs all of the semantic analysis required for an
9839 /// explicit member function specialization. On successful completion,
9840 /// the function declaration \p FD will become a member function
9841 /// specialization.
9842 ///
9843 /// \param Member the member declaration, which will be updated to become a
9844 /// specialization.
9845 ///
9846 /// \param Previous the set of declarations, one of which may be specialized
9847 /// by this function specialization;  the set will be modified to contain the
9848 /// redeclared member.
9849 bool
CheckMemberSpecialization(NamedDecl * Member,LookupResult & Previous)9850 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9851   assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
9852 
9853   // Try to find the member we are instantiating.
9854   NamedDecl *FoundInstantiation = nullptr;
9855   NamedDecl *Instantiation = nullptr;
9856   NamedDecl *InstantiatedFrom = nullptr;
9857   MemberSpecializationInfo *MSInfo = nullptr;
9858 
9859   if (Previous.empty()) {
9860     // Nowhere to look anyway.
9861   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9862     for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9863            I != E; ++I) {
9864       NamedDecl *D = (*I)->getUnderlyingDecl();
9865       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
9866         QualType Adjusted = Function->getType();
9867         if (!hasExplicitCallingConv(Adjusted))
9868           Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9869         // This doesn't handle deduced return types, but both function
9870         // declarations should be undeduced at this point.
9871         if (Context.hasSameType(Adjusted, Method->getType())) {
9872           FoundInstantiation = *I;
9873           Instantiation = Method;
9874           InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
9875           MSInfo = Method->getMemberSpecializationInfo();
9876           break;
9877         }
9878       }
9879     }
9880   } else if (isa<VarDecl>(Member)) {
9881     VarDecl *PrevVar;
9882     if (Previous.isSingleResult() &&
9883         (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9884       if (PrevVar->isStaticDataMember()) {
9885         FoundInstantiation = Previous.getRepresentativeDecl();
9886         Instantiation = PrevVar;
9887         InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9888         MSInfo = PrevVar->getMemberSpecializationInfo();
9889       }
9890   } else if (isa<RecordDecl>(Member)) {
9891     CXXRecordDecl *PrevRecord;
9892     if (Previous.isSingleResult() &&
9893         (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9894       FoundInstantiation = Previous.getRepresentativeDecl();
9895       Instantiation = PrevRecord;
9896       InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9897       MSInfo = PrevRecord->getMemberSpecializationInfo();
9898     }
9899   } else if (isa<EnumDecl>(Member)) {
9900     EnumDecl *PrevEnum;
9901     if (Previous.isSingleResult() &&
9902         (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9903       FoundInstantiation = Previous.getRepresentativeDecl();
9904       Instantiation = PrevEnum;
9905       InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9906       MSInfo = PrevEnum->getMemberSpecializationInfo();
9907     }
9908   }
9909 
9910   if (!Instantiation) {
9911     // There is no previous declaration that matches. Since member
9912     // specializations are always out-of-line, the caller will complain about
9913     // this mismatch later.
9914     return false;
9915   }
9916 
9917   // A member specialization in a friend declaration isn't really declaring
9918   // an explicit specialization, just identifying a specific (possibly implicit)
9919   // specialization. Don't change the template specialization kind.
9920   //
9921   // FIXME: Is this really valid? Other compilers reject.
9922   if (Member->getFriendObjectKind() != Decl::FOK_None) {
9923     // Preserve instantiation information.
9924     if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9925       cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9926                                       cast<CXXMethodDecl>(InstantiatedFrom),
9927         cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
9928     } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9929       cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9930                                       cast<CXXRecordDecl>(InstantiatedFrom),
9931         cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
9932     }
9933 
9934     Previous.clear();
9935     Previous.addDecl(FoundInstantiation);
9936     return false;
9937   }
9938 
9939   // Make sure that this is a specialization of a member.
9940   if (!InstantiatedFrom) {
9941     Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9942       << Member;
9943     Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9944     return true;
9945   }
9946 
9947   // C++ [temp.expl.spec]p6:
9948   //   If a template, a member template or the member of a class template is
9949   //   explicitly specialized then that specialization shall be declared
9950   //   before the first use of that specialization that would cause an implicit
9951   //   instantiation to take place, in every translation unit in which such a
9952   //   use occurs; no diagnostic is required.
9953   assert(MSInfo && "Member specialization info missing?");
9954 
9955   bool HasNoEffect = false;
9956   if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
9957                                              TSK_ExplicitSpecialization,
9958                                              Instantiation,
9959                                      MSInfo->getTemplateSpecializationKind(),
9960                                            MSInfo->getPointOfInstantiation(),
9961                                              HasNoEffect))
9962     return true;
9963 
9964   // Check the scope of this explicit specialization.
9965   if (CheckTemplateSpecializationScope(*this,
9966                                        InstantiatedFrom,
9967                                        Instantiation, Member->getLocation(),
9968                                        false))
9969     return true;
9970 
9971   // Note that this member specialization is an "instantiation of" the
9972   // corresponding member of the original template.
9973   if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9974     FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9975     if (InstantiationFunction->getTemplateSpecializationKind() ==
9976           TSK_ImplicitInstantiation) {
9977       // Explicit specializations of member functions of class templates do not
9978       // inherit '=delete' from the member function they are specializing.
9979       if (InstantiationFunction->isDeleted()) {
9980         // FIXME: This assert will not hold in the presence of modules.
9981         assert(InstantiationFunction->getCanonicalDecl() ==
9982                InstantiationFunction);
9983         // FIXME: We need an update record for this AST mutation.
9984         InstantiationFunction->setDeletedAsWritten(false);
9985       }
9986     }
9987 
9988     MemberFunction->setInstantiationOfMemberFunction(
9989         cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9990   } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9991     MemberVar->setInstantiationOfStaticDataMember(
9992         cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9993   } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9994     MemberClass->setInstantiationOfMemberClass(
9995         cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9996   } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9997     MemberEnum->setInstantiationOfMemberEnum(
9998         cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9999   } else {
10000     llvm_unreachable("unknown member specialization kind");
10001   }
10002 
10003   // Save the caller the trouble of having to figure out which declaration
10004   // this specialization matches.
10005   Previous.clear();
10006   Previous.addDecl(FoundInstantiation);
10007   return false;
10008 }
10009 
10010 /// Complete the explicit specialization of a member of a class template by
10011 /// updating the instantiated member to be marked as an explicit specialization.
10012 ///
10013 /// \param OrigD The member declaration instantiated from the template.
10014 /// \param Loc The location of the explicit specialization of the member.
10015 template<typename DeclT>
completeMemberSpecializationImpl(Sema & S,DeclT * OrigD,SourceLocation Loc)10016 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10017                                              SourceLocation Loc) {
10018   if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10019     return;
10020 
10021   // FIXME: Inform AST mutation listeners of this AST mutation.
10022   // FIXME: If there are multiple in-class declarations of the member (from
10023   // multiple modules, or a declaration and later definition of a member type),
10024   // should we update all of them?
10025   OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10026   OrigD->setLocation(Loc);
10027 }
10028 
CompleteMemberSpecialization(NamedDecl * Member,LookupResult & Previous)10029 void Sema::CompleteMemberSpecialization(NamedDecl *Member,
10030                                         LookupResult &Previous) {
10031   NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10032   if (Instantiation == Member)
10033     return;
10034 
10035   if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10036     completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10037   else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10038     completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10039   else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10040     completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10041   else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10042     completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10043   else
10044     llvm_unreachable("unknown member specialization kind");
10045 }
10046 
10047 /// Check the scope of an explicit instantiation.
10048 ///
10049 /// \returns true if a serious error occurs, false otherwise.
CheckExplicitInstantiationScope(Sema & S,NamedDecl * D,SourceLocation InstLoc,bool WasQualifiedName)10050 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
10051                                             SourceLocation InstLoc,
10052                                             bool WasQualifiedName) {
10053   DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
10054   DeclContext *CurContext = S.CurContext->getRedeclContext();
10055 
10056   if (CurContext->isRecord()) {
10057     S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10058       << D;
10059     return true;
10060   }
10061 
10062   // C++11 [temp.explicit]p3:
10063   //   An explicit instantiation shall appear in an enclosing namespace of its
10064   //   template. If the name declared in the explicit instantiation is an
10065   //   unqualified name, the explicit instantiation shall appear in the
10066   //   namespace where its template is declared or, if that namespace is inline
10067   //   (7.3.1), any namespace from its enclosing namespace set.
10068   //
10069   // This is DR275, which we do not retroactively apply to C++98/03.
10070   if (WasQualifiedName) {
10071     if (CurContext->Encloses(OrigContext))
10072       return false;
10073   } else {
10074     if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10075       return false;
10076   }
10077 
10078   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10079     if (WasQualifiedName)
10080       S.Diag(InstLoc,
10081              S.getLangOpts().CPlusPlus11?
10082                diag::err_explicit_instantiation_out_of_scope :
10083                diag::warn_explicit_instantiation_out_of_scope_0x)
10084         << D << NS;
10085     else
10086       S.Diag(InstLoc,
10087              S.getLangOpts().CPlusPlus11?
10088                diag::err_explicit_instantiation_unqualified_wrong_namespace :
10089                diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10090         << D << NS;
10091   } else
10092     S.Diag(InstLoc,
10093            S.getLangOpts().CPlusPlus11?
10094              diag::err_explicit_instantiation_must_be_global :
10095              diag::warn_explicit_instantiation_must_be_global_0x)
10096       << D;
10097   S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10098   return false;
10099 }
10100 
10101 /// Common checks for whether an explicit instantiation of \p D is valid.
CheckExplicitInstantiation(Sema & S,NamedDecl * D,SourceLocation InstLoc,bool WasQualifiedName,TemplateSpecializationKind TSK)10102 static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
10103                                        SourceLocation InstLoc,
10104                                        bool WasQualifiedName,
10105                                        TemplateSpecializationKind TSK) {
10106   // C++ [temp.explicit]p13:
10107   //   An explicit instantiation declaration shall not name a specialization of
10108   //   a template with internal linkage.
10109   if (TSK == TSK_ExplicitInstantiationDeclaration &&
10110       D->getFormalLinkage() == Linkage::Internal) {
10111     S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10112     return true;
10113   }
10114 
10115   // C++11 [temp.explicit]p3: [DR 275]
10116   //   An explicit instantiation shall appear in an enclosing namespace of its
10117   //   template.
10118   if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10119     return true;
10120 
10121   return false;
10122 }
10123 
10124 /// Determine whether the given scope specifier has a template-id in it.
ScopeSpecifierHasTemplateId(const CXXScopeSpec & SS)10125 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
10126   if (!SS.isSet())
10127     return false;
10128 
10129   // C++11 [temp.explicit]p3:
10130   //   If the explicit instantiation is for a member function, a member class
10131   //   or a static data member of a class template specialization, the name of
10132   //   the class template specialization in the qualified-id for the member
10133   //   name shall be a simple-template-id.
10134   //
10135   // C++98 has the same restriction, just worded differently.
10136   for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
10137        NNS = NNS->getPrefix())
10138     if (const Type *T = NNS->getAsType())
10139       if (isa<TemplateSpecializationType>(T))
10140         return true;
10141 
10142   return false;
10143 }
10144 
10145 /// Make a dllexport or dllimport attr on a class template specialization take
10146 /// effect.
dllExportImportClassTemplateSpecialization(Sema & S,ClassTemplateSpecializationDecl * Def)10147 static void dllExportImportClassTemplateSpecialization(
10148     Sema &S, ClassTemplateSpecializationDecl *Def) {
10149   auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10150   assert(A && "dllExportImportClassTemplateSpecialization called "
10151               "on Def without dllexport or dllimport");
10152 
10153   // We reject explicit instantiations in class scope, so there should
10154   // never be any delayed exported classes to worry about.
10155   assert(S.DelayedDllExportClasses.empty() &&
10156          "delayed exports present at explicit instantiation");
10157   S.checkClassLevelDLLAttribute(Def);
10158 
10159   // Propagate attribute to base class templates.
10160   for (auto &B : Def->bases()) {
10161     if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10162             B.getType()->getAsCXXRecordDecl()))
10163       S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
10164   }
10165 
10166   S.referenceDLLExportedClassMethods();
10167 }
10168 
10169 // Explicit instantiation of a class template specialization
ActOnExplicitInstantiation(Scope * S,SourceLocation ExternLoc,SourceLocation TemplateLoc,unsigned TagSpec,SourceLocation KWLoc,const CXXScopeSpec & SS,TemplateTy TemplateD,SourceLocation TemplateNameLoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc,const ParsedAttributesView & Attr)10170 DeclResult Sema::ActOnExplicitInstantiation(
10171     Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10172     unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10173     TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10174     SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10175     SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10176   // Find the class template we're specializing
10177   TemplateName Name = TemplateD.get();
10178   TemplateDecl *TD = Name.getAsTemplateDecl();
10179   // Check that the specialization uses the same tag kind as the
10180   // original template.
10181   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10182   assert(Kind != TagTypeKind::Enum &&
10183          "Invalid enum tag in class template explicit instantiation!");
10184 
10185   ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10186 
10187   if (!ClassTemplate) {
10188     NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10189     Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
10190         << TD << NTK << llvm::to_underlying(Kind);
10191     Diag(TD->getLocation(), diag::note_previous_use);
10192     return true;
10193   }
10194 
10195   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10196                                     Kind, /*isDefinition*/false, KWLoc,
10197                                     ClassTemplate->getIdentifier())) {
10198     Diag(KWLoc, diag::err_use_with_wrong_tag)
10199       << ClassTemplate
10200       << FixItHint::CreateReplacement(KWLoc,
10201                             ClassTemplate->getTemplatedDecl()->getKindName());
10202     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10203          diag::note_previous_use);
10204     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10205   }
10206 
10207   // C++0x [temp.explicit]p2:
10208   //   There are two forms of explicit instantiation: an explicit instantiation
10209   //   definition and an explicit instantiation declaration. An explicit
10210   //   instantiation declaration begins with the extern keyword. [...]
10211   TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10212                                        ? TSK_ExplicitInstantiationDefinition
10213                                        : TSK_ExplicitInstantiationDeclaration;
10214 
10215   if (TSK == TSK_ExplicitInstantiationDeclaration &&
10216       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
10217     // Check for dllexport class template instantiation declarations,
10218     // except for MinGW mode.
10219     for (const ParsedAttr &AL : Attr) {
10220       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10221         Diag(ExternLoc,
10222              diag::warn_attribute_dllexport_explicit_instantiation_decl);
10223         Diag(AL.getLoc(), diag::note_attribute);
10224         break;
10225       }
10226     }
10227 
10228     if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10229       Diag(ExternLoc,
10230            diag::warn_attribute_dllexport_explicit_instantiation_decl);
10231       Diag(A->getLocation(), diag::note_attribute);
10232     }
10233   }
10234 
10235   // In MSVC mode, dllimported explicit instantiation definitions are treated as
10236   // instantiation declarations for most purposes.
10237   bool DLLImportExplicitInstantiationDef = false;
10238   if (TSK == TSK_ExplicitInstantiationDefinition &&
10239       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10240     // Check for dllimport class template instantiation definitions.
10241     bool DLLImport =
10242         ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10243     for (const ParsedAttr &AL : Attr) {
10244       if (AL.getKind() == ParsedAttr::AT_DLLImport)
10245         DLLImport = true;
10246       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10247         // dllexport trumps dllimport here.
10248         DLLImport = false;
10249         break;
10250       }
10251     }
10252     if (DLLImport) {
10253       TSK = TSK_ExplicitInstantiationDeclaration;
10254       DLLImportExplicitInstantiationDef = true;
10255     }
10256   }
10257 
10258   // Translate the parser's template argument list in our AST format.
10259   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10260   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10261 
10262   // Check that the template argument list is well-formed for this
10263   // template.
10264   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
10265   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10266                                 false, SugaredConverted, CanonicalConverted,
10267                                 /*UpdateArgsWithConversions=*/true))
10268     return true;
10269 
10270   // Find the class template specialization declaration that
10271   // corresponds to these arguments.
10272   void *InsertPos = nullptr;
10273   ClassTemplateSpecializationDecl *PrevDecl =
10274       ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
10275 
10276   TemplateSpecializationKind PrevDecl_TSK
10277     = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10278 
10279   if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10280       Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
10281     // Check for dllexport class template instantiation definitions in MinGW
10282     // mode, if a previous declaration of the instantiation was seen.
10283     for (const ParsedAttr &AL : Attr) {
10284       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10285         Diag(AL.getLoc(),
10286              diag::warn_attribute_dllexport_explicit_instantiation_def);
10287         break;
10288       }
10289     }
10290   }
10291 
10292   if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10293                                  SS.isSet(), TSK))
10294     return true;
10295 
10296   ClassTemplateSpecializationDecl *Specialization = nullptr;
10297 
10298   bool HasNoEffect = false;
10299   if (PrevDecl) {
10300     if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10301                                                PrevDecl, PrevDecl_TSK,
10302                                             PrevDecl->getPointOfInstantiation(),
10303                                                HasNoEffect))
10304       return PrevDecl;
10305 
10306     // Even though HasNoEffect == true means that this explicit instantiation
10307     // has no effect on semantics, we go on to put its syntax in the AST.
10308 
10309     if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10310         PrevDecl_TSK == TSK_Undeclared) {
10311       // Since the only prior class template specialization with these
10312       // arguments was referenced but not declared, reuse that
10313       // declaration node as our own, updating the source location
10314       // for the template name to reflect our new declaration.
10315       // (Other source locations will be updated later.)
10316       Specialization = PrevDecl;
10317       Specialization->setLocation(TemplateNameLoc);
10318       PrevDecl = nullptr;
10319     }
10320 
10321     if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10322         DLLImportExplicitInstantiationDef) {
10323       // The new specialization might add a dllimport attribute.
10324       HasNoEffect = false;
10325     }
10326   }
10327 
10328   if (!Specialization) {
10329     // Create a new class template specialization declaration node for
10330     // this explicit specialization.
10331     Specialization = ClassTemplateSpecializationDecl::Create(
10332         Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10333         ClassTemplate, CanonicalConverted, PrevDecl);
10334     SetNestedNameSpecifier(*this, Specialization, SS);
10335 
10336     // A MSInheritanceAttr attached to the previous declaration must be
10337     // propagated to the new node prior to instantiation.
10338     if (PrevDecl) {
10339       if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10340         auto *Clone = A->clone(getASTContext());
10341         Clone->setInherited(true);
10342         Specialization->addAttr(Clone);
10343         Consumer.AssignInheritanceModel(Specialization);
10344       }
10345     }
10346 
10347     if (!HasNoEffect && !PrevDecl) {
10348       // Insert the new specialization.
10349       ClassTemplate->AddSpecialization(Specialization, InsertPos);
10350     }
10351   }
10352 
10353   // Build the fully-sugared type for this explicit instantiation as
10354   // the user wrote in the explicit instantiation itself. This means
10355   // that we'll pretty-print the type retrieved from the
10356   // specialization's declaration the way that the user actually wrote
10357   // the explicit instantiation, rather than formatting the name based
10358   // on the "canonical" representation used to store the template
10359   // arguments in the specialization.
10360   TypeSourceInfo *WrittenTy
10361     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
10362                                                 TemplateArgs,
10363                                   Context.getTypeDeclType(Specialization));
10364   Specialization->setTypeAsWritten(WrittenTy);
10365 
10366   // Set source locations for keywords.
10367   Specialization->setExternLoc(ExternLoc);
10368   Specialization->setTemplateKeywordLoc(TemplateLoc);
10369   Specialization->setBraceRange(SourceRange());
10370 
10371   bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10372   ProcessDeclAttributeList(S, Specialization, Attr);
10373 
10374   // Add the explicit instantiation into its lexical context. However,
10375   // since explicit instantiations are never found by name lookup, we
10376   // just put it into the declaration context directly.
10377   Specialization->setLexicalDeclContext(CurContext);
10378   CurContext->addDecl(Specialization);
10379 
10380   // Syntax is now OK, so return if it has no other effect on semantics.
10381   if (HasNoEffect) {
10382     // Set the template specialization kind.
10383     Specialization->setTemplateSpecializationKind(TSK);
10384     return Specialization;
10385   }
10386 
10387   // C++ [temp.explicit]p3:
10388   //   A definition of a class template or class member template
10389   //   shall be in scope at the point of the explicit instantiation of
10390   //   the class template or class member template.
10391   //
10392   // This check comes when we actually try to perform the
10393   // instantiation.
10394   ClassTemplateSpecializationDecl *Def
10395     = cast_or_null<ClassTemplateSpecializationDecl>(
10396                                               Specialization->getDefinition());
10397   if (!Def)
10398     InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
10399   else if (TSK == TSK_ExplicitInstantiationDefinition) {
10400     MarkVTableUsed(TemplateNameLoc, Specialization, true);
10401     Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10402   }
10403 
10404   // Instantiate the members of this class template specialization.
10405   Def = cast_or_null<ClassTemplateSpecializationDecl>(
10406                                        Specialization->getDefinition());
10407   if (Def) {
10408     TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10409     // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10410     // TSK_ExplicitInstantiationDefinition
10411     if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10412         (TSK == TSK_ExplicitInstantiationDefinition ||
10413          DLLImportExplicitInstantiationDef)) {
10414       // FIXME: Need to notify the ASTMutationListener that we did this.
10415       Def->setTemplateSpecializationKind(TSK);
10416 
10417       if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10418           (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
10419            !Context.getTargetInfo().getTriple().isPS())) {
10420         // An explicit instantiation definition can add a dll attribute to a
10421         // template with a previous instantiation declaration. MinGW doesn't
10422         // allow this.
10423         auto *A = cast<InheritableAttr>(
10424             getDLLAttr(Specialization)->clone(getASTContext()));
10425         A->setInherited(true);
10426         Def->addAttr(A);
10427         dllExportImportClassTemplateSpecialization(*this, Def);
10428       }
10429     }
10430 
10431     // Fix a TSK_ImplicitInstantiation followed by a
10432     // TSK_ExplicitInstantiationDefinition
10433     bool NewlyDLLExported =
10434         !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10435     if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10436         (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
10437          !Context.getTargetInfo().getTriple().isPS())) {
10438       // An explicit instantiation definition can add a dll attribute to a
10439       // template with a previous implicit instantiation. MinGW doesn't allow
10440       // this. We limit clang to only adding dllexport, to avoid potentially
10441       // strange codegen behavior. For example, if we extend this conditional
10442       // to dllimport, and we have a source file calling a method on an
10443       // implicitly instantiated template class instance and then declaring a
10444       // dllimport explicit instantiation definition for the same template
10445       // class, the codegen for the method call will not respect the dllimport,
10446       // while it will with cl. The Def will already have the DLL attribute,
10447       // since the Def and Specialization will be the same in the case of
10448       // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10449       // attribute to the Specialization; we just need to make it take effect.
10450       assert(Def == Specialization &&
10451              "Def and Specialization should match for implicit instantiation");
10452       dllExportImportClassTemplateSpecialization(*this, Def);
10453     }
10454 
10455     // In MinGW mode, export the template instantiation if the declaration
10456     // was marked dllexport.
10457     if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10458         Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10459         PrevDecl->hasAttr<DLLExportAttr>()) {
10460       dllExportImportClassTemplateSpecialization(*this, Def);
10461     }
10462 
10463     // Set the template specialization kind. Make sure it is set before
10464     // instantiating the members which will trigger ASTConsumer callbacks.
10465     Specialization->setTemplateSpecializationKind(TSK);
10466     InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10467   } else {
10468 
10469     // Set the template specialization kind.
10470     Specialization->setTemplateSpecializationKind(TSK);
10471   }
10472 
10473   return Specialization;
10474 }
10475 
10476 // Explicit instantiation of a member class of a class template.
10477 DeclResult
ActOnExplicitInstantiation(Scope * S,SourceLocation ExternLoc,SourceLocation TemplateLoc,unsigned TagSpec,SourceLocation KWLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,const ParsedAttributesView & Attr)10478 Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10479                                  SourceLocation TemplateLoc, unsigned TagSpec,
10480                                  SourceLocation KWLoc, CXXScopeSpec &SS,
10481                                  IdentifierInfo *Name, SourceLocation NameLoc,
10482                                  const ParsedAttributesView &Attr) {
10483 
10484   bool Owned = false;
10485   bool IsDependent = false;
10486   Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name,
10487                NameLoc, Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10488                MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10489                false, TypeResult(), /*IsTypeSpecifier*/ false,
10490                /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get();
10491   assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10492 
10493   if (!TagD)
10494     return true;
10495 
10496   TagDecl *Tag = cast<TagDecl>(TagD);
10497   assert(!Tag->isEnum() && "shouldn't see enumerations here");
10498 
10499   if (Tag->isInvalidDecl())
10500     return true;
10501 
10502   CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
10503   CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10504   if (!Pattern) {
10505     Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10506       << Context.getTypeDeclType(Record);
10507     Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10508     return true;
10509   }
10510 
10511   // C++0x [temp.explicit]p2:
10512   //   If the explicit instantiation is for a class or member class, the
10513   //   elaborated-type-specifier in the declaration shall include a
10514   //   simple-template-id.
10515   //
10516   // C++98 has the same restriction, just worded differently.
10517   if (!ScopeSpecifierHasTemplateId(SS))
10518     Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10519       << Record << SS.getRange();
10520 
10521   // C++0x [temp.explicit]p2:
10522   //   There are two forms of explicit instantiation: an explicit instantiation
10523   //   definition and an explicit instantiation declaration. An explicit
10524   //   instantiation declaration begins with the extern keyword. [...]
10525   TemplateSpecializationKind TSK
10526     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10527                            : TSK_ExplicitInstantiationDeclaration;
10528 
10529   CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10530 
10531   // Verify that it is okay to explicitly instantiate here.
10532   CXXRecordDecl *PrevDecl
10533     = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10534   if (!PrevDecl && Record->getDefinition())
10535     PrevDecl = Record;
10536   if (PrevDecl) {
10537     MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10538     bool HasNoEffect = false;
10539     assert(MSInfo && "No member specialization information?");
10540     if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10541                                                PrevDecl,
10542                                         MSInfo->getTemplateSpecializationKind(),
10543                                              MSInfo->getPointOfInstantiation(),
10544                                                HasNoEffect))
10545       return true;
10546     if (HasNoEffect)
10547       return TagD;
10548   }
10549 
10550   CXXRecordDecl *RecordDef
10551     = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10552   if (!RecordDef) {
10553     // C++ [temp.explicit]p3:
10554     //   A definition of a member class of a class template shall be in scope
10555     //   at the point of an explicit instantiation of the member class.
10556     CXXRecordDecl *Def
10557       = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10558     if (!Def) {
10559       Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10560         << 0 << Record->getDeclName() << Record->getDeclContext();
10561       Diag(Pattern->getLocation(), diag::note_forward_declaration)
10562         << Pattern;
10563       return true;
10564     } else {
10565       if (InstantiateClass(NameLoc, Record, Def,
10566                            getTemplateInstantiationArgs(Record),
10567                            TSK))
10568         return true;
10569 
10570       RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10571       if (!RecordDef)
10572         return true;
10573     }
10574   }
10575 
10576   // Instantiate all of the members of the class.
10577   InstantiateClassMembers(NameLoc, RecordDef,
10578                           getTemplateInstantiationArgs(Record), TSK);
10579 
10580   if (TSK == TSK_ExplicitInstantiationDefinition)
10581     MarkVTableUsed(NameLoc, RecordDef, true);
10582 
10583   // FIXME: We don't have any representation for explicit instantiations of
10584   // member classes. Such a representation is not needed for compilation, but it
10585   // should be available for clients that want to see all of the declarations in
10586   // the source code.
10587   return TagD;
10588 }
10589 
ActOnExplicitInstantiation(Scope * S,SourceLocation ExternLoc,SourceLocation TemplateLoc,Declarator & D)10590 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10591                                             SourceLocation ExternLoc,
10592                                             SourceLocation TemplateLoc,
10593                                             Declarator &D) {
10594   // Explicit instantiations always require a name.
10595   // TODO: check if/when DNInfo should replace Name.
10596   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10597   DeclarationName Name = NameInfo.getName();
10598   if (!Name) {
10599     if (!D.isInvalidType())
10600       Diag(D.getDeclSpec().getBeginLoc(),
10601            diag::err_explicit_instantiation_requires_name)
10602           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10603 
10604     return true;
10605   }
10606 
10607   // The scope passed in may not be a decl scope.  Zip up the scope tree until
10608   // we find one that is.
10609   while ((S->getFlags() & Scope::DeclScope) == 0 ||
10610          (S->getFlags() & Scope::TemplateParamScope) != 0)
10611     S = S->getParent();
10612 
10613   // Determine the type of the declaration.
10614   TypeSourceInfo *T = GetTypeForDeclarator(D);
10615   QualType R = T->getType();
10616   if (R.isNull())
10617     return true;
10618 
10619   // C++ [dcl.stc]p1:
10620   //   A storage-class-specifier shall not be specified in [...] an explicit
10621   //   instantiation (14.7.2) directive.
10622   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10623     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10624       << Name;
10625     return true;
10626   } else if (D.getDeclSpec().getStorageClassSpec()
10627                                                 != DeclSpec::SCS_unspecified) {
10628     // Complain about then remove the storage class specifier.
10629     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10630       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10631 
10632     D.getMutableDeclSpec().ClearStorageClassSpecs();
10633   }
10634 
10635   // C++0x [temp.explicit]p1:
10636   //   [...] An explicit instantiation of a function template shall not use the
10637   //   inline or constexpr specifiers.
10638   // Presumably, this also applies to member functions of class templates as
10639   // well.
10640   if (D.getDeclSpec().isInlineSpecified())
10641     Diag(D.getDeclSpec().getInlineSpecLoc(),
10642          getLangOpts().CPlusPlus11 ?
10643            diag::err_explicit_instantiation_inline :
10644            diag::warn_explicit_instantiation_inline_0x)
10645       << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10646   if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10647     // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10648     // not already specified.
10649     Diag(D.getDeclSpec().getConstexprSpecLoc(),
10650          diag::err_explicit_instantiation_constexpr);
10651 
10652   // A deduction guide is not on the list of entities that can be explicitly
10653   // instantiated.
10654   if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10655     Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10656         << /*explicit instantiation*/ 0;
10657     return true;
10658   }
10659 
10660   // C++0x [temp.explicit]p2:
10661   //   There are two forms of explicit instantiation: an explicit instantiation
10662   //   definition and an explicit instantiation declaration. An explicit
10663   //   instantiation declaration begins with the extern keyword. [...]
10664   TemplateSpecializationKind TSK
10665     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10666                            : TSK_ExplicitInstantiationDeclaration;
10667 
10668   LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10669   LookupParsedName(Previous, S, &D.getCXXScopeSpec());
10670 
10671   if (!R->isFunctionType()) {
10672     // C++ [temp.explicit]p1:
10673     //   A [...] static data member of a class template can be explicitly
10674     //   instantiated from the member definition associated with its class
10675     //   template.
10676     // C++1y [temp.explicit]p1:
10677     //   A [...] variable [...] template specialization can be explicitly
10678     //   instantiated from its template.
10679     if (Previous.isAmbiguous())
10680       return true;
10681 
10682     VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10683     VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10684 
10685     if (!PrevTemplate) {
10686       if (!Prev || !Prev->isStaticDataMember()) {
10687         // We expect to see a static data member here.
10688         Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10689             << Name;
10690         for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10691              P != PEnd; ++P)
10692           Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10693         return true;
10694       }
10695 
10696       if (!Prev->getInstantiatedFromStaticDataMember()) {
10697         // FIXME: Check for explicit specialization?
10698         Diag(D.getIdentifierLoc(),
10699              diag::err_explicit_instantiation_data_member_not_instantiated)
10700             << Prev;
10701         Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10702         // FIXME: Can we provide a note showing where this was declared?
10703         return true;
10704       }
10705     } else {
10706       // Explicitly instantiate a variable template.
10707 
10708       // C++1y [dcl.spec.auto]p6:
10709       //   ... A program that uses auto or decltype(auto) in a context not
10710       //   explicitly allowed in this section is ill-formed.
10711       //
10712       // This includes auto-typed variable template instantiations.
10713       if (R->isUndeducedType()) {
10714         Diag(T->getTypeLoc().getBeginLoc(),
10715              diag::err_auto_not_allowed_var_inst);
10716         return true;
10717       }
10718 
10719       if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10720         // C++1y [temp.explicit]p3:
10721         //   If the explicit instantiation is for a variable, the unqualified-id
10722         //   in the declaration shall be a template-id.
10723         Diag(D.getIdentifierLoc(),
10724              diag::err_explicit_instantiation_without_template_id)
10725           << PrevTemplate;
10726         Diag(PrevTemplate->getLocation(),
10727              diag::note_explicit_instantiation_here);
10728         return true;
10729       }
10730 
10731       // Translate the parser's template argument list into our AST format.
10732       TemplateArgumentListInfo TemplateArgs =
10733           makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10734 
10735       DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
10736                                           D.getIdentifierLoc(), TemplateArgs);
10737       if (Res.isInvalid())
10738         return true;
10739 
10740       if (!Res.isUsable()) {
10741         // We somehow specified dependent template arguments in an explicit
10742         // instantiation. This should probably only happen during error
10743         // recovery.
10744         Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10745         return true;
10746       }
10747 
10748       // Ignore access control bits, we don't need them for redeclaration
10749       // checking.
10750       Prev = cast<VarDecl>(Res.get());
10751     }
10752 
10753     // C++0x [temp.explicit]p2:
10754     //   If the explicit instantiation is for a member function, a member class
10755     //   or a static data member of a class template specialization, the name of
10756     //   the class template specialization in the qualified-id for the member
10757     //   name shall be a simple-template-id.
10758     //
10759     // C++98 has the same restriction, just worded differently.
10760     //
10761     // This does not apply to variable template specializations, where the
10762     // template-id is in the unqualified-id instead.
10763     if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10764       Diag(D.getIdentifierLoc(),
10765            diag::ext_explicit_instantiation_without_qualified_id)
10766         << Prev << D.getCXXScopeSpec().getRange();
10767 
10768     CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10769 
10770     // Verify that it is okay to explicitly instantiate here.
10771     TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10772     SourceLocation POI = Prev->getPointOfInstantiation();
10773     bool HasNoEffect = false;
10774     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
10775                                                PrevTSK, POI, HasNoEffect))
10776       return true;
10777 
10778     if (!HasNoEffect) {
10779       // Instantiate static data member or variable template.
10780       Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10781       // Merge attributes.
10782       ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10783       if (TSK == TSK_ExplicitInstantiationDefinition)
10784         InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
10785     }
10786 
10787     // Check the new variable specialization against the parsed input.
10788     if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10789       Diag(T->getTypeLoc().getBeginLoc(),
10790            diag::err_invalid_var_template_spec_type)
10791           << 0 << PrevTemplate << R << Prev->getType();
10792       Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10793           << 2 << PrevTemplate->getDeclName();
10794       return true;
10795     }
10796 
10797     // FIXME: Create an ExplicitInstantiation node?
10798     return (Decl*) nullptr;
10799   }
10800 
10801   // If the declarator is a template-id, translate the parser's template
10802   // argument list into our AST format.
10803   bool HasExplicitTemplateArgs = false;
10804   TemplateArgumentListInfo TemplateArgs;
10805   if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10806     TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10807     HasExplicitTemplateArgs = true;
10808   }
10809 
10810   // C++ [temp.explicit]p1:
10811   //   A [...] function [...] can be explicitly instantiated from its template.
10812   //   A member function [...] of a class template can be explicitly
10813   //  instantiated from the member definition associated with its class
10814   //  template.
10815   UnresolvedSet<8> TemplateMatches;
10816   FunctionDecl *NonTemplateMatch = nullptr;
10817   TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
10818   for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10819        P != PEnd; ++P) {
10820     NamedDecl *Prev = *P;
10821     if (!HasExplicitTemplateArgs) {
10822       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10823         QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10824                                                 /*AdjustExceptionSpec*/true);
10825         if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10826           if (Method->getPrimaryTemplate()) {
10827             TemplateMatches.addDecl(Method, P.getAccess());
10828           } else {
10829             // FIXME: Can this assert ever happen?  Needs a test.
10830             assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
10831             NonTemplateMatch = Method;
10832           }
10833         }
10834       }
10835     }
10836 
10837     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10838     if (!FunTmpl)
10839       continue;
10840 
10841     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10842     FunctionDecl *Specialization = nullptr;
10843     if (TemplateDeductionResult TDK
10844           = DeduceTemplateArguments(FunTmpl,
10845                                (HasExplicitTemplateArgs ? &TemplateArgs
10846                                                         : nullptr),
10847                                     R, Specialization, Info)) {
10848       // Keep track of almost-matches.
10849       FailedCandidates.addCandidate()
10850           .set(P.getPair(), FunTmpl->getTemplatedDecl(),
10851                MakeDeductionFailureInfo(Context, TDK, Info));
10852       (void)TDK;
10853       continue;
10854     }
10855 
10856     // Target attributes are part of the cuda function signature, so
10857     // the cuda target of the instantiated function must match that of its
10858     // template.  Given that C++ template deduction does not take
10859     // target attributes into account, we reject candidates here that
10860     // have a different target.
10861     if (LangOpts.CUDA &&
10862         IdentifyCUDATarget(Specialization,
10863                            /* IgnoreImplicitHDAttr = */ true) !=
10864             IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
10865       FailedCandidates.addCandidate().set(
10866           P.getPair(), FunTmpl->getTemplatedDecl(),
10867           MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
10868       continue;
10869     }
10870 
10871     TemplateMatches.addDecl(Specialization, P.getAccess());
10872   }
10873 
10874   FunctionDecl *Specialization = NonTemplateMatch;
10875   if (!Specialization) {
10876     // Find the most specialized function template specialization.
10877     UnresolvedSetIterator Result = getMostSpecialized(
10878         TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
10879         D.getIdentifierLoc(),
10880         PDiag(diag::err_explicit_instantiation_not_known) << Name,
10881         PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10882         PDiag(diag::note_explicit_instantiation_candidate));
10883 
10884     if (Result == TemplateMatches.end())
10885       return true;
10886 
10887     // Ignore access control bits, we don't need them for redeclaration checking.
10888     Specialization = cast<FunctionDecl>(*Result);
10889   }
10890 
10891   // C++11 [except.spec]p4
10892   // In an explicit instantiation an exception-specification may be specified,
10893   // but is not required.
10894   // If an exception-specification is specified in an explicit instantiation
10895   // directive, it shall be compatible with the exception-specifications of
10896   // other declarations of that function.
10897   if (auto *FPT = R->getAs<FunctionProtoType>())
10898     if (FPT->hasExceptionSpec()) {
10899       unsigned DiagID =
10900           diag::err_mismatched_exception_spec_explicit_instantiation;
10901       if (getLangOpts().MicrosoftExt)
10902         DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10903       bool Result = CheckEquivalentExceptionSpec(
10904           PDiag(DiagID) << Specialization->getType(),
10905           PDiag(diag::note_explicit_instantiation_here),
10906           Specialization->getType()->getAs<FunctionProtoType>(),
10907           Specialization->getLocation(), FPT, D.getBeginLoc());
10908       // In Microsoft mode, mismatching exception specifications just cause a
10909       // warning.
10910       if (!getLangOpts().MicrosoftExt && Result)
10911         return true;
10912     }
10913 
10914   if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10915     Diag(D.getIdentifierLoc(),
10916          diag::err_explicit_instantiation_member_function_not_instantiated)
10917       << Specialization
10918       << (Specialization->getTemplateSpecializationKind() ==
10919           TSK_ExplicitSpecialization);
10920     Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10921     return true;
10922   }
10923 
10924   FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10925   if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10926     PrevDecl = Specialization;
10927 
10928   if (PrevDecl) {
10929     bool HasNoEffect = false;
10930     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10931                                                PrevDecl,
10932                                      PrevDecl->getTemplateSpecializationKind(),
10933                                           PrevDecl->getPointOfInstantiation(),
10934                                                HasNoEffect))
10935       return true;
10936 
10937     // FIXME: We may still want to build some representation of this
10938     // explicit specialization.
10939     if (HasNoEffect)
10940       return (Decl*) nullptr;
10941   }
10942 
10943   // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10944   // functions
10945   //     valarray<size_t>::valarray(size_t) and
10946   //     valarray<size_t>::~valarray()
10947   // that it declared to have internal linkage with the internal_linkage
10948   // attribute. Ignore the explicit instantiation declaration in this case.
10949   if (Specialization->hasAttr<InternalLinkageAttr>() &&
10950       TSK == TSK_ExplicitInstantiationDeclaration) {
10951     if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10952       if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10953           RD->isInStdNamespace())
10954         return (Decl*) nullptr;
10955   }
10956 
10957   ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10958 
10959   // In MSVC mode, dllimported explicit instantiation definitions are treated as
10960   // instantiation declarations.
10961   if (TSK == TSK_ExplicitInstantiationDefinition &&
10962       Specialization->hasAttr<DLLImportAttr>() &&
10963       Context.getTargetInfo().getCXXABI().isMicrosoft())
10964     TSK = TSK_ExplicitInstantiationDeclaration;
10965 
10966   Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10967 
10968   if (Specialization->isDefined()) {
10969     // Let the ASTConsumer know that this function has been explicitly
10970     // instantiated now, and its linkage might have changed.
10971     Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
10972   } else if (TSK == TSK_ExplicitInstantiationDefinition)
10973     InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10974 
10975   // C++0x [temp.explicit]p2:
10976   //   If the explicit instantiation is for a member function, a member class
10977   //   or a static data member of a class template specialization, the name of
10978   //   the class template specialization in the qualified-id for the member
10979   //   name shall be a simple-template-id.
10980   //
10981   // C++98 has the same restriction, just worded differently.
10982   FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10983   if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10984       D.getCXXScopeSpec().isSet() &&
10985       !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10986     Diag(D.getIdentifierLoc(),
10987          diag::ext_explicit_instantiation_without_qualified_id)
10988     << Specialization << D.getCXXScopeSpec().getRange();
10989 
10990   CheckExplicitInstantiation(
10991       *this,
10992       FunTmpl ? (NamedDecl *)FunTmpl
10993               : Specialization->getInstantiatedFromMemberFunction(),
10994       D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10995 
10996   // FIXME: Create some kind of ExplicitInstantiationDecl here.
10997   return (Decl*) nullptr;
10998 }
10999 
11000 TypeResult
ActOnDependentTag(Scope * S,unsigned TagSpec,TagUseKind TUK,const CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation TagLoc,SourceLocation NameLoc)11001 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11002                         const CXXScopeSpec &SS, IdentifierInfo *Name,
11003                         SourceLocation TagLoc, SourceLocation NameLoc) {
11004   // This has to hold, because SS is expected to be defined.
11005   assert(Name && "Expected a name in a dependent tag");
11006 
11007   NestedNameSpecifier *NNS = SS.getScopeRep();
11008   if (!NNS)
11009     return true;
11010 
11011   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11012 
11013   if (TUK == TUK_Declaration || TUK == TUK_Definition) {
11014     Diag(NameLoc, diag::err_dependent_tag_decl)
11015         << (TUK == TUK_Definition) << llvm::to_underlying(Kind)
11016         << SS.getRange();
11017     return true;
11018   }
11019 
11020   // Create the resulting type.
11021   ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11022   QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11023 
11024   // Create type-source location information for this type.
11025   TypeLocBuilder TLB;
11026   DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
11027   TL.setElaboratedKeywordLoc(TagLoc);
11028   TL.setQualifierLoc(SS.getWithLocInContext(Context));
11029   TL.setNameLoc(NameLoc);
11030   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
11031 }
11032 
ActOnTypenameType(Scope * S,SourceLocation TypenameLoc,const CXXScopeSpec & SS,const IdentifierInfo & II,SourceLocation IdLoc,ImplicitTypenameContext IsImplicitTypename)11033 TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11034                                    const CXXScopeSpec &SS,
11035                                    const IdentifierInfo &II,
11036                                    SourceLocation IdLoc,
11037                                    ImplicitTypenameContext IsImplicitTypename) {
11038   if (SS.isInvalid())
11039     return true;
11040 
11041   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11042     Diag(TypenameLoc,
11043          getLangOpts().CPlusPlus11 ?
11044            diag::warn_cxx98_compat_typename_outside_of_template :
11045            diag::ext_typename_outside_of_template)
11046       << FixItHint::CreateRemoval(TypenameLoc);
11047 
11048   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11049   TypeSourceInfo *TSI = nullptr;
11050   QualType T =
11051       CheckTypenameType((TypenameLoc.isValid() ||
11052                          IsImplicitTypename == ImplicitTypenameContext::Yes)
11053                             ? ElaboratedTypeKeyword::Typename
11054                             : ElaboratedTypeKeyword::None,
11055                         TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11056                         /*DeducedTSTContext=*/true);
11057   if (T.isNull())
11058     return true;
11059   return CreateParsedType(T, TSI);
11060 }
11061 
11062 TypeResult
ActOnTypenameType(Scope * S,SourceLocation TypenameLoc,const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,TemplateTy TemplateIn,IdentifierInfo * TemplateII,SourceLocation TemplateIILoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc)11063 Sema::ActOnTypenameType(Scope *S,
11064                         SourceLocation TypenameLoc,
11065                         const CXXScopeSpec &SS,
11066                         SourceLocation TemplateKWLoc,
11067                         TemplateTy TemplateIn,
11068                         IdentifierInfo *TemplateII,
11069                         SourceLocation TemplateIILoc,
11070                         SourceLocation LAngleLoc,
11071                         ASTTemplateArgsPtr TemplateArgsIn,
11072                         SourceLocation RAngleLoc) {
11073   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11074     Diag(TypenameLoc,
11075          getLangOpts().CPlusPlus11 ?
11076            diag::warn_cxx98_compat_typename_outside_of_template :
11077            diag::ext_typename_outside_of_template)
11078       << FixItHint::CreateRemoval(TypenameLoc);
11079 
11080   // Strangely, non-type results are not ignored by this lookup, so the
11081   // program is ill-formed if it finds an injected-class-name.
11082   if (TypenameLoc.isValid()) {
11083     auto *LookupRD =
11084         dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11085     if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11086       Diag(TemplateIILoc,
11087            diag::ext_out_of_line_qualified_id_type_names_constructor)
11088         << TemplateII << 0 /*injected-class-name used as template name*/
11089         << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11090     }
11091   }
11092 
11093   // Translate the parser's template argument list in our AST format.
11094   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11095   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11096 
11097   TemplateName Template = TemplateIn.get();
11098   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
11099     // Construct a dependent template specialization type.
11100     assert(DTN && "dependent template has non-dependent name?");
11101     assert(DTN->getQualifier() == SS.getScopeRep());
11102     QualType T = Context.getDependentTemplateSpecializationType(
11103         ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
11104         DTN->getIdentifier(), TemplateArgs.arguments());
11105 
11106     // Create source-location information for this type.
11107     TypeLocBuilder Builder;
11108     DependentTemplateSpecializationTypeLoc SpecTL
11109     = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
11110     SpecTL.setElaboratedKeywordLoc(TypenameLoc);
11111     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
11112     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
11113     SpecTL.setTemplateNameLoc(TemplateIILoc);
11114     SpecTL.setLAngleLoc(LAngleLoc);
11115     SpecTL.setRAngleLoc(RAngleLoc);
11116     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
11117       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
11118     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
11119   }
11120 
11121   QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
11122   if (T.isNull())
11123     return true;
11124 
11125   // Provide source-location information for the template specialization type.
11126   TypeLocBuilder Builder;
11127   TemplateSpecializationTypeLoc SpecTL
11128     = Builder.push<TemplateSpecializationTypeLoc>(T);
11129   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
11130   SpecTL.setTemplateNameLoc(TemplateIILoc);
11131   SpecTL.setLAngleLoc(LAngleLoc);
11132   SpecTL.setRAngleLoc(RAngleLoc);
11133   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
11134     SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
11135 
11136   T = Context.getElaboratedType(ElaboratedTypeKeyword::Typename,
11137                                 SS.getScopeRep(), T);
11138   ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
11139   TL.setElaboratedKeywordLoc(TypenameLoc);
11140   TL.setQualifierLoc(SS.getWithLocInContext(Context));
11141 
11142   TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11143   return CreateParsedType(T, TSI);
11144 }
11145 
11146 
11147 /// Determine whether this failed name lookup should be treated as being
11148 /// disabled by a usage of std::enable_if.
isEnableIf(NestedNameSpecifierLoc NNS,const IdentifierInfo & II,SourceRange & CondRange,Expr * & Cond)11149 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
11150                        SourceRange &CondRange, Expr *&Cond) {
11151   // We must be looking for a ::type...
11152   if (!II.isStr("type"))
11153     return false;
11154 
11155   // ... within an explicitly-written template specialization...
11156   if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
11157     return false;
11158   TypeLoc EnableIfTy = NNS.getTypeLoc();
11159   TemplateSpecializationTypeLoc EnableIfTSTLoc =
11160       EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
11161   if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11162     return false;
11163   const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11164 
11165   // ... which names a complete class template declaration...
11166   const TemplateDecl *EnableIfDecl =
11167     EnableIfTST->getTemplateName().getAsTemplateDecl();
11168   if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11169     return false;
11170 
11171   // ... called "enable_if".
11172   const IdentifierInfo *EnableIfII =
11173     EnableIfDecl->getDeclName().getAsIdentifierInfo();
11174   if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11175     return false;
11176 
11177   // Assume the first template argument is the condition.
11178   CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11179 
11180   // Dig out the condition.
11181   Cond = nullptr;
11182   if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11183         != TemplateArgument::Expression)
11184     return true;
11185 
11186   Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11187 
11188   // Ignore Boolean literals; they add no value.
11189   if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11190     Cond = nullptr;
11191 
11192   return true;
11193 }
11194 
11195 QualType
CheckTypenameType(ElaboratedTypeKeyword Keyword,SourceLocation KeywordLoc,NestedNameSpecifierLoc QualifierLoc,const IdentifierInfo & II,SourceLocation IILoc,TypeSourceInfo ** TSI,bool DeducedTSTContext)11196 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11197                         SourceLocation KeywordLoc,
11198                         NestedNameSpecifierLoc QualifierLoc,
11199                         const IdentifierInfo &II,
11200                         SourceLocation IILoc,
11201                         TypeSourceInfo **TSI,
11202                         bool DeducedTSTContext) {
11203   QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11204                                  DeducedTSTContext);
11205   if (T.isNull())
11206     return QualType();
11207 
11208   *TSI = Context.CreateTypeSourceInfo(T);
11209   if (isa<DependentNameType>(T)) {
11210     DependentNameTypeLoc TL =
11211         (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
11212     TL.setElaboratedKeywordLoc(KeywordLoc);
11213     TL.setQualifierLoc(QualifierLoc);
11214     TL.setNameLoc(IILoc);
11215   } else {
11216     ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
11217     TL.setElaboratedKeywordLoc(KeywordLoc);
11218     TL.setQualifierLoc(QualifierLoc);
11219     TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
11220   }
11221   return T;
11222 }
11223 
11224 /// Build the type that describes a C++ typename specifier,
11225 /// e.g., "typename T::type".
11226 QualType
CheckTypenameType(ElaboratedTypeKeyword Keyword,SourceLocation KeywordLoc,NestedNameSpecifierLoc QualifierLoc,const IdentifierInfo & II,SourceLocation IILoc,bool DeducedTSTContext)11227 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11228                         SourceLocation KeywordLoc,
11229                         NestedNameSpecifierLoc QualifierLoc,
11230                         const IdentifierInfo &II,
11231                         SourceLocation IILoc, bool DeducedTSTContext) {
11232   CXXScopeSpec SS;
11233   SS.Adopt(QualifierLoc);
11234 
11235   DeclContext *Ctx = nullptr;
11236   if (QualifierLoc) {
11237     Ctx = computeDeclContext(SS);
11238     if (!Ctx) {
11239       // If the nested-name-specifier is dependent and couldn't be
11240       // resolved to a type, build a typename type.
11241       assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
11242       return Context.getDependentNameType(Keyword,
11243                                           QualifierLoc.getNestedNameSpecifier(),
11244                                           &II);
11245     }
11246 
11247     // If the nested-name-specifier refers to the current instantiation,
11248     // the "typename" keyword itself is superfluous. In C++03, the
11249     // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11250     // allows such extraneous "typename" keywords, and we retroactively
11251     // apply this DR to C++03 code with only a warning. In any case we continue.
11252 
11253     if (RequireCompleteDeclContext(SS, Ctx))
11254       return QualType();
11255   }
11256 
11257   DeclarationName Name(&II);
11258   LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11259   if (Ctx)
11260     LookupQualifiedName(Result, Ctx, SS);
11261   else
11262     LookupName(Result, CurScope);
11263   unsigned DiagID = 0;
11264   Decl *Referenced = nullptr;
11265   switch (Result.getResultKind()) {
11266   case LookupResult::NotFound: {
11267     // If we're looking up 'type' within a template named 'enable_if', produce
11268     // a more specific diagnostic.
11269     SourceRange CondRange;
11270     Expr *Cond = nullptr;
11271     if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11272       // If we have a condition, narrow it down to the specific failed
11273       // condition.
11274       if (Cond) {
11275         Expr *FailedCond;
11276         std::string FailedDescription;
11277         std::tie(FailedCond, FailedDescription) =
11278           findFailedBooleanCondition(Cond);
11279 
11280         Diag(FailedCond->getExprLoc(),
11281              diag::err_typename_nested_not_found_requirement)
11282           << FailedDescription
11283           << FailedCond->getSourceRange();
11284         return QualType();
11285       }
11286 
11287       Diag(CondRange.getBegin(),
11288            diag::err_typename_nested_not_found_enable_if)
11289           << Ctx << CondRange;
11290       return QualType();
11291     }
11292 
11293     DiagID = Ctx ? diag::err_typename_nested_not_found
11294                  : diag::err_unknown_typename;
11295     break;
11296   }
11297 
11298   case LookupResult::FoundUnresolvedValue: {
11299     // We found a using declaration that is a value. Most likely, the using
11300     // declaration itself is meant to have the 'typename' keyword.
11301     SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11302                           IILoc);
11303     Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11304       << Name << Ctx << FullRange;
11305     if (UnresolvedUsingValueDecl *Using
11306           = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11307       SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11308       Diag(Loc, diag::note_using_value_decl_missing_typename)
11309         << FixItHint::CreateInsertion(Loc, "typename ");
11310     }
11311   }
11312   // Fall through to create a dependent typename type, from which we can recover
11313   // better.
11314   [[fallthrough]];
11315 
11316   case LookupResult::NotFoundInCurrentInstantiation:
11317     // Okay, it's a member of an unknown instantiation.
11318     return Context.getDependentNameType(Keyword,
11319                                         QualifierLoc.getNestedNameSpecifier(),
11320                                         &II);
11321 
11322   case LookupResult::Found:
11323     if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11324       // C++ [class.qual]p2:
11325       //   In a lookup in which function names are not ignored and the
11326       //   nested-name-specifier nominates a class C, if the name specified
11327       //   after the nested-name-specifier, when looked up in C, is the
11328       //   injected-class-name of C [...] then the name is instead considered
11329       //   to name the constructor of class C.
11330       //
11331       // Unlike in an elaborated-type-specifier, function names are not ignored
11332       // in typename-specifier lookup. However, they are ignored in all the
11333       // contexts where we form a typename type with no keyword (that is, in
11334       // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11335       //
11336       // FIXME: That's not strictly true: mem-initializer-id lookup does not
11337       // ignore functions, but that appears to be an oversight.
11338       auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
11339       auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
11340       if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
11341           FoundRD->isInjectedClassName() &&
11342           declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
11343         Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
11344             << &II << 1 << 0 /*'typename' keyword used*/;
11345 
11346       // We found a type. Build an ElaboratedType, since the
11347       // typename-specifier was just sugar.
11348       MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
11349       return Context.getElaboratedType(Keyword,
11350                                        QualifierLoc.getNestedNameSpecifier(),
11351                                        Context.getTypeDeclType(Type));
11352     }
11353 
11354     // C++ [dcl.type.simple]p2:
11355     //   A type-specifier of the form
11356     //     typename[opt] nested-name-specifier[opt] template-name
11357     //   is a placeholder for a deduced class type [...].
11358     if (getLangOpts().CPlusPlus17) {
11359       if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11360         if (!DeducedTSTContext) {
11361           QualType T(QualifierLoc
11362                          ? QualifierLoc.getNestedNameSpecifier()->getAsType()
11363                          : nullptr, 0);
11364           if (!T.isNull())
11365             Diag(IILoc, diag::err_dependent_deduced_tst)
11366               << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T;
11367           else
11368             Diag(IILoc, diag::err_deduced_tst)
11369               << (int)getTemplateNameKindForDiagnostics(TemplateName(TD));
11370           NoteTemplateLocation(*TD);
11371           return QualType();
11372         }
11373         return Context.getElaboratedType(
11374             Keyword, QualifierLoc.getNestedNameSpecifier(),
11375             Context.getDeducedTemplateSpecializationType(TemplateName(TD),
11376                                                          QualType(), false));
11377       }
11378     }
11379 
11380     DiagID = Ctx ? diag::err_typename_nested_not_type
11381                  : diag::err_typename_not_type;
11382     Referenced = Result.getFoundDecl();
11383     break;
11384 
11385   case LookupResult::FoundOverloaded:
11386     DiagID = Ctx ? diag::err_typename_nested_not_type
11387                  : diag::err_typename_not_type;
11388     Referenced = *Result.begin();
11389     break;
11390 
11391   case LookupResult::Ambiguous:
11392     return QualType();
11393   }
11394 
11395   // If we get here, it's because name lookup did not find a
11396   // type. Emit an appropriate diagnostic and return an error.
11397   SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11398                         IILoc);
11399   if (Ctx)
11400     Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11401   else
11402     Diag(IILoc, DiagID) << FullRange << Name;
11403   if (Referenced)
11404     Diag(Referenced->getLocation(),
11405          Ctx ? diag::note_typename_member_refers_here
11406              : diag::note_typename_refers_here)
11407       << Name;
11408   return QualType();
11409 }
11410 
11411 namespace {
11412   // See Sema::RebuildTypeInCurrentInstantiation
11413   class CurrentInstantiationRebuilder
11414     : public TreeTransform<CurrentInstantiationRebuilder> {
11415     SourceLocation Loc;
11416     DeclarationName Entity;
11417 
11418   public:
11419     typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11420 
CurrentInstantiationRebuilder(Sema & SemaRef,SourceLocation Loc,DeclarationName Entity)11421     CurrentInstantiationRebuilder(Sema &SemaRef,
11422                                   SourceLocation Loc,
11423                                   DeclarationName Entity)
11424     : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11425       Loc(Loc), Entity(Entity) { }
11426 
11427     /// Determine whether the given type \p T has already been
11428     /// transformed.
11429     ///
11430     /// For the purposes of type reconstruction, a type has already been
11431     /// transformed if it is NULL or if it is not dependent.
AlreadyTransformed(QualType T)11432     bool AlreadyTransformed(QualType T) {
11433       return T.isNull() || !T->isInstantiationDependentType();
11434     }
11435 
11436     /// Returns the location of the entity whose type is being
11437     /// rebuilt.
getBaseLocation()11438     SourceLocation getBaseLocation() { return Loc; }
11439 
11440     /// Returns the name of the entity whose type is being rebuilt.
getBaseEntity()11441     DeclarationName getBaseEntity() { return Entity; }
11442 
11443     /// Sets the "base" location and entity when that
11444     /// information is known based on another transformation.
setBase(SourceLocation Loc,DeclarationName Entity)11445     void setBase(SourceLocation Loc, DeclarationName Entity) {
11446       this->Loc = Loc;
11447       this->Entity = Entity;
11448     }
11449 
TransformLambdaExpr(LambdaExpr * E)11450     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11451       // Lambdas never need to be transformed.
11452       return E;
11453     }
11454   };
11455 } // end anonymous namespace
11456 
11457 /// Rebuilds a type within the context of the current instantiation.
11458 ///
11459 /// The type \p T is part of the type of an out-of-line member definition of
11460 /// a class template (or class template partial specialization) that was parsed
11461 /// and constructed before we entered the scope of the class template (or
11462 /// partial specialization thereof). This routine will rebuild that type now
11463 /// that we have entered the declarator's scope, which may produce different
11464 /// canonical types, e.g.,
11465 ///
11466 /// \code
11467 /// template<typename T>
11468 /// struct X {
11469 ///   typedef T* pointer;
11470 ///   pointer data();
11471 /// };
11472 ///
11473 /// template<typename T>
11474 /// typename X<T>::pointer X<T>::data() { ... }
11475 /// \endcode
11476 ///
11477 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
11478 /// since we do not know that we can look into X<T> when we parsed the type.
11479 /// This function will rebuild the type, performing the lookup of "pointer"
11480 /// in X<T> and returning an ElaboratedType whose canonical type is the same
11481 /// as the canonical type of T*, allowing the return types of the out-of-line
11482 /// definition and the declaration to match.
RebuildTypeInCurrentInstantiation(TypeSourceInfo * T,SourceLocation Loc,DeclarationName Name)11483 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11484                                                         SourceLocation Loc,
11485                                                         DeclarationName Name) {
11486   if (!T || !T->getType()->isInstantiationDependentType())
11487     return T;
11488 
11489   CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11490   return Rebuilder.TransformType(T);
11491 }
11492 
RebuildExprInCurrentInstantiation(Expr * E)11493 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11494   CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11495                                           DeclarationName());
11496   return Rebuilder.TransformExpr(E);
11497 }
11498 
RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec & SS)11499 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11500   if (SS.isInvalid())
11501     return true;
11502 
11503   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11504   CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11505                                           DeclarationName());
11506   NestedNameSpecifierLoc Rebuilt
11507     = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11508   if (!Rebuilt)
11509     return true;
11510 
11511   SS.Adopt(Rebuilt);
11512   return false;
11513 }
11514 
11515 /// Rebuild the template parameters now that we know we're in a current
11516 /// instantiation.
RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList * Params)11517 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11518                                                TemplateParameterList *Params) {
11519   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11520     Decl *Param = Params->getParam(I);
11521 
11522     // There is nothing to rebuild in a type parameter.
11523     if (isa<TemplateTypeParmDecl>(Param))
11524       continue;
11525 
11526     // Rebuild the template parameter list of a template template parameter.
11527     if (TemplateTemplateParmDecl *TTP
11528         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11529       if (RebuildTemplateParamsInCurrentInstantiation(
11530             TTP->getTemplateParameters()))
11531         return true;
11532 
11533       continue;
11534     }
11535 
11536     // Rebuild the type of a non-type template parameter.
11537     NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
11538     TypeSourceInfo *NewTSI
11539       = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
11540                                           NTTP->getLocation(),
11541                                           NTTP->getDeclName());
11542     if (!NewTSI)
11543       return true;
11544 
11545     if (NewTSI->getType()->isUndeducedType()) {
11546       // C++17 [temp.dep.expr]p3:
11547       //   An id-expression is type-dependent if it contains
11548       //    - an identifier associated by name lookup with a non-type
11549       //      template-parameter declared with a type that contains a
11550       //      placeholder type (7.1.7.4),
11551       NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11552     }
11553 
11554     if (NewTSI != NTTP->getTypeSourceInfo()) {
11555       NTTP->setTypeSourceInfo(NewTSI);
11556       NTTP->setType(NewTSI->getType());
11557     }
11558   }
11559 
11560   return false;
11561 }
11562 
11563 /// Produces a formatted string that describes the binding of
11564 /// template parameters to template arguments.
11565 std::string
getTemplateArgumentBindingsText(const TemplateParameterList * Params,const TemplateArgumentList & Args)11566 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11567                                       const TemplateArgumentList &Args) {
11568   return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11569 }
11570 
11571 std::string
getTemplateArgumentBindingsText(const TemplateParameterList * Params,const TemplateArgument * Args,unsigned NumArgs)11572 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11573                                       const TemplateArgument *Args,
11574                                       unsigned NumArgs) {
11575   SmallString<128> Str;
11576   llvm::raw_svector_ostream Out(Str);
11577 
11578   if (!Params || Params->size() == 0 || NumArgs == 0)
11579     return std::string();
11580 
11581   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11582     if (I >= NumArgs)
11583       break;
11584 
11585     if (I == 0)
11586       Out << "[with ";
11587     else
11588       Out << ", ";
11589 
11590     if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11591       Out << Id->getName();
11592     } else {
11593       Out << '$' << I;
11594     }
11595 
11596     Out << " = ";
11597     Args[I].print(getPrintingPolicy(), Out,
11598                   TemplateParameterList::shouldIncludeTypeForArgument(
11599                       getPrintingPolicy(), Params, I));
11600   }
11601 
11602   Out << ']';
11603   return std::string(Out.str());
11604 }
11605 
MarkAsLateParsedTemplate(FunctionDecl * FD,Decl * FnD,CachedTokens & Toks)11606 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11607                                     CachedTokens &Toks) {
11608   if (!FD)
11609     return;
11610 
11611   auto LPT = std::make_unique<LateParsedTemplate>();
11612 
11613   // Take tokens to avoid allocations
11614   LPT->Toks.swap(Toks);
11615   LPT->D = FnD;
11616   LPT->FPO = getCurFPFeatures();
11617   LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11618 
11619   FD->setLateTemplateParsed(true);
11620 }
11621 
UnmarkAsLateParsedTemplate(FunctionDecl * FD)11622 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11623   if (!FD)
11624     return;
11625   FD->setLateTemplateParsed(false);
11626 }
11627 
IsInsideALocalClassWithinATemplateFunction()11628 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11629   DeclContext *DC = CurContext;
11630 
11631   while (DC) {
11632     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11633       const FunctionDecl *FD = RD->isLocalClass();
11634       return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11635     } else if (DC->isTranslationUnit() || DC->isNamespace())
11636       return false;
11637 
11638     DC = DC->getParent();
11639   }
11640   return false;
11641 }
11642 
11643 namespace {
11644 /// Walk the path from which a declaration was instantiated, and check
11645 /// that every explicit specialization along that path is visible. This enforces
11646 /// C++ [temp.expl.spec]/6:
11647 ///
11648 ///   If a template, a member template or a member of a class template is
11649 ///   explicitly specialized then that specialization shall be declared before
11650 ///   the first use of that specialization that would cause an implicit
11651 ///   instantiation to take place, in every translation unit in which such a
11652 ///   use occurs; no diagnostic is required.
11653 ///
11654 /// and also C++ [temp.class.spec]/1:
11655 ///
11656 ///   A partial specialization shall be declared before the first use of a
11657 ///   class template specialization that would make use of the partial
11658 ///   specialization as the result of an implicit or explicit instantiation
11659 ///   in every translation unit in which such a use occurs; no diagnostic is
11660 ///   required.
11661 class ExplicitSpecializationVisibilityChecker {
11662   Sema &S;
11663   SourceLocation Loc;
11664   llvm::SmallVector<Module *, 8> Modules;
11665   Sema::AcceptableKind Kind;
11666 
11667 public:
ExplicitSpecializationVisibilityChecker(Sema & S,SourceLocation Loc,Sema::AcceptableKind Kind)11668   ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11669                                           Sema::AcceptableKind Kind)
11670       : S(S), Loc(Loc), Kind(Kind) {}
11671 
check(NamedDecl * ND)11672   void check(NamedDecl *ND) {
11673     if (auto *FD = dyn_cast<FunctionDecl>(ND))
11674       return checkImpl(FD);
11675     if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11676       return checkImpl(RD);
11677     if (auto *VD = dyn_cast<VarDecl>(ND))
11678       return checkImpl(VD);
11679     if (auto *ED = dyn_cast<EnumDecl>(ND))
11680       return checkImpl(ED);
11681   }
11682 
11683 private:
diagnose(NamedDecl * D,bool IsPartialSpec)11684   void diagnose(NamedDecl *D, bool IsPartialSpec) {
11685     auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11686                               : Sema::MissingImportKind::ExplicitSpecialization;
11687     const bool Recover = true;
11688 
11689     // If we got a custom set of modules (because only a subset of the
11690     // declarations are interesting), use them, otherwise let
11691     // diagnoseMissingImport intelligently pick some.
11692     if (Modules.empty())
11693       S.diagnoseMissingImport(Loc, D, Kind, Recover);
11694     else
11695       S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11696   }
11697 
CheckMemberSpecialization(const NamedDecl * D)11698   bool CheckMemberSpecialization(const NamedDecl *D) {
11699     return Kind == Sema::AcceptableKind::Visible
11700                ? S.hasVisibleMemberSpecialization(D)
11701                : S.hasReachableMemberSpecialization(D);
11702   }
11703 
CheckExplicitSpecialization(const NamedDecl * D)11704   bool CheckExplicitSpecialization(const NamedDecl *D) {
11705     return Kind == Sema::AcceptableKind::Visible
11706                ? S.hasVisibleExplicitSpecialization(D)
11707                : S.hasReachableExplicitSpecialization(D);
11708   }
11709 
CheckDeclaration(const NamedDecl * D)11710   bool CheckDeclaration(const NamedDecl *D) {
11711     return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11712                                                  : S.hasReachableDeclaration(D);
11713   }
11714 
11715   // Check a specific declaration. There are three problematic cases:
11716   //
11717   //  1) The declaration is an explicit specialization of a template
11718   //     specialization.
11719   //  2) The declaration is an explicit specialization of a member of an
11720   //     templated class.
11721   //  3) The declaration is an instantiation of a template, and that template
11722   //     is an explicit specialization of a member of a templated class.
11723   //
11724   // We don't need to go any deeper than that, as the instantiation of the
11725   // surrounding class / etc is not triggered by whatever triggered this
11726   // instantiation, and thus should be checked elsewhere.
11727   template<typename SpecDecl>
checkImpl(SpecDecl * Spec)11728   void checkImpl(SpecDecl *Spec) {
11729     bool IsHiddenExplicitSpecialization = false;
11730     if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
11731       IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11732                                            ? !CheckMemberSpecialization(Spec)
11733                                            : !CheckExplicitSpecialization(Spec);
11734     } else {
11735       checkInstantiated(Spec);
11736     }
11737 
11738     if (IsHiddenExplicitSpecialization)
11739       diagnose(Spec->getMostRecentDecl(), false);
11740   }
11741 
checkInstantiated(FunctionDecl * FD)11742   void checkInstantiated(FunctionDecl *FD) {
11743     if (auto *TD = FD->getPrimaryTemplate())
11744       checkTemplate(TD);
11745   }
11746 
checkInstantiated(CXXRecordDecl * RD)11747   void checkInstantiated(CXXRecordDecl *RD) {
11748     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11749     if (!SD)
11750       return;
11751 
11752     auto From = SD->getSpecializedTemplateOrPartial();
11753     if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11754       checkTemplate(TD);
11755     else if (auto *TD =
11756                  From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11757       if (!CheckDeclaration(TD))
11758         diagnose(TD, true);
11759       checkTemplate(TD);
11760     }
11761   }
11762 
checkInstantiated(VarDecl * RD)11763   void checkInstantiated(VarDecl *RD) {
11764     auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11765     if (!SD)
11766       return;
11767 
11768     auto From = SD->getSpecializedTemplateOrPartial();
11769     if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11770       checkTemplate(TD);
11771     else if (auto *TD =
11772                  From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11773       if (!CheckDeclaration(TD))
11774         diagnose(TD, true);
11775       checkTemplate(TD);
11776     }
11777   }
11778 
checkInstantiated(EnumDecl * FD)11779   void checkInstantiated(EnumDecl *FD) {}
11780 
11781   template<typename TemplDecl>
checkTemplate(TemplDecl * TD)11782   void checkTemplate(TemplDecl *TD) {
11783     if (TD->isMemberSpecialization()) {
11784       if (!CheckMemberSpecialization(TD))
11785         diagnose(TD->getMostRecentDecl(), false);
11786     }
11787   }
11788 };
11789 } // end anonymous namespace
11790 
checkSpecializationVisibility(SourceLocation Loc,NamedDecl * Spec)11791 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11792   if (!getLangOpts().Modules)
11793     return;
11794 
11795   ExplicitSpecializationVisibilityChecker(*this, Loc,
11796                                           Sema::AcceptableKind::Visible)
11797       .check(Spec);
11798 }
11799 
checkSpecializationReachability(SourceLocation Loc,NamedDecl * Spec)11800 void Sema::checkSpecializationReachability(SourceLocation Loc,
11801                                            NamedDecl *Spec) {
11802   if (!getLangOpts().CPlusPlusModules)
11803     return checkSpecializationVisibility(Loc, Spec);
11804 
11805   ExplicitSpecializationVisibilityChecker(*this, Loc,
11806                                           Sema::AcceptableKind::Reachable)
11807       .check(Spec);
11808 }
11809 
11810 /// Returns the top most location responsible for the definition of \p N.
11811 /// If \p N is a a template specialization, this is the location
11812 /// of the top of the instantiation stack.
11813 /// Otherwise, the location of \p N is returned.
getTopMostPointOfInstantiation(const NamedDecl * N) const11814 SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
11815   if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11816     return N->getLocation();
11817   if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11818     if (!FD->isFunctionTemplateSpecialization())
11819       return FD->getLocation();
11820   } else if (!isa<ClassTemplateSpecializationDecl,
11821                   VarTemplateSpecializationDecl>(N)) {
11822     return N->getLocation();
11823   }
11824   for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11825     if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11826       continue;
11827     return CSC.PointOfInstantiation;
11828   }
11829   return N->getLocation();
11830 }
11831