xref: /openbsd/gnu/llvm/clang/lib/Sema/SemaTemplate.cpp (revision 12c85518)
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/Stack.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/Initialization.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Overload.h"
32 #include "clang/Sema/ParsedTemplate.h"
33 #include "clang/Sema/Scope.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "clang/Sema/Template.h"
36 #include "clang/Sema/TemplateDeduction.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/ADT/StringExtras.h"
40 
41 #include <iterator>
42 #include <optional>
43 using namespace clang;
44 using namespace sema;
45 
46 // Exported for use by Parser.
47 SourceRange
getTemplateParamsRange(TemplateParameterList const * const * Ps,unsigned N)48 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
49                               unsigned N) {
50   if (!N) return SourceRange();
51   return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
52 }
53 
getTemplateDepth(Scope * S) const54 unsigned Sema::getTemplateDepth(Scope *S) const {
55   unsigned Depth = 0;
56 
57   // Each template parameter scope represents one level of template parameter
58   // depth.
59   for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
60        TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
61     ++Depth;
62   }
63 
64   // Note that there are template parameters with the given depth.
65   auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
66 
67   // Look for parameters of an enclosing generic lambda. We don't create a
68   // template parameter scope for these.
69   for (FunctionScopeInfo *FSI : getFunctionScopes()) {
70     if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
71       if (!LSI->TemplateParams.empty()) {
72         ParamsAtDepth(LSI->AutoTemplateParameterDepth);
73         break;
74       }
75       if (LSI->GLTemplateParameterList) {
76         ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
77         break;
78       }
79     }
80   }
81 
82   // Look for parameters of an enclosing terse function template. We don't
83   // create a template parameter scope for these either.
84   for (const InventedTemplateParameterInfo &Info :
85        getInventedParameterInfos()) {
86     if (!Info.TemplateParams.empty()) {
87       ParamsAtDepth(Info.AutoTemplateParameterDepth);
88       break;
89     }
90   }
91 
92   return Depth;
93 }
94 
95 /// \brief Determine whether the declaration found is acceptable as the name
96 /// of a template and, if so, return that template declaration. Otherwise,
97 /// returns null.
98 ///
99 /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
100 /// is true. In all other cases it will return a TemplateDecl (or null).
getAsTemplateNameDecl(NamedDecl * D,bool AllowFunctionTemplates,bool AllowDependent)101 NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
102                                        bool AllowFunctionTemplates,
103                                        bool AllowDependent) {
104   D = D->getUnderlyingDecl();
105 
106   if (isa<TemplateDecl>(D)) {
107     if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
108       return nullptr;
109 
110     return D;
111   }
112 
113   if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
114     // C++ [temp.local]p1:
115     //   Like normal (non-template) classes, class templates have an
116     //   injected-class-name (Clause 9). The injected-class-name
117     //   can be used with or without a template-argument-list. When
118     //   it is used without a template-argument-list, it is
119     //   equivalent to the injected-class-name followed by the
120     //   template-parameters of the class template enclosed in
121     //   <>. When it is used with a template-argument-list, it
122     //   refers to the specified class template specialization,
123     //   which could be the current specialization or another
124     //   specialization.
125     if (Record->isInjectedClassName()) {
126       Record = cast<CXXRecordDecl>(Record->getDeclContext());
127       if (Record->getDescribedClassTemplate())
128         return Record->getDescribedClassTemplate();
129 
130       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
131         return Spec->getSpecializedTemplate();
132     }
133 
134     return nullptr;
135   }
136 
137   // 'using Dependent::foo;' can resolve to a template name.
138   // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
139   // injected-class-name).
140   if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
141     return D;
142 
143   return nullptr;
144 }
145 
FilterAcceptableTemplateNames(LookupResult & R,bool AllowFunctionTemplates,bool AllowDependent)146 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
147                                          bool AllowFunctionTemplates,
148                                          bool AllowDependent) {
149   LookupResult::Filter filter = R.makeFilter();
150   while (filter.hasNext()) {
151     NamedDecl *Orig = filter.next();
152     if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
153       filter.erase();
154   }
155   filter.done();
156 }
157 
hasAnyAcceptableTemplateNames(LookupResult & R,bool AllowFunctionTemplates,bool AllowDependent,bool AllowNonTemplateFunctions)158 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
159                                          bool AllowFunctionTemplates,
160                                          bool AllowDependent,
161                                          bool AllowNonTemplateFunctions) {
162   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
163     if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
164       return true;
165     if (AllowNonTemplateFunctions &&
166         isa<FunctionDecl>((*I)->getUnderlyingDecl()))
167       return true;
168   }
169 
170   return false;
171 }
172 
isTemplateName(Scope * S,CXXScopeSpec & SS,bool hasTemplateKeyword,const UnqualifiedId & Name,ParsedType ObjectTypePtr,bool EnteringContext,TemplateTy & TemplateResult,bool & MemberOfUnknownSpecialization,bool Disambiguation)173 TemplateNameKind Sema::isTemplateName(Scope *S,
174                                       CXXScopeSpec &SS,
175                                       bool hasTemplateKeyword,
176                                       const UnqualifiedId &Name,
177                                       ParsedType ObjectTypePtr,
178                                       bool EnteringContext,
179                                       TemplateTy &TemplateResult,
180                                       bool &MemberOfUnknownSpecialization,
181                                       bool Disambiguation) {
182   assert(getLangOpts().CPlusPlus && "No template names in C!");
183 
184   DeclarationName TName;
185   MemberOfUnknownSpecialization = false;
186 
187   switch (Name.getKind()) {
188   case UnqualifiedIdKind::IK_Identifier:
189     TName = DeclarationName(Name.Identifier);
190     break;
191 
192   case UnqualifiedIdKind::IK_OperatorFunctionId:
193     TName = Context.DeclarationNames.getCXXOperatorName(
194                                               Name.OperatorFunctionId.Operator);
195     break;
196 
197   case UnqualifiedIdKind::IK_LiteralOperatorId:
198     TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
199     break;
200 
201   default:
202     return TNK_Non_template;
203   }
204 
205   QualType ObjectType = ObjectTypePtr.get();
206 
207   AssumedTemplateKind AssumedTemplate;
208   LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
209   if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
210                          MemberOfUnknownSpecialization, SourceLocation(),
211                          &AssumedTemplate,
212                          /*AllowTypoCorrection=*/!Disambiguation))
213     return TNK_Non_template;
214 
215   if (AssumedTemplate != AssumedTemplateKind::None) {
216     TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
217     // Let the parser know whether we found nothing or found functions; if we
218     // found nothing, we want to more carefully check whether this is actually
219     // a function template name versus some other kind of undeclared identifier.
220     return AssumedTemplate == AssumedTemplateKind::FoundNothing
221                ? TNK_Undeclared_template
222                : TNK_Function_template;
223   }
224 
225   if (R.empty())
226     return TNK_Non_template;
227 
228   NamedDecl *D = nullptr;
229   UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
230   if (R.isAmbiguous()) {
231     // If we got an ambiguity involving a non-function template, treat this
232     // as a template name, and pick an arbitrary template for error recovery.
233     bool AnyFunctionTemplates = false;
234     for (NamedDecl *FoundD : R) {
235       if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
236         if (isa<FunctionTemplateDecl>(FoundTemplate))
237           AnyFunctionTemplates = true;
238         else {
239           D = FoundTemplate;
240           FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
241           break;
242         }
243       }
244     }
245 
246     // If we didn't find any templates at all, this isn't a template name.
247     // Leave the ambiguity for a later lookup to diagnose.
248     if (!D && !AnyFunctionTemplates) {
249       R.suppressDiagnostics();
250       return TNK_Non_template;
251     }
252 
253     // If the only templates were function templates, filter out the rest.
254     // We'll diagnose the ambiguity later.
255     if (!D)
256       FilterAcceptableTemplateNames(R);
257   }
258 
259   // At this point, we have either picked a single template name declaration D
260   // or we have a non-empty set of results R containing either one template name
261   // declaration or a set of function templates.
262 
263   TemplateName Template;
264   TemplateNameKind TemplateKind;
265 
266   unsigned ResultCount = R.end() - R.begin();
267   if (!D && ResultCount > 1) {
268     // We assume that we'll preserve the qualifier from a function
269     // template name in other ways.
270     Template = Context.getOverloadedTemplateName(R.begin(), R.end());
271     TemplateKind = TNK_Function_template;
272 
273     // We'll do this lookup again later.
274     R.suppressDiagnostics();
275   } else {
276     if (!D) {
277       D = getAsTemplateNameDecl(*R.begin());
278       assert(D && "unambiguous result is not a template name");
279     }
280 
281     if (isa<UnresolvedUsingValueDecl>(D)) {
282       // We don't yet know whether this is a template-name or not.
283       MemberOfUnknownSpecialization = true;
284       return TNK_Non_template;
285     }
286 
287     TemplateDecl *TD = cast<TemplateDecl>(D);
288     Template =
289         FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
290     assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
291     if (SS.isSet() && !SS.isInvalid()) {
292       NestedNameSpecifier *Qualifier = SS.getScopeRep();
293       Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
294                                                   Template);
295     }
296 
297     if (isa<FunctionTemplateDecl>(TD)) {
298       TemplateKind = TNK_Function_template;
299 
300       // We'll do this lookup again later.
301       R.suppressDiagnostics();
302     } else {
303       assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
304              isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
305              isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
306       TemplateKind =
307           isa<VarTemplateDecl>(TD) ? TNK_Var_template :
308           isa<ConceptDecl>(TD) ? TNK_Concept_template :
309           TNK_Type_template;
310     }
311   }
312 
313   TemplateResult = TemplateTy::make(Template);
314   return TemplateKind;
315 }
316 
isDeductionGuideName(Scope * S,const IdentifierInfo & Name,SourceLocation NameLoc,ParsedTemplateTy * Template)317 bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
318                                 SourceLocation NameLoc,
319                                 ParsedTemplateTy *Template) {
320   CXXScopeSpec SS;
321   bool MemberOfUnknownSpecialization = false;
322 
323   // We could use redeclaration lookup here, but we don't need to: the
324   // syntactic form of a deduction guide is enough to identify it even
325   // if we can't look up the template name at all.
326   LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
327   if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
328                          /*EnteringContext*/ false,
329                          MemberOfUnknownSpecialization))
330     return false;
331 
332   if (R.empty()) return false;
333   if (R.isAmbiguous()) {
334     // FIXME: Diagnose an ambiguity if we find at least one template.
335     R.suppressDiagnostics();
336     return false;
337   }
338 
339   // We only treat template-names that name type templates as valid deduction
340   // guide names.
341   TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
342   if (!TD || !getAsTypeTemplateDecl(TD))
343     return false;
344 
345   if (Template)
346     *Template = TemplateTy::make(TemplateName(TD));
347   return true;
348 }
349 
DiagnoseUnknownTemplateName(const IdentifierInfo & II,SourceLocation IILoc,Scope * S,const CXXScopeSpec * SS,TemplateTy & SuggestedTemplate,TemplateNameKind & SuggestedKind)350 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
351                                        SourceLocation IILoc,
352                                        Scope *S,
353                                        const CXXScopeSpec *SS,
354                                        TemplateTy &SuggestedTemplate,
355                                        TemplateNameKind &SuggestedKind) {
356   // We can't recover unless there's a dependent scope specifier preceding the
357   // template name.
358   // FIXME: Typo correction?
359   if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
360       computeDeclContext(*SS))
361     return false;
362 
363   // The code is missing a 'template' keyword prior to the dependent template
364   // name.
365   NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
366   Diag(IILoc, diag::err_template_kw_missing)
367     << Qualifier << II.getName()
368     << FixItHint::CreateInsertion(IILoc, "template ");
369   SuggestedTemplate
370     = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
371   SuggestedKind = TNK_Dependent_template_name;
372   return true;
373 }
374 
LookupTemplateName(LookupResult & Found,Scope * S,CXXScopeSpec & SS,QualType ObjectType,bool EnteringContext,bool & MemberOfUnknownSpecialization,RequiredTemplateKind RequiredTemplate,AssumedTemplateKind * ATK,bool AllowTypoCorrection)375 bool Sema::LookupTemplateName(LookupResult &Found,
376                               Scope *S, CXXScopeSpec &SS,
377                               QualType ObjectType,
378                               bool EnteringContext,
379                               bool &MemberOfUnknownSpecialization,
380                               RequiredTemplateKind RequiredTemplate,
381                               AssumedTemplateKind *ATK,
382                               bool AllowTypoCorrection) {
383   if (ATK)
384     *ATK = AssumedTemplateKind::None;
385 
386   if (SS.isInvalid())
387     return true;
388 
389   Found.setTemplateNameLookup(true);
390 
391   // Determine where to perform name lookup
392   MemberOfUnknownSpecialization = false;
393   DeclContext *LookupCtx = nullptr;
394   bool IsDependent = false;
395   if (!ObjectType.isNull()) {
396     // This nested-name-specifier occurs in a member access expression, e.g.,
397     // x->B::f, and we are looking into the type of the object.
398     assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
399     LookupCtx = computeDeclContext(ObjectType);
400     IsDependent = !LookupCtx && ObjectType->isDependentType();
401     assert((IsDependent || !ObjectType->isIncompleteType() ||
402             !ObjectType->getAs<TagType>() ||
403             ObjectType->castAs<TagType>()->isBeingDefined()) &&
404            "Caller should have completed object type");
405 
406     // Template names cannot appear inside an Objective-C class or object type
407     // or a vector type.
408     //
409     // FIXME: This is wrong. For example:
410     //
411     //   template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
412     //   Vec<int> vi;
413     //   vi.Vec<int>::~Vec<int>();
414     //
415     // ... should be accepted but we will not treat 'Vec' as a template name
416     // here. The right thing to do would be to check if the name is a valid
417     // vector component name, and look up a template name if not. And similarly
418     // for lookups into Objective-C class and object types, where the same
419     // problem can arise.
420     if (ObjectType->isObjCObjectOrInterfaceType() ||
421         ObjectType->isVectorType()) {
422       Found.clear();
423       return false;
424     }
425   } else if (SS.isNotEmpty()) {
426     // This nested-name-specifier occurs after another nested-name-specifier,
427     // so long into the context associated with the prior nested-name-specifier.
428     LookupCtx = computeDeclContext(SS, EnteringContext);
429     IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
430 
431     // The declaration context must be complete.
432     if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
433       return true;
434   }
435 
436   bool ObjectTypeSearchedInScope = false;
437   bool AllowFunctionTemplatesInLookup = true;
438   if (LookupCtx) {
439     // Perform "qualified" name lookup into the declaration context we
440     // computed, which is either the type of the base of a member access
441     // expression or the declaration context associated with a prior
442     // nested-name-specifier.
443     LookupQualifiedName(Found, LookupCtx);
444 
445     // FIXME: The C++ standard does not clearly specify what happens in the
446     // case where the object type is dependent, and implementations vary. In
447     // Clang, we treat a name after a . or -> as a template-name if lookup
448     // finds a non-dependent member or member of the current instantiation that
449     // is a type template, or finds no such members and lookup in the context
450     // of the postfix-expression finds a type template. In the latter case, the
451     // name is nonetheless dependent, and we may resolve it to a member of an
452     // unknown specialization when we come to instantiate the template.
453     IsDependent |= Found.wasNotFoundInCurrentInstantiation();
454   }
455 
456   if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
457     // C++ [basic.lookup.classref]p1:
458     //   In a class member access expression (5.2.5), if the . or -> token is
459     //   immediately followed by an identifier followed by a <, the
460     //   identifier must be looked up to determine whether the < is the
461     //   beginning of a template argument list (14.2) or a less-than operator.
462     //   The identifier is first looked up in the class of the object
463     //   expression. If the identifier is not found, it is then looked up in
464     //   the context of the entire postfix-expression and shall name a class
465     //   template.
466     if (S)
467       LookupName(Found, S);
468 
469     if (!ObjectType.isNull()) {
470       //  FIXME: We should filter out all non-type templates here, particularly
471       //  variable templates and concepts. But the exclusion of alias templates
472       //  and template template parameters is a wording defect.
473       AllowFunctionTemplatesInLookup = false;
474       ObjectTypeSearchedInScope = true;
475     }
476 
477     IsDependent |= Found.wasNotFoundInCurrentInstantiation();
478   }
479 
480   if (Found.isAmbiguous())
481     return false;
482 
483   if (ATK && SS.isEmpty() && ObjectType.isNull() &&
484       !RequiredTemplate.hasTemplateKeyword()) {
485     // C++2a [temp.names]p2:
486     //   A name is also considered to refer to a template if it is an
487     //   unqualified-id followed by a < and name lookup finds either one or more
488     //   functions or finds nothing.
489     //
490     // To keep our behavior consistent, we apply the "finds nothing" part in
491     // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
492     // successfully form a call to an undeclared template-id.
493     bool AllFunctions =
494         getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
495           return isa<FunctionDecl>(ND->getUnderlyingDecl());
496         });
497     if (AllFunctions || (Found.empty() && !IsDependent)) {
498       // If lookup found any functions, or if this is a name that can only be
499       // used for a function, then strongly assume this is a function
500       // template-id.
501       *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
502                  ? AssumedTemplateKind::FoundNothing
503                  : AssumedTemplateKind::FoundFunctions;
504       Found.clear();
505       return false;
506     }
507   }
508 
509   if (Found.empty() && !IsDependent && AllowTypoCorrection) {
510     // If we did not find any names, and this is not a disambiguation, attempt
511     // to correct any typos.
512     DeclarationName Name = Found.getLookupName();
513     Found.clear();
514     // Simple filter callback that, for keywords, only accepts the C++ *_cast
515     DefaultFilterCCC FilterCCC{};
516     FilterCCC.WantTypeSpecifiers = false;
517     FilterCCC.WantExpressionKeywords = false;
518     FilterCCC.WantRemainingKeywords = false;
519     FilterCCC.WantCXXNamedCasts = true;
520     if (TypoCorrection Corrected =
521             CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
522                         &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
523       if (auto *ND = Corrected.getFoundDecl())
524         Found.addDecl(ND);
525       FilterAcceptableTemplateNames(Found);
526       if (Found.isAmbiguous()) {
527         Found.clear();
528       } else if (!Found.empty()) {
529         Found.setLookupName(Corrected.getCorrection());
530         if (LookupCtx) {
531           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
532           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
533                                   Name.getAsString() == CorrectedStr;
534           diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
535                                     << Name << LookupCtx << DroppedSpecifier
536                                     << SS.getRange());
537         } else {
538           diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
539         }
540       }
541     }
542   }
543 
544   NamedDecl *ExampleLookupResult =
545       Found.empty() ? nullptr : Found.getRepresentativeDecl();
546   FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
547   if (Found.empty()) {
548     if (IsDependent) {
549       MemberOfUnknownSpecialization = true;
550       return false;
551     }
552 
553     // If a 'template' keyword was used, a lookup that finds only non-template
554     // names is an error.
555     if (ExampleLookupResult && RequiredTemplate) {
556       Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
557           << Found.getLookupName() << SS.getRange()
558           << RequiredTemplate.hasTemplateKeyword()
559           << RequiredTemplate.getTemplateKeywordLoc();
560       Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
561            diag::note_template_kw_refers_to_non_template)
562           << Found.getLookupName();
563       return true;
564     }
565 
566     return false;
567   }
568 
569   if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
570       !getLangOpts().CPlusPlus11) {
571     // C++03 [basic.lookup.classref]p1:
572     //   [...] If the lookup in the class of the object expression finds a
573     //   template, the name is also looked up in the context of the entire
574     //   postfix-expression and [...]
575     //
576     // Note: C++11 does not perform this second lookup.
577     LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
578                             LookupOrdinaryName);
579     FoundOuter.setTemplateNameLookup(true);
580     LookupName(FoundOuter, S);
581     // FIXME: We silently accept an ambiguous lookup here, in violation of
582     // [basic.lookup]/1.
583     FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
584 
585     NamedDecl *OuterTemplate;
586     if (FoundOuter.empty()) {
587       //   - if the name is not found, the name found in the class of the
588       //     object expression is used, otherwise
589     } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
590                !(OuterTemplate =
591                      getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
592       //   - if the name is found in the context of the entire
593       //     postfix-expression and does not name a class template, the name
594       //     found in the class of the object expression is used, otherwise
595       FoundOuter.clear();
596     } else if (!Found.isSuppressingDiagnostics()) {
597       //   - if the name found is a class template, it must refer to the same
598       //     entity as the one found in the class of the object expression,
599       //     otherwise the program is ill-formed.
600       if (!Found.isSingleResult() ||
601           getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
602               OuterTemplate->getCanonicalDecl()) {
603         Diag(Found.getNameLoc(),
604              diag::ext_nested_name_member_ref_lookup_ambiguous)
605           << Found.getLookupName()
606           << ObjectType;
607         Diag(Found.getRepresentativeDecl()->getLocation(),
608              diag::note_ambig_member_ref_object_type)
609           << ObjectType;
610         Diag(FoundOuter.getFoundDecl()->getLocation(),
611              diag::note_ambig_member_ref_scope);
612 
613         // Recover by taking the template that we found in the object
614         // expression's type.
615       }
616     }
617   }
618 
619   return false;
620 }
621 
diagnoseExprIntendedAsTemplateName(Scope * S,ExprResult TemplateName,SourceLocation Less,SourceLocation Greater)622 void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
623                                               SourceLocation Less,
624                                               SourceLocation Greater) {
625   if (TemplateName.isInvalid())
626     return;
627 
628   DeclarationNameInfo NameInfo;
629   CXXScopeSpec SS;
630   LookupNameKind LookupKind;
631 
632   DeclContext *LookupCtx = nullptr;
633   NamedDecl *Found = nullptr;
634   bool MissingTemplateKeyword = false;
635 
636   // Figure out what name we looked up.
637   if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
638     NameInfo = DRE->getNameInfo();
639     SS.Adopt(DRE->getQualifierLoc());
640     LookupKind = LookupOrdinaryName;
641     Found = DRE->getFoundDecl();
642   } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
643     NameInfo = ME->getMemberNameInfo();
644     SS.Adopt(ME->getQualifierLoc());
645     LookupKind = LookupMemberName;
646     LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
647     Found = ME->getMemberDecl();
648   } else if (auto *DSDRE =
649                  dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
650     NameInfo = DSDRE->getNameInfo();
651     SS.Adopt(DSDRE->getQualifierLoc());
652     MissingTemplateKeyword = true;
653   } else if (auto *DSME =
654                  dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
655     NameInfo = DSME->getMemberNameInfo();
656     SS.Adopt(DSME->getQualifierLoc());
657     MissingTemplateKeyword = true;
658   } else {
659     llvm_unreachable("unexpected kind of potential template name");
660   }
661 
662   // If this is a dependent-scope lookup, diagnose that the 'template' keyword
663   // was missing.
664   if (MissingTemplateKeyword) {
665     Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
666         << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
667     return;
668   }
669 
670   // Try to correct the name by looking for templates and C++ named casts.
671   struct TemplateCandidateFilter : CorrectionCandidateCallback {
672     Sema &S;
673     TemplateCandidateFilter(Sema &S) : S(S) {
674       WantTypeSpecifiers = false;
675       WantExpressionKeywords = false;
676       WantRemainingKeywords = false;
677       WantCXXNamedCasts = true;
678     };
679     bool ValidateCandidate(const TypoCorrection &Candidate) override {
680       if (auto *ND = Candidate.getCorrectionDecl())
681         return S.getAsTemplateNameDecl(ND);
682       return Candidate.isKeyword();
683     }
684 
685     std::unique_ptr<CorrectionCandidateCallback> clone() override {
686       return std::make_unique<TemplateCandidateFilter>(*this);
687     }
688   };
689 
690   DeclarationName Name = NameInfo.getName();
691   TemplateCandidateFilter CCC(*this);
692   if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
693                                              CTK_ErrorRecovery, LookupCtx)) {
694     auto *ND = Corrected.getFoundDecl();
695     if (ND)
696       ND = getAsTemplateNameDecl(ND);
697     if (ND || Corrected.isKeyword()) {
698       if (LookupCtx) {
699         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
700         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
701                                 Name.getAsString() == CorrectedStr;
702         diagnoseTypo(Corrected,
703                      PDiag(diag::err_non_template_in_member_template_id_suggest)
704                          << Name << LookupCtx << DroppedSpecifier
705                          << SS.getRange(), false);
706       } else {
707         diagnoseTypo(Corrected,
708                      PDiag(diag::err_non_template_in_template_id_suggest)
709                          << Name, false);
710       }
711       if (Found)
712         Diag(Found->getLocation(),
713              diag::note_non_template_in_template_id_found);
714       return;
715     }
716   }
717 
718   Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
719     << Name << SourceRange(Less, Greater);
720   if (Found)
721     Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
722 }
723 
724 /// ActOnDependentIdExpression - Handle a dependent id-expression that
725 /// was just parsed.  This is only possible with an explicit scope
726 /// specifier naming a dependent type.
727 ExprResult
ActOnDependentIdExpression(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,bool isAddressOfOperand,const TemplateArgumentListInfo * TemplateArgs)728 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
729                                  SourceLocation TemplateKWLoc,
730                                  const DeclarationNameInfo &NameInfo,
731                                  bool isAddressOfOperand,
732                            const TemplateArgumentListInfo *TemplateArgs) {
733   DeclContext *DC = getFunctionLevelDeclContext();
734 
735   // C++11 [expr.prim.general]p12:
736   //   An id-expression that denotes a non-static data member or non-static
737   //   member function of a class can only be used:
738   //   (...)
739   //   - if that id-expression denotes a non-static data member and it
740   //     appears in an unevaluated operand.
741   //
742   // If this might be the case, form a DependentScopeDeclRefExpr instead of a
743   // CXXDependentScopeMemberExpr. The former can instantiate to either
744   // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
745   // always a MemberExpr.
746   bool MightBeCxx11UnevalField =
747       getLangOpts().CPlusPlus11 && isUnevaluatedContext();
748 
749   // Check if the nested name specifier is an enum type.
750   bool IsEnum = false;
751   if (NestedNameSpecifier *NNS = SS.getScopeRep())
752     IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType());
753 
754   if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
755       isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
756     QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
757 
758     // Since the 'this' expression is synthesized, we don't need to
759     // perform the double-lookup check.
760     NamedDecl *FirstQualifierInScope = nullptr;
761 
762     return CXXDependentScopeMemberExpr::Create(
763         Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
764         /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
765         FirstQualifierInScope, NameInfo, TemplateArgs);
766   }
767 
768   return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
769 }
770 
771 ExprResult
BuildDependentDeclRefExpr(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * TemplateArgs)772 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
773                                 SourceLocation TemplateKWLoc,
774                                 const DeclarationNameInfo &NameInfo,
775                                 const TemplateArgumentListInfo *TemplateArgs) {
776   // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
777   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
778   if (!QualifierLoc)
779     return ExprError();
780 
781   return DependentScopeDeclRefExpr::Create(
782       Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
783 }
784 
785 
786 /// Determine whether we would be unable to instantiate this template (because
787 /// 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)788 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
789                                           NamedDecl *Instantiation,
790                                           bool InstantiatedFromMember,
791                                           const NamedDecl *Pattern,
792                                           const NamedDecl *PatternDef,
793                                           TemplateSpecializationKind TSK,
794                                           bool Complain /*= true*/) {
795   assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
796          isa<VarDecl>(Instantiation));
797 
798   bool IsEntityBeingDefined = false;
799   if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
800     IsEntityBeingDefined = TD->isBeingDefined();
801 
802   if (PatternDef && !IsEntityBeingDefined) {
803     NamedDecl *SuggestedDef = nullptr;
804     if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
805                                 &SuggestedDef,
806                                 /*OnlyNeedComplete*/ false)) {
807       // If we're allowed to diagnose this and recover, do so.
808       bool Recover = Complain && !isSFINAEContext();
809       if (Complain)
810         diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
811                               Sema::MissingImportKind::Definition, Recover);
812       return !Recover;
813     }
814     return false;
815   }
816 
817   if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
818     return true;
819 
820   std::optional<unsigned> Note;
821   QualType InstantiationTy;
822   if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
823     InstantiationTy = Context.getTypeDeclType(TD);
824   if (PatternDef) {
825     Diag(PointOfInstantiation,
826          diag::err_template_instantiate_within_definition)
827       << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
828       << InstantiationTy;
829     // Not much point in noting the template declaration here, since
830     // we're lexically inside it.
831     Instantiation->setInvalidDecl();
832   } else if (InstantiatedFromMember) {
833     if (isa<FunctionDecl>(Instantiation)) {
834       Diag(PointOfInstantiation,
835            diag::err_explicit_instantiation_undefined_member)
836         << /*member function*/ 1 << Instantiation->getDeclName()
837         << Instantiation->getDeclContext();
838       Note = diag::note_explicit_instantiation_here;
839     } else {
840       assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
841       Diag(PointOfInstantiation,
842            diag::err_implicit_instantiate_member_undefined)
843         << InstantiationTy;
844       Note = diag::note_member_declared_at;
845     }
846   } else {
847     if (isa<FunctionDecl>(Instantiation)) {
848       Diag(PointOfInstantiation,
849            diag::err_explicit_instantiation_undefined_func_template)
850         << Pattern;
851       Note = diag::note_explicit_instantiation_here;
852     } else if (isa<TagDecl>(Instantiation)) {
853       Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
854         << (TSK != TSK_ImplicitInstantiation)
855         << InstantiationTy;
856       Note = diag::note_template_decl_here;
857     } else {
858       assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
859       if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
860         Diag(PointOfInstantiation,
861              diag::err_explicit_instantiation_undefined_var_template)
862           << Instantiation;
863         Instantiation->setInvalidDecl();
864       } else
865         Diag(PointOfInstantiation,
866              diag::err_explicit_instantiation_undefined_member)
867           << /*static data member*/ 2 << Instantiation->getDeclName()
868           << Instantiation->getDeclContext();
869       Note = diag::note_explicit_instantiation_here;
870     }
871   }
872   if (Note) // Diagnostics were emitted.
873     Diag(Pattern->getLocation(), *Note);
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   Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName();
899   Diag(PrevDecl->getLocation(), diag::note_template_param_here);
900 }
901 
902 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
903 /// the parameter D to reference the templated declaration and return a pointer
904 /// to the template declaration. Otherwise, do nothing to D and return null.
AdjustDeclIfTemplate(Decl * & D)905 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
906   if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
907     D = Temp->getTemplatedDecl();
908     return Temp;
909   }
910   return nullptr;
911 }
912 
getTemplatePackExpansion(SourceLocation EllipsisLoc) const913 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
914                                              SourceLocation EllipsisLoc) const {
915   assert(Kind == Template &&
916          "Only template template arguments can be pack expansions here");
917   assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
918          "Template template argument pack expansion without packs");
919   ParsedTemplateArgument Result(*this);
920   Result.EllipsisLoc = EllipsisLoc;
921   return Result;
922 }
923 
translateTemplateArgument(Sema & SemaRef,const ParsedTemplateArgument & Arg)924 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
925                                             const ParsedTemplateArgument &Arg) {
926 
927   switch (Arg.getKind()) {
928   case ParsedTemplateArgument::Type: {
929     TypeSourceInfo *DI;
930     QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
931     if (!DI)
932       DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
933     return TemplateArgumentLoc(TemplateArgument(T), DI);
934   }
935 
936   case ParsedTemplateArgument::NonType: {
937     Expr *E = static_cast<Expr *>(Arg.getAsExpr());
938     return TemplateArgumentLoc(TemplateArgument(E), E);
939   }
940 
941   case ParsedTemplateArgument::Template: {
942     TemplateName Template = Arg.getAsTemplate().get();
943     TemplateArgument TArg;
944     if (Arg.getEllipsisLoc().isValid())
945       TArg = TemplateArgument(Template, std::optional<unsigned int>());
946     else
947       TArg = Template;
948     return TemplateArgumentLoc(
949         SemaRef.Context, TArg,
950         Arg.getScopeSpec().getWithLocInContext(SemaRef.Context),
951         Arg.getLocation(), Arg.getEllipsisLoc());
952   }
953   }
954 
955   llvm_unreachable("Unhandled parsed template argument");
956 }
957 
958 /// Translates template arguments as provided by the parser
959 /// into template arguments used by semantic analysis.
translateTemplateArguments(const ASTTemplateArgsPtr & TemplateArgsIn,TemplateArgumentListInfo & TemplateArgs)960 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
961                                       TemplateArgumentListInfo &TemplateArgs) {
962  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
963    TemplateArgs.addArgument(translateTemplateArgument(*this,
964                                                       TemplateArgsIn[I]));
965 }
966 
maybeDiagnoseTemplateParameterShadow(Sema & SemaRef,Scope * S,SourceLocation Loc,IdentifierInfo * Name)967 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
968                                                  SourceLocation Loc,
969                                                  IdentifierInfo *Name) {
970   NamedDecl *PrevDecl = SemaRef.LookupSingleName(
971       S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
972   if (PrevDecl && PrevDecl->isTemplateParameter())
973     SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
974 }
975 
976 /// Convert a parsed type into a parsed template argument. This is mostly
977 /// trivial, except that we may have parsed a C++17 deduced class template
978 /// specialization type, in which case we should form a template template
979 /// argument instead of a type template argument.
ActOnTemplateTypeArgument(TypeResult ParsedType)980 ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
981   TypeSourceInfo *TInfo;
982   QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
983   if (T.isNull())
984     return ParsedTemplateArgument();
985   assert(TInfo && "template argument with no location");
986 
987   // If we might have formed a deduced template specialization type, convert
988   // it to a template template argument.
989   if (getLangOpts().CPlusPlus17) {
990     TypeLoc TL = TInfo->getTypeLoc();
991     SourceLocation EllipsisLoc;
992     if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
993       EllipsisLoc = PET.getEllipsisLoc();
994       TL = PET.getPatternLoc();
995     }
996 
997     CXXScopeSpec SS;
998     if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
999       SS.Adopt(ET.getQualifierLoc());
1000       TL = ET.getNamedTypeLoc();
1001     }
1002 
1003     if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1004       TemplateName Name = DTST.getTypePtr()->getTemplateName();
1005       if (SS.isSet())
1006         Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
1007                                                 /*HasTemplateKeyword=*/false,
1008                                                 Name);
1009       ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
1010                                     DTST.getTemplateNameLoc());
1011       if (EllipsisLoc.isValid())
1012         Result = Result.getTemplatePackExpansion(EllipsisLoc);
1013       return Result;
1014     }
1015   }
1016 
1017   // This is a normal type template argument. Note, if the type template
1018   // argument is an injected-class-name for a template, it has a dual nature
1019   // and can be used as either a type or a template. We handle that in
1020   // convertTypeTemplateArgumentToTemplate.
1021   return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1022                                 ParsedType.get().getAsOpaquePtr(),
1023                                 TInfo->getTypeLoc().getBeginLoc());
1024 }
1025 
1026 /// ActOnTypeParameter - Called when a C++ template type parameter
1027 /// (e.g., "typename T") has been parsed. Typename specifies whether
1028 /// the keyword "typename" was used to declare the type parameter
1029 /// (otherwise, "class" was used), and KeyLoc is the location of the
1030 /// "class" or "typename" keyword. ParamName is the name of the
1031 /// parameter (NULL indicates an unnamed template parameter) and
1032 /// ParamNameLoc is the location of the parameter name (if any).
1033 /// If the type parameter has a default argument, it will be added
1034 /// 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)1035 NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1036                                     SourceLocation EllipsisLoc,
1037                                     SourceLocation KeyLoc,
1038                                     IdentifierInfo *ParamName,
1039                                     SourceLocation ParamNameLoc,
1040                                     unsigned Depth, unsigned Position,
1041                                     SourceLocation EqualLoc,
1042                                     ParsedType DefaultArg,
1043                                     bool HasTypeConstraint) {
1044   assert(S->isTemplateParamScope() &&
1045          "Template type parameter not in template parameter scope!");
1046 
1047   bool IsParameterPack = EllipsisLoc.isValid();
1048   TemplateTypeParmDecl *Param
1049     = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1050                                    KeyLoc, ParamNameLoc, Depth, Position,
1051                                    ParamName, Typename, IsParameterPack,
1052                                    HasTypeConstraint);
1053   Param->setAccess(AS_public);
1054 
1055   if (Param->isParameterPack())
1056     if (auto *LSI = getEnclosingLambda())
1057       LSI->LocalPacks.push_back(Param);
1058 
1059   if (ParamName) {
1060     maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1061 
1062     // Add the template parameter into the current scope.
1063     S->AddDecl(Param);
1064     IdResolver.AddDecl(Param);
1065   }
1066 
1067   // C++0x [temp.param]p9:
1068   //   A default template-argument may be specified for any kind of
1069   //   template-parameter that is not a template parameter pack.
1070   if (DefaultArg && IsParameterPack) {
1071     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1072     DefaultArg = nullptr;
1073   }
1074 
1075   // Handle the default argument, if provided.
1076   if (DefaultArg) {
1077     TypeSourceInfo *DefaultTInfo;
1078     GetTypeFromParser(DefaultArg, &DefaultTInfo);
1079 
1080     assert(DefaultTInfo && "expected source information for type");
1081 
1082     // Check for unexpanded parameter packs.
1083     if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1084                                         UPPC_DefaultArgument))
1085       return Param;
1086 
1087     // Check the template argument itself.
1088     if (CheckTemplateArgument(DefaultTInfo)) {
1089       Param->setInvalidDecl();
1090       return Param;
1091     }
1092 
1093     Param->setDefaultArgument(DefaultTInfo);
1094   }
1095 
1096   return Param;
1097 }
1098 
1099 /// Convert the parser's template argument list representation into our form.
1100 static TemplateArgumentListInfo
makeTemplateArgumentListInfo(Sema & S,TemplateIdAnnotation & TemplateId)1101 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1102   TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1103                                         TemplateId.RAngleLoc);
1104   ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1105                                      TemplateId.NumArgs);
1106   S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1107   return TemplateArgs;
1108 }
1109 
ActOnTypeConstraint(const CXXScopeSpec & SS,TemplateIdAnnotation * TypeConstr,TemplateTypeParmDecl * ConstrainedParameter,SourceLocation EllipsisLoc)1110 bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1111                                TemplateIdAnnotation *TypeConstr,
1112                                TemplateTypeParmDecl *ConstrainedParameter,
1113                                SourceLocation EllipsisLoc) {
1114   return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1115                              false);
1116 }
1117 
BuildTypeConstraint(const CXXScopeSpec & SS,TemplateIdAnnotation * TypeConstr,TemplateTypeParmDecl * ConstrainedParameter,SourceLocation EllipsisLoc,bool AllowUnexpandedPack)1118 bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1119                                TemplateIdAnnotation *TypeConstr,
1120                                TemplateTypeParmDecl *ConstrainedParameter,
1121                                SourceLocation EllipsisLoc,
1122                                bool AllowUnexpandedPack) {
1123   TemplateName TN = TypeConstr->Template.get();
1124   ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1125 
1126   // C++2a [temp.param]p4:
1127   //     [...] The concept designated by a type-constraint shall be a type
1128   //     concept ([temp.concept]).
1129   if (!CD->isTypeConcept()) {
1130     Diag(TypeConstr->TemplateNameLoc,
1131          diag::err_type_constraint_non_type_concept);
1132     return true;
1133   }
1134 
1135   bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1136 
1137   if (!WereArgsSpecified &&
1138       CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1139     Diag(TypeConstr->TemplateNameLoc,
1140          diag::err_type_constraint_missing_arguments) << CD;
1141     return true;
1142   }
1143 
1144   DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1145                                   TypeConstr->TemplateNameLoc);
1146 
1147   TemplateArgumentListInfo TemplateArgs;
1148   if (TypeConstr->LAngleLoc.isValid()) {
1149     TemplateArgs =
1150         makeTemplateArgumentListInfo(*this, *TypeConstr);
1151 
1152     if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1153       for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1154         if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint))
1155           return true;
1156       }
1157     }
1158   }
1159   return AttachTypeConstraint(
1160       SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1161       ConceptName, CD,
1162       TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1163       ConstrainedParameter, EllipsisLoc);
1164 }
1165 
1166 template<typename ArgumentLocAppender>
formImmediatelyDeclaredConstraint(Sema & S,NestedNameSpecifierLoc NS,DeclarationNameInfo NameInfo,ConceptDecl * NamedConcept,SourceLocation LAngleLoc,SourceLocation RAngleLoc,QualType ConstrainedType,SourceLocation ParamNameLoc,ArgumentLocAppender Appender,SourceLocation EllipsisLoc)1167 static ExprResult formImmediatelyDeclaredConstraint(
1168     Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1169     ConceptDecl *NamedConcept, SourceLocation LAngleLoc,
1170     SourceLocation RAngleLoc, QualType ConstrainedType,
1171     SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1172     SourceLocation EllipsisLoc) {
1173 
1174   TemplateArgumentListInfo ConstraintArgs;
1175   ConstraintArgs.addArgument(
1176     S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1177                                     /*NTTPType=*/QualType(), ParamNameLoc));
1178 
1179   ConstraintArgs.setRAngleLoc(RAngleLoc);
1180   ConstraintArgs.setLAngleLoc(LAngleLoc);
1181   Appender(ConstraintArgs);
1182 
1183   // C++2a [temp.param]p4:
1184   //     [...] This constraint-expression E is called the immediately-declared
1185   //     constraint of T. [...]
1186   CXXScopeSpec SS;
1187   SS.Adopt(NS);
1188   ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1189       SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1190       /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
1191   if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1192     return ImmediatelyDeclaredConstraint;
1193 
1194   // C++2a [temp.param]p4:
1195   //     [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1196   //
1197   // We have the following case:
1198   //
1199   // template<typename T> concept C1 = true;
1200   // template<C1... T> struct s1;
1201   //
1202   // The constraint: (C1<T> && ...)
1203   //
1204   // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1205   // any unqualified lookups for 'operator&&' here.
1206   return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1207                             /*LParenLoc=*/SourceLocation(),
1208                             ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1209                             EllipsisLoc, /*RHS=*/nullptr,
1210                             /*RParenLoc=*/SourceLocation(),
1211                             /*NumExpansions=*/std::nullopt);
1212 }
1213 
1214 /// Attach a type-constraint to a template parameter.
1215 /// \returns true if an error occurred. This can happen if the
1216 /// immediately-declared constraint could not be formed (e.g. incorrect number
1217 /// of arguments for the named concept).
AttachTypeConstraint(NestedNameSpecifierLoc NS,DeclarationNameInfo NameInfo,ConceptDecl * NamedConcept,const TemplateArgumentListInfo * TemplateArgs,TemplateTypeParmDecl * ConstrainedParameter,SourceLocation EllipsisLoc)1218 bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1219                                 DeclarationNameInfo NameInfo,
1220                                 ConceptDecl *NamedConcept,
1221                                 const TemplateArgumentListInfo *TemplateArgs,
1222                                 TemplateTypeParmDecl *ConstrainedParameter,
1223                                 SourceLocation EllipsisLoc) {
1224   // C++2a [temp.param]p4:
1225   //     [...] If Q is of the form C<A1, ..., An>, then let E' be
1226   //     C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1227   const ASTTemplateArgumentListInfo *ArgsAsWritten =
1228     TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1229                                                        *TemplateArgs) : nullptr;
1230 
1231   QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1232 
1233   ExprResult ImmediatelyDeclaredConstraint =
1234       formImmediatelyDeclaredConstraint(
1235           *this, NS, NameInfo, NamedConcept,
1236           TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1237           TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1238           ParamAsArgument, ConstrainedParameter->getLocation(),
1239           [&] (TemplateArgumentListInfo &ConstraintArgs) {
1240             if (TemplateArgs)
1241               for (const auto &ArgLoc : TemplateArgs->arguments())
1242                 ConstraintArgs.addArgument(ArgLoc);
1243           }, EllipsisLoc);
1244   if (ImmediatelyDeclaredConstraint.isInvalid())
1245     return true;
1246 
1247   ConstrainedParameter->setTypeConstraint(NS, NameInfo,
1248                                           /*FoundDecl=*/NamedConcept,
1249                                           NamedConcept, ArgsAsWritten,
1250                                           ImmediatelyDeclaredConstraint.get());
1251   return false;
1252 }
1253 
AttachTypeConstraint(AutoTypeLoc TL,NonTypeTemplateParmDecl * NTTP,SourceLocation EllipsisLoc)1254 bool Sema::AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *NTTP,
1255                                 SourceLocation EllipsisLoc) {
1256   if (NTTP->getType() != TL.getType() ||
1257       TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1258     Diag(NTTP->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1259          diag::err_unsupported_placeholder_constraint)
1260        << NTTP->getTypeSourceInfo()->getTypeLoc().getSourceRange();
1261     return true;
1262   }
1263   // FIXME: Concepts: This should be the type of the placeholder, but this is
1264   // unclear in the wording right now.
1265   DeclRefExpr *Ref =
1266       BuildDeclRefExpr(NTTP, NTTP->getType(), VK_PRValue, NTTP->getLocation());
1267   if (!Ref)
1268     return true;
1269   ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1270       *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
1271       TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(),
1272       BuildDecltypeType(Ref), NTTP->getLocation(),
1273       [&](TemplateArgumentListInfo &ConstraintArgs) {
1274         for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1275           ConstraintArgs.addArgument(TL.getArgLoc(I));
1276       },
1277       EllipsisLoc);
1278   if (ImmediatelyDeclaredConstraint.isInvalid() ||
1279      !ImmediatelyDeclaredConstraint.isUsable())
1280     return true;
1281 
1282   NTTP->setPlaceholderTypeConstraint(ImmediatelyDeclaredConstraint.get());
1283   return false;
1284 }
1285 
1286 /// Check that the type of a non-type template parameter is
1287 /// well-formed.
1288 ///
1289 /// \returns the (possibly-promoted) parameter type if valid;
1290 /// otherwise, produces a diagnostic and returns a NULL type.
CheckNonTypeTemplateParameterType(TypeSourceInfo * & TSI,SourceLocation Loc)1291 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1292                                                  SourceLocation Loc) {
1293   if (TSI->getType()->isUndeducedType()) {
1294     // C++17 [temp.dep.expr]p3:
1295     //   An id-expression is type-dependent if it contains
1296     //    - an identifier associated by name lookup with a non-type
1297     //      template-parameter declared with a type that contains a
1298     //      placeholder type (7.1.7.4),
1299     TSI = SubstAutoTypeSourceInfoDependent(TSI);
1300   }
1301 
1302   return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1303 }
1304 
1305 /// Require the given type to be a structural type, and diagnose if it is not.
1306 ///
1307 /// \return \c true if an error was produced.
RequireStructuralType(QualType T,SourceLocation Loc)1308 bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1309   if (T->isDependentType())
1310     return false;
1311 
1312   if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1313     return true;
1314 
1315   if (T->isStructuralType())
1316     return false;
1317 
1318   // Structural types are required to be object types or lvalue references.
1319   if (T->isRValueReferenceType()) {
1320     Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1321     return true;
1322   }
1323 
1324   // Don't mention structural types in our diagnostic prior to C++20. Also,
1325   // there's not much more we can say about non-scalar non-class types --
1326   // because we can't see functions or arrays here, those can only be language
1327   // extensions.
1328   if (!getLangOpts().CPlusPlus20 ||
1329       (!T->isScalarType() && !T->isRecordType())) {
1330     Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1331     return true;
1332   }
1333 
1334   // Structural types are required to be literal types.
1335   if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1336     return true;
1337 
1338   Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1339 
1340   // Drill down into the reason why the class is non-structural.
1341   while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1342     // All members are required to be public and non-mutable, and can't be of
1343     // rvalue reference type. Check these conditions first to prefer a "local"
1344     // reason over a more distant one.
1345     for (const FieldDecl *FD : RD->fields()) {
1346       if (FD->getAccess() != AS_public) {
1347         Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1348         return true;
1349       }
1350       if (FD->isMutable()) {
1351         Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1352         return true;
1353       }
1354       if (FD->getType()->isRValueReferenceType()) {
1355         Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1356             << T;
1357         return true;
1358       }
1359     }
1360 
1361     // All bases are required to be public.
1362     for (const auto &BaseSpec : RD->bases()) {
1363       if (BaseSpec.getAccessSpecifier() != AS_public) {
1364         Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1365             << T << 1;
1366         return true;
1367       }
1368     }
1369 
1370     // All subobjects are required to be of structural types.
1371     SourceLocation SubLoc;
1372     QualType SubType;
1373     int Kind = -1;
1374 
1375     for (const FieldDecl *FD : RD->fields()) {
1376       QualType T = Context.getBaseElementType(FD->getType());
1377       if (!T->isStructuralType()) {
1378         SubLoc = FD->getLocation();
1379         SubType = T;
1380         Kind = 0;
1381         break;
1382       }
1383     }
1384 
1385     if (Kind == -1) {
1386       for (const auto &BaseSpec : RD->bases()) {
1387         QualType T = BaseSpec.getType();
1388         if (!T->isStructuralType()) {
1389           SubLoc = BaseSpec.getBaseTypeLoc();
1390           SubType = T;
1391           Kind = 1;
1392           break;
1393         }
1394       }
1395     }
1396 
1397     assert(Kind != -1 && "couldn't find reason why type is not structural");
1398     Diag(SubLoc, diag::note_not_structural_subobject)
1399         << T << Kind << SubType;
1400     T = SubType;
1401     RD = T->getAsCXXRecordDecl();
1402   }
1403 
1404   return true;
1405 }
1406 
CheckNonTypeTemplateParameterType(QualType T,SourceLocation Loc)1407 QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1408                                                  SourceLocation Loc) {
1409   // We don't allow variably-modified types as the type of non-type template
1410   // parameters.
1411   if (T->isVariablyModifiedType()) {
1412     Diag(Loc, diag::err_variably_modified_nontype_template_param)
1413       << T;
1414     return QualType();
1415   }
1416 
1417   // C++ [temp.param]p4:
1418   //
1419   // A non-type template-parameter shall have one of the following
1420   // (optionally cv-qualified) types:
1421   //
1422   //       -- integral or enumeration type,
1423   if (T->isIntegralOrEnumerationType() ||
1424       //   -- pointer to object or pointer to function,
1425       T->isPointerType() ||
1426       //   -- lvalue reference to object or lvalue reference to function,
1427       T->isLValueReferenceType() ||
1428       //   -- pointer to member,
1429       T->isMemberPointerType() ||
1430       //   -- std::nullptr_t, or
1431       T->isNullPtrType() ||
1432       //   -- a type that contains a placeholder type.
1433       T->isUndeducedType()) {
1434     // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1435     // are ignored when determining its type.
1436     return T.getUnqualifiedType();
1437   }
1438 
1439   // C++ [temp.param]p8:
1440   //
1441   //   A non-type template-parameter of type "array of T" or
1442   //   "function returning T" is adjusted to be of type "pointer to
1443   //   T" or "pointer to function returning T", respectively.
1444   if (T->isArrayType() || T->isFunctionType())
1445     return Context.getDecayedType(T);
1446 
1447   // If T is a dependent type, we can't do the check now, so we
1448   // assume that it is well-formed. Note that stripping off the
1449   // qualifiers here is not really correct if T turns out to be
1450   // an array type, but we'll recompute the type everywhere it's
1451   // used during instantiation, so that should be OK. (Using the
1452   // qualified type is equally wrong.)
1453   if (T->isDependentType())
1454     return T.getUnqualifiedType();
1455 
1456   // C++20 [temp.param]p6:
1457   //   -- a structural type
1458   if (RequireStructuralType(T, Loc))
1459     return QualType();
1460 
1461   if (!getLangOpts().CPlusPlus20) {
1462     // FIXME: Consider allowing structural types as an extension in C++17. (In
1463     // earlier language modes, the template argument evaluation rules are too
1464     // inflexible.)
1465     Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1466     return QualType();
1467   }
1468 
1469   Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1470   return T.getUnqualifiedType();
1471 }
1472 
ActOnNonTypeTemplateParameter(Scope * S,Declarator & D,unsigned Depth,unsigned Position,SourceLocation EqualLoc,Expr * Default)1473 NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1474                                           unsigned Depth,
1475                                           unsigned Position,
1476                                           SourceLocation EqualLoc,
1477                                           Expr *Default) {
1478   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
1479 
1480   // Check that we have valid decl-specifiers specified.
1481   auto CheckValidDeclSpecifiers = [this, &D] {
1482     // C++ [temp.param]
1483     // p1
1484     //   template-parameter:
1485     //     ...
1486     //     parameter-declaration
1487     // p2
1488     //   ... A storage class shall not be specified in a template-parameter
1489     //   declaration.
1490     // [dcl.typedef]p1:
1491     //   The typedef specifier [...] shall not be used in the decl-specifier-seq
1492     //   of a parameter-declaration
1493     const DeclSpec &DS = D.getDeclSpec();
1494     auto EmitDiag = [this](SourceLocation Loc) {
1495       Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1496           << FixItHint::CreateRemoval(Loc);
1497     };
1498     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1499       EmitDiag(DS.getStorageClassSpecLoc());
1500 
1501     if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1502       EmitDiag(DS.getThreadStorageClassSpecLoc());
1503 
1504     // [dcl.inline]p1:
1505     //   The inline specifier can be applied only to the declaration or
1506     //   definition of a variable or function.
1507 
1508     if (DS.isInlineSpecified())
1509       EmitDiag(DS.getInlineSpecLoc());
1510 
1511     // [dcl.constexpr]p1:
1512     //   The constexpr specifier shall be applied only to the definition of a
1513     //   variable or variable template or the declaration of a function or
1514     //   function template.
1515 
1516     if (DS.hasConstexprSpecifier())
1517       EmitDiag(DS.getConstexprSpecLoc());
1518 
1519     // [dcl.fct.spec]p1:
1520     //   Function-specifiers can be used only in function declarations.
1521 
1522     if (DS.isVirtualSpecified())
1523       EmitDiag(DS.getVirtualSpecLoc());
1524 
1525     if (DS.hasExplicitSpecifier())
1526       EmitDiag(DS.getExplicitSpecLoc());
1527 
1528     if (DS.isNoreturnSpecified())
1529       EmitDiag(DS.getNoreturnSpecLoc());
1530   };
1531 
1532   CheckValidDeclSpecifiers();
1533 
1534   if (const auto *T = TInfo->getType()->getContainedDeducedType())
1535     if (isa<AutoType>(T))
1536       Diag(D.getIdentifierLoc(),
1537            diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1538           << QualType(TInfo->getType()->getContainedAutoType(), 0);
1539 
1540   assert(S->isTemplateParamScope() &&
1541          "Non-type template parameter not in template parameter scope!");
1542   bool Invalid = false;
1543 
1544   QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1545   if (T.isNull()) {
1546     T = Context.IntTy; // Recover with an 'int' type.
1547     Invalid = true;
1548   }
1549 
1550   CheckFunctionOrTemplateParamDeclarator(S, D);
1551 
1552   IdentifierInfo *ParamName = D.getIdentifier();
1553   bool IsParameterPack = D.hasEllipsis();
1554   NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1555       Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1556       D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1557       TInfo);
1558   Param->setAccess(AS_public);
1559 
1560   if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1561     if (TL.isConstrained())
1562       if (AttachTypeConstraint(TL, Param, D.getEllipsisLoc()))
1563         Invalid = true;
1564 
1565   if (Invalid)
1566     Param->setInvalidDecl();
1567 
1568   if (Param->isParameterPack())
1569     if (auto *LSI = getEnclosingLambda())
1570       LSI->LocalPacks.push_back(Param);
1571 
1572   if (ParamName) {
1573     maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1574                                          ParamName);
1575 
1576     // Add the template parameter into the current scope.
1577     S->AddDecl(Param);
1578     IdResolver.AddDecl(Param);
1579   }
1580 
1581   // C++0x [temp.param]p9:
1582   //   A default template-argument may be specified for any kind of
1583   //   template-parameter that is not a template parameter pack.
1584   if (Default && IsParameterPack) {
1585     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1586     Default = nullptr;
1587   }
1588 
1589   // Check the well-formedness of the default template argument, if provided.
1590   if (Default) {
1591     // Check for unexpanded parameter packs.
1592     if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1593       return Param;
1594 
1595     TemplateArgument SugaredConverted, CanonicalConverted;
1596     ExprResult DefaultRes = CheckTemplateArgument(
1597         Param, Param->getType(), Default, SugaredConverted, CanonicalConverted,
1598         CTAK_Specified);
1599     if (DefaultRes.isInvalid()) {
1600       Param->setInvalidDecl();
1601       return Param;
1602     }
1603     Default = DefaultRes.get();
1604 
1605     Param->setDefaultArgument(Default);
1606   }
1607 
1608   return Param;
1609 }
1610 
1611 /// ActOnTemplateTemplateParameter - Called when a C++ template template
1612 /// parameter (e.g. T in template <template \<typename> class T> class array)
1613 /// 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)1614 NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1615                                            SourceLocation TmpLoc,
1616                                            TemplateParameterList *Params,
1617                                            SourceLocation EllipsisLoc,
1618                                            IdentifierInfo *Name,
1619                                            SourceLocation NameLoc,
1620                                            unsigned Depth,
1621                                            unsigned Position,
1622                                            SourceLocation EqualLoc,
1623                                            ParsedTemplateArgument Default) {
1624   assert(S->isTemplateParamScope() &&
1625          "Template template parameter not in template parameter scope!");
1626 
1627   // Construct the parameter object.
1628   bool IsParameterPack = EllipsisLoc.isValid();
1629   TemplateTemplateParmDecl *Param =
1630     TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1631                                      NameLoc.isInvalid()? TmpLoc : NameLoc,
1632                                      Depth, Position, IsParameterPack,
1633                                      Name, Params);
1634   Param->setAccess(AS_public);
1635 
1636   if (Param->isParameterPack())
1637     if (auto *LSI = getEnclosingLambda())
1638       LSI->LocalPacks.push_back(Param);
1639 
1640   // If the template template parameter has a name, then link the identifier
1641   // into the scope and lookup mechanisms.
1642   if (Name) {
1643     maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1644 
1645     S->AddDecl(Param);
1646     IdResolver.AddDecl(Param);
1647   }
1648 
1649   if (Params->size() == 0) {
1650     Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1651     << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1652     Param->setInvalidDecl();
1653   }
1654 
1655   // C++0x [temp.param]p9:
1656   //   A default template-argument may be specified for any kind of
1657   //   template-parameter that is not a template parameter pack.
1658   if (IsParameterPack && !Default.isInvalid()) {
1659     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1660     Default = ParsedTemplateArgument();
1661   }
1662 
1663   if (!Default.isInvalid()) {
1664     // Check only that we have a template template argument. We don't want to
1665     // try to check well-formedness now, because our template template parameter
1666     // might have dependent types in its template parameters, which we wouldn't
1667     // be able to match now.
1668     //
1669     // If none of the template template parameter's template arguments mention
1670     // other template parameters, we could actually perform more checking here.
1671     // However, it isn't worth doing.
1672     TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1673     if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1674       Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1675         << DefaultArg.getSourceRange();
1676       return Param;
1677     }
1678 
1679     // Check for unexpanded parameter packs.
1680     if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1681                                         DefaultArg.getArgument().getAsTemplate(),
1682                                         UPPC_DefaultArgument))
1683       return Param;
1684 
1685     Param->setDefaultArgument(Context, DefaultArg);
1686   }
1687 
1688   return Param;
1689 }
1690 
1691 namespace {
1692 class ConstraintRefersToContainingTemplateChecker
1693     : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1694   bool Result = false;
1695   const FunctionDecl *Friend = nullptr;
1696   unsigned TemplateDepth = 0;
1697 
1698   // Check a record-decl that we've seen to see if it is a lexical parent of the
1699   // Friend, likely because it was referred to without its template arguments.
CheckIfContainingRecord(const CXXRecordDecl * CheckingRD)1700   void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1701     CheckingRD = CheckingRD->getMostRecentDecl();
1702 
1703     for (const DeclContext *DC = Friend->getLexicalDeclContext();
1704          DC && !DC->isFileContext(); DC = DC->getParent())
1705       if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1706         if (CheckingRD == RD->getMostRecentDecl())
1707           Result = true;
1708   }
1709 
CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl * D)1710   void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1711     assert(D->getDepth() <= TemplateDepth &&
1712            "Nothing should reference a value below the actual template depth, "
1713            "depth is likely wrong");
1714     if (D->getDepth() != TemplateDepth)
1715       Result = true;
1716 
1717     // Necessary because the type of the NTTP might be what refers to the parent
1718     // constriant.
1719     TransformType(D->getType());
1720   }
1721 
1722 public:
1723   using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>;
1724 
ConstraintRefersToContainingTemplateChecker(Sema & SemaRef,const FunctionDecl * Friend,unsigned TemplateDepth)1725   ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1726                                               const FunctionDecl *Friend,
1727                                               unsigned TemplateDepth)
1728       : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
getResult() const1729   bool getResult() const { return Result; }
1730 
1731   // This should be the only template parm type that we have to deal with.
1732   // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1733   // FunctionParmPackExpr are all partially substituted, which cannot happen
1734   // with concepts at this point in translation.
1735   using inherited::TransformTemplateTypeParmType;
TransformTemplateTypeParmType(TypeLocBuilder & TLB,TemplateTypeParmTypeLoc TL,bool)1736   QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1737                                          TemplateTypeParmTypeLoc TL, bool) {
1738     assert(TL.getDecl()->getDepth() <= TemplateDepth &&
1739            "Nothing should reference a value below the actual template depth, "
1740            "depth is likely wrong");
1741     if (TL.getDecl()->getDepth() != TemplateDepth)
1742       Result = true;
1743     return inherited::TransformTemplateTypeParmType(
1744         TLB, TL,
1745         /*SuppressObjCLifetime=*/false);
1746   }
1747 
TransformDecl(SourceLocation Loc,Decl * D)1748   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1749     if (!D)
1750       return D;
1751     // FIXME : This is possibly an incomplete list, but it is unclear what other
1752     // Decl kinds could be used to refer to the template parameters.  This is a
1753     // best guess so far based on examples currently available, but the
1754     // unreachable should catch future instances/cases.
1755     if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1756       TransformType(TD->getUnderlyingType());
1757     else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1758       CheckNonTypeTemplateParmDecl(NTTPD);
1759     else if (auto *VD = dyn_cast<ValueDecl>(D))
1760       TransformType(VD->getType());
1761     else if (auto *TD = dyn_cast<TemplateDecl>(D))
1762       TransformTemplateParameterList(TD->getTemplateParameters());
1763     else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1764       CheckIfContainingRecord(RD);
1765     else if (isa<NamedDecl>(D)) {
1766       // No direct types to visit here I believe.
1767     } else
1768       llvm_unreachable("Don't know how to handle this declaration type yet");
1769     return D;
1770   }
1771 };
1772 } // namespace
1773 
ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl * Friend,unsigned TemplateDepth,const Expr * Constraint)1774 bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1775     const FunctionDecl *Friend, unsigned TemplateDepth,
1776     const Expr *Constraint) {
1777   assert(Friend->getFriendObjectKind() && "Only works on a friend");
1778   ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1779                                                       TemplateDepth);
1780   Checker.TransformExpr(const_cast<Expr *>(Constraint));
1781   return Checker.getResult();
1782 }
1783 
1784 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1785 /// constrained by RequiresClause, that contains the template parameters in
1786 /// Params.
1787 TemplateParameterList *
ActOnTemplateParameterList(unsigned Depth,SourceLocation ExportLoc,SourceLocation TemplateLoc,SourceLocation LAngleLoc,ArrayRef<NamedDecl * > Params,SourceLocation RAngleLoc,Expr * RequiresClause)1788 Sema::ActOnTemplateParameterList(unsigned Depth,
1789                                  SourceLocation ExportLoc,
1790                                  SourceLocation TemplateLoc,
1791                                  SourceLocation LAngleLoc,
1792                                  ArrayRef<NamedDecl *> Params,
1793                                  SourceLocation RAngleLoc,
1794                                  Expr *RequiresClause) {
1795   if (ExportLoc.isValid())
1796     Diag(ExportLoc, diag::warn_template_export_unsupported);
1797 
1798   for (NamedDecl *P : Params)
1799     warnOnReservedIdentifier(P);
1800 
1801   return TemplateParameterList::Create(
1802       Context, TemplateLoc, LAngleLoc,
1803       llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1804 }
1805 
SetNestedNameSpecifier(Sema & S,TagDecl * T,const CXXScopeSpec & SS)1806 static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1807                                    const CXXScopeSpec &SS) {
1808   if (SS.isSet())
1809     T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1810 }
1811 
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)1812 DeclResult Sema::CheckClassTemplate(
1813     Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1814     CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1815     const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1816     AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1817     SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1818     TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1819   assert(TemplateParams && TemplateParams->size() > 0 &&
1820          "No template parameters");
1821   assert(TUK != TUK_Reference && "Can only declare or define class templates");
1822   bool Invalid = false;
1823 
1824   // Check that we can declare a template here.
1825   if (CheckTemplateDeclScope(S, TemplateParams))
1826     return true;
1827 
1828   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1829   assert(Kind != TTK_Enum && "can't build template of enumerated type");
1830 
1831   // There is no such thing as an unnamed class template.
1832   if (!Name) {
1833     Diag(KWLoc, diag::err_template_unnamed_class);
1834     return true;
1835   }
1836 
1837   // Find any previous declaration with this name. For a friend with no
1838   // scope explicitly specified, we only look for tag declarations (per
1839   // C++11 [basic.lookup.elab]p2).
1840   DeclContext *SemanticContext;
1841   LookupResult Previous(*this, Name, NameLoc,
1842                         (SS.isEmpty() && TUK == TUK_Friend)
1843                           ? LookupTagName : LookupOrdinaryName,
1844                         forRedeclarationInCurContext());
1845   if (SS.isNotEmpty() && !SS.isInvalid()) {
1846     SemanticContext = computeDeclContext(SS, true);
1847     if (!SemanticContext) {
1848       // FIXME: Horrible, horrible hack! We can't currently represent this
1849       // in the AST, and historically we have just ignored such friend
1850       // class templates, so don't complain here.
1851       Diag(NameLoc, TUK == TUK_Friend
1852                         ? diag::warn_template_qualified_friend_ignored
1853                         : diag::err_template_qualified_declarator_no_match)
1854           << SS.getScopeRep() << SS.getRange();
1855       return TUK != TUK_Friend;
1856     }
1857 
1858     if (RequireCompleteDeclContext(SS, SemanticContext))
1859       return true;
1860 
1861     // If we're adding a template to a dependent context, we may need to
1862     // rebuilding some of the types used within the template parameter list,
1863     // now that we know what the current instantiation is.
1864     if (SemanticContext->isDependentContext()) {
1865       ContextRAII SavedContext(*this, SemanticContext);
1866       if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1867         Invalid = true;
1868     } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1869       diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1870 
1871     LookupQualifiedName(Previous, SemanticContext);
1872   } else {
1873     SemanticContext = CurContext;
1874 
1875     // C++14 [class.mem]p14:
1876     //   If T is the name of a class, then each of the following shall have a
1877     //   name different from T:
1878     //    -- every member template of class T
1879     if (TUK != TUK_Friend &&
1880         DiagnoseClassNameShadow(SemanticContext,
1881                                 DeclarationNameInfo(Name, NameLoc)))
1882       return true;
1883 
1884     LookupName(Previous, S);
1885   }
1886 
1887   if (Previous.isAmbiguous())
1888     return true;
1889 
1890   NamedDecl *PrevDecl = nullptr;
1891   if (Previous.begin() != Previous.end())
1892     PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1893 
1894   if (PrevDecl && PrevDecl->isTemplateParameter()) {
1895     // Maybe we will complain about the shadowed template parameter.
1896     DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1897     // Just pretend that we didn't see the previous declaration.
1898     PrevDecl = nullptr;
1899   }
1900 
1901   // If there is a previous declaration with the same name, check
1902   // whether this is a valid redeclaration.
1903   ClassTemplateDecl *PrevClassTemplate =
1904       dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1905 
1906   // We may have found the injected-class-name of a class template,
1907   // class template partial specialization, or class template specialization.
1908   // In these cases, grab the template that is being defined or specialized.
1909   if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1910       cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1911     PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1912     PrevClassTemplate
1913       = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1914     if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1915       PrevClassTemplate
1916         = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1917             ->getSpecializedTemplate();
1918     }
1919   }
1920 
1921   if (TUK == TUK_Friend) {
1922     // C++ [namespace.memdef]p3:
1923     //   [...] When looking for a prior declaration of a class or a function
1924     //   declared as a friend, and when the name of the friend class or
1925     //   function is neither a qualified name nor a template-id, scopes outside
1926     //   the innermost enclosing namespace scope are not considered.
1927     if (!SS.isSet()) {
1928       DeclContext *OutermostContext = CurContext;
1929       while (!OutermostContext->isFileContext())
1930         OutermostContext = OutermostContext->getLookupParent();
1931 
1932       if (PrevDecl &&
1933           (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1934            OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1935         SemanticContext = PrevDecl->getDeclContext();
1936       } else {
1937         // Declarations in outer scopes don't matter. However, the outermost
1938         // context we computed is the semantic context for our new
1939         // declaration.
1940         PrevDecl = PrevClassTemplate = nullptr;
1941         SemanticContext = OutermostContext;
1942 
1943         // Check that the chosen semantic context doesn't already contain a
1944         // declaration of this name as a non-tag type.
1945         Previous.clear(LookupOrdinaryName);
1946         DeclContext *LookupContext = SemanticContext;
1947         while (LookupContext->isTransparentContext())
1948           LookupContext = LookupContext->getLookupParent();
1949         LookupQualifiedName(Previous, LookupContext);
1950 
1951         if (Previous.isAmbiguous())
1952           return true;
1953 
1954         if (Previous.begin() != Previous.end())
1955           PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1956       }
1957     }
1958   } else if (PrevDecl &&
1959              !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1960                             S, SS.isValid()))
1961     PrevDecl = PrevClassTemplate = nullptr;
1962 
1963   if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1964           PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1965     if (SS.isEmpty() &&
1966         !(PrevClassTemplate &&
1967           PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1968               SemanticContext->getRedeclContext()))) {
1969       Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1970       Diag(Shadow->getTargetDecl()->getLocation(),
1971            diag::note_using_decl_target);
1972       Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1973       // Recover by ignoring the old declaration.
1974       PrevDecl = PrevClassTemplate = nullptr;
1975     }
1976   }
1977 
1978   if (PrevClassTemplate) {
1979     // Ensure that the template parameter lists are compatible. Skip this check
1980     // for a friend in a dependent context: the template parameter list itself
1981     // could be dependent.
1982     if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1983         !TemplateParameterListsAreEqual(TemplateParams,
1984                                    PrevClassTemplate->getTemplateParameters(),
1985                                         /*Complain=*/true,
1986                                         TPL_TemplateMatch))
1987       return true;
1988 
1989     // C++ [temp.class]p4:
1990     //   In a redeclaration, partial specialization, explicit
1991     //   specialization or explicit instantiation of a class template,
1992     //   the class-key shall agree in kind with the original class
1993     //   template declaration (7.1.5.3).
1994     RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1995     if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1996                                       TUK == TUK_Definition,  KWLoc, Name)) {
1997       Diag(KWLoc, diag::err_use_with_wrong_tag)
1998         << Name
1999         << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2000       Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2001       Kind = PrevRecordDecl->getTagKind();
2002     }
2003 
2004     // Check for redefinition of this class template.
2005     if (TUK == TUK_Definition) {
2006       if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2007         // If we have a prior definition that is not visible, treat this as
2008         // simply making that previous definition visible.
2009         NamedDecl *Hidden = nullptr;
2010         if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2011           SkipBody->ShouldSkip = true;
2012           SkipBody->Previous = Def;
2013           auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2014           assert(Tmpl && "original definition of a class template is not a "
2015                          "class template?");
2016           makeMergedDefinitionVisible(Hidden);
2017           makeMergedDefinitionVisible(Tmpl);
2018         } else {
2019           Diag(NameLoc, diag::err_redefinition) << Name;
2020           Diag(Def->getLocation(), diag::note_previous_definition);
2021           // FIXME: Would it make sense to try to "forget" the previous
2022           // definition, as part of error recovery?
2023           return true;
2024         }
2025       }
2026     }
2027   } else if (PrevDecl) {
2028     // C++ [temp]p5:
2029     //   A class template shall not have the same name as any other
2030     //   template, class, function, object, enumeration, enumerator,
2031     //   namespace, or type in the same scope (3.3), except as specified
2032     //   in (14.5.4).
2033     Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2034     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2035     return true;
2036   }
2037 
2038   // Check the template parameter list of this declaration, possibly
2039   // merging in the template parameter list from the previous class
2040   // template declaration. Skip this check for a friend in a dependent
2041   // context, because the template parameter list might be dependent.
2042   if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2043       CheckTemplateParameterList(
2044           TemplateParams,
2045           PrevClassTemplate
2046               ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
2047               : nullptr,
2048           (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2049            SemanticContext->isDependentContext())
2050               ? TPC_ClassTemplateMember
2051               : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
2052           SkipBody))
2053     Invalid = true;
2054 
2055   if (SS.isSet()) {
2056     // If the name of the template was qualified, we must be defining the
2057     // template out-of-line.
2058     if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2059       Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
2060                                       : diag::err_member_decl_does_not_match)
2061         << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
2062       Invalid = true;
2063     }
2064   }
2065 
2066   // If this is a templated friend in a dependent context we should not put it
2067   // on the redecl chain. In some cases, the templated friend can be the most
2068   // recent declaration tricking the template instantiator to make substitutions
2069   // there.
2070   // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2071   bool ShouldAddRedecl
2072     = !(TUK == TUK_Friend && CurContext->isDependentContext());
2073 
2074   CXXRecordDecl *NewClass =
2075     CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2076                           PrevClassTemplate && ShouldAddRedecl ?
2077                             PrevClassTemplate->getTemplatedDecl() : nullptr,
2078                           /*DelayTypeCreation=*/true);
2079   SetNestedNameSpecifier(*this, NewClass, SS);
2080   if (NumOuterTemplateParamLists > 0)
2081     NewClass->setTemplateParameterListsInfo(
2082         Context,
2083         llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2084 
2085   // Add alignment attributes if necessary; these attributes are checked when
2086   // the ASTContext lays out the structure.
2087   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2088     AddAlignmentAttributesForRecord(NewClass);
2089     AddMsStructLayoutForRecord(NewClass);
2090   }
2091 
2092   ClassTemplateDecl *NewTemplate
2093     = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2094                                 DeclarationName(Name), TemplateParams,
2095                                 NewClass);
2096 
2097   if (ShouldAddRedecl)
2098     NewTemplate->setPreviousDecl(PrevClassTemplate);
2099 
2100   NewClass->setDescribedClassTemplate(NewTemplate);
2101 
2102   if (ModulePrivateLoc.isValid())
2103     NewTemplate->setModulePrivate();
2104 
2105   // Build the type for the class template declaration now.
2106   QualType T = NewTemplate->getInjectedClassNameSpecialization();
2107   T = Context.getInjectedClassNameType(NewClass, T);
2108   assert(T->isDependentType() && "Class template type is not dependent?");
2109   (void)T;
2110 
2111   // If we are providing an explicit specialization of a member that is a
2112   // class template, make a note of that.
2113   if (PrevClassTemplate &&
2114       PrevClassTemplate->getInstantiatedFromMemberTemplate())
2115     PrevClassTemplate->setMemberSpecialization();
2116 
2117   // Set the access specifier.
2118   if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
2119     SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2120 
2121   // Set the lexical context of these templates
2122   NewClass->setLexicalDeclContext(CurContext);
2123   NewTemplate->setLexicalDeclContext(CurContext);
2124 
2125   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
2126     NewClass->startDefinition();
2127 
2128   ProcessDeclAttributeList(S, NewClass, Attr);
2129 
2130   if (PrevClassTemplate)
2131     mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2132 
2133   AddPushedVisibilityAttribute(NewClass);
2134   inferGslOwnerPointerAttribute(NewClass);
2135 
2136   if (TUK != TUK_Friend) {
2137     // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2138     Scope *Outer = S;
2139     while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2140       Outer = Outer->getParent();
2141     PushOnScopeChains(NewTemplate, Outer);
2142   } else {
2143     if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2144       NewTemplate->setAccess(PrevClassTemplate->getAccess());
2145       NewClass->setAccess(PrevClassTemplate->getAccess());
2146     }
2147 
2148     NewTemplate->setObjectOfFriendDecl();
2149 
2150     // Friend templates are visible in fairly strange ways.
2151     if (!CurContext->isDependentContext()) {
2152       DeclContext *DC = SemanticContext->getRedeclContext();
2153       DC->makeDeclVisibleInContext(NewTemplate);
2154       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2155         PushOnScopeChains(NewTemplate, EnclosingScope,
2156                           /* AddToContext = */ false);
2157     }
2158 
2159     FriendDecl *Friend = FriendDecl::Create(
2160         Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2161     Friend->setAccess(AS_public);
2162     CurContext->addDecl(Friend);
2163   }
2164 
2165   if (PrevClassTemplate)
2166     CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2167 
2168   if (Invalid) {
2169     NewTemplate->setInvalidDecl();
2170     NewClass->setInvalidDecl();
2171   }
2172 
2173   ActOnDocumentableDecl(NewTemplate);
2174 
2175   if (SkipBody && SkipBody->ShouldSkip)
2176     return SkipBody->Previous;
2177 
2178   return NewTemplate;
2179 }
2180 
2181 namespace {
2182 /// Tree transform to "extract" a transformed type from a class template's
2183 /// constructor to a deduction guide.
2184 class ExtractTypeForDeductionGuide
2185   : public TreeTransform<ExtractTypeForDeductionGuide> {
2186   llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
2187 
2188 public:
2189   typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
ExtractTypeForDeductionGuide(Sema & SemaRef,llvm::SmallVectorImpl<TypedefNameDecl * > & MaterializedTypedefs)2190   ExtractTypeForDeductionGuide(
2191       Sema &SemaRef,
2192       llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
2193       : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
2194 
transform(TypeSourceInfo * TSI)2195   TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
2196 
TransformTypedefType(TypeLocBuilder & TLB,TypedefTypeLoc TL)2197   QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
2198     ASTContext &Context = SemaRef.getASTContext();
2199     TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
2200     TypedefNameDecl *Decl = OrigDecl;
2201     // Transform the underlying type of the typedef and clone the Decl only if
2202     // the typedef has a dependent context.
2203     if (OrigDecl->getDeclContext()->isDependentContext()) {
2204       TypeLocBuilder InnerTLB;
2205       QualType Transformed =
2206           TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
2207       TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
2208       if (isa<TypeAliasDecl>(OrigDecl))
2209         Decl = TypeAliasDecl::Create(
2210             Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2211             OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2212       else {
2213         assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
2214         Decl = TypedefDecl::Create(
2215             Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2216             OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2217       }
2218       MaterializedTypedefs.push_back(Decl);
2219     }
2220 
2221     QualType TDTy = Context.getTypedefType(Decl);
2222     TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
2223     TypedefTL.setNameLoc(TL.getNameLoc());
2224 
2225     return TDTy;
2226   }
2227 };
2228 
2229 /// Transform to convert portions of a constructor declaration into the
2230 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
2231 struct ConvertConstructorToDeductionGuideTransform {
ConvertConstructorToDeductionGuideTransform__anon8a5f675e0811::ConvertConstructorToDeductionGuideTransform2232   ConvertConstructorToDeductionGuideTransform(Sema &S,
2233                                               ClassTemplateDecl *Template)
2234       : SemaRef(S), Template(Template) {}
2235 
2236   Sema &SemaRef;
2237   ClassTemplateDecl *Template;
2238 
2239   DeclContext *DC = Template->getDeclContext();
2240   CXXRecordDecl *Primary = Template->getTemplatedDecl();
2241   DeclarationName DeductionGuideName =
2242       SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
2243 
2244   QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
2245 
2246   // Index adjustment to apply to convert depth-1 template parameters into
2247   // depth-0 template parameters.
2248   unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
2249 
2250   /// Transform a constructor declaration into a deduction guide.
transformConstructor__anon8a5f675e0811::ConvertConstructorToDeductionGuideTransform2251   NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
2252                                   CXXConstructorDecl *CD) {
2253     SmallVector<TemplateArgument, 16> SubstArgs;
2254 
2255     LocalInstantiationScope Scope(SemaRef);
2256 
2257     // C++ [over.match.class.deduct]p1:
2258     // -- For each constructor of the class template designated by the
2259     //    template-name, a function template with the following properties:
2260 
2261     //    -- The template parameters are the template parameters of the class
2262     //       template followed by the template parameters (including default
2263     //       template arguments) of the constructor, if any.
2264     TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2265     if (FTD) {
2266       TemplateParameterList *InnerParams = FTD->getTemplateParameters();
2267       SmallVector<NamedDecl *, 16> AllParams;
2268       AllParams.reserve(TemplateParams->size() + InnerParams->size());
2269       AllParams.insert(AllParams.begin(),
2270                        TemplateParams->begin(), TemplateParams->end());
2271       SubstArgs.reserve(InnerParams->size());
2272 
2273       // Later template parameters could refer to earlier ones, so build up
2274       // a list of substituted template arguments as we go.
2275       for (NamedDecl *Param : *InnerParams) {
2276         MultiLevelTemplateArgumentList Args;
2277         Args.setKind(TemplateSubstitutionKind::Rewrite);
2278         Args.addOuterTemplateArguments(SubstArgs);
2279         Args.addOuterRetainedLevel();
2280         NamedDecl *NewParam = transformTemplateParameter(Param, Args);
2281         if (!NewParam)
2282           return nullptr;
2283         AllParams.push_back(NewParam);
2284         SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2285             SemaRef.Context.getInjectedTemplateArg(NewParam)));
2286       }
2287 
2288       // Substitute new template parameters into requires-clause if present.
2289       Expr *RequiresClause = nullptr;
2290       if (Expr *InnerRC = InnerParams->getRequiresClause()) {
2291         MultiLevelTemplateArgumentList Args;
2292         Args.setKind(TemplateSubstitutionKind::Rewrite);
2293         Args.addOuterTemplateArguments(SubstArgs);
2294         Args.addOuterRetainedLevel();
2295         ExprResult E = SemaRef.SubstExpr(InnerRC, Args);
2296         if (E.isInvalid())
2297           return nullptr;
2298         RequiresClause = E.getAs<Expr>();
2299       }
2300 
2301       TemplateParams = TemplateParameterList::Create(
2302           SemaRef.Context, InnerParams->getTemplateLoc(),
2303           InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
2304           RequiresClause);
2305     }
2306 
2307     // If we built a new template-parameter-list, track that we need to
2308     // substitute references to the old parameters into references to the
2309     // new ones.
2310     MultiLevelTemplateArgumentList Args;
2311     Args.setKind(TemplateSubstitutionKind::Rewrite);
2312     if (FTD) {
2313       Args.addOuterTemplateArguments(SubstArgs);
2314       Args.addOuterRetainedLevel();
2315     }
2316 
2317     FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
2318                                    .getAsAdjusted<FunctionProtoTypeLoc>();
2319     assert(FPTL && "no prototype for constructor declaration");
2320 
2321     // Transform the type of the function, adjusting the return type and
2322     // replacing references to the old parameters with references to the
2323     // new ones.
2324     TypeLocBuilder TLB;
2325     SmallVector<ParmVarDecl*, 8> Params;
2326     SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
2327     QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
2328                                                   MaterializedTypedefs);
2329     if (NewType.isNull())
2330       return nullptr;
2331     TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
2332 
2333     return buildDeductionGuide(TemplateParams, CD, CD->getExplicitSpecifier(),
2334                                NewTInfo, CD->getBeginLoc(), CD->getLocation(),
2335                                CD->getEndLoc(), MaterializedTypedefs);
2336   }
2337 
2338   /// Build a deduction guide with the specified parameter types.
buildSimpleDeductionGuide__anon8a5f675e0811::ConvertConstructorToDeductionGuideTransform2339   NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
2340     SourceLocation Loc = Template->getLocation();
2341 
2342     // Build the requested type.
2343     FunctionProtoType::ExtProtoInfo EPI;
2344     EPI.HasTrailingReturn = true;
2345     QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
2346                                                 DeductionGuideName, EPI);
2347     TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
2348 
2349     FunctionProtoTypeLoc FPTL =
2350         TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
2351 
2352     // Build the parameters, needed during deduction / substitution.
2353     SmallVector<ParmVarDecl*, 4> Params;
2354     for (auto T : ParamTypes) {
2355       ParmVarDecl *NewParam = ParmVarDecl::Create(
2356           SemaRef.Context, DC, Loc, Loc, nullptr, T,
2357           SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
2358       NewParam->setScopeInfo(0, Params.size());
2359       FPTL.setParam(Params.size(), NewParam);
2360       Params.push_back(NewParam);
2361     }
2362 
2363     return buildDeductionGuide(Template->getTemplateParameters(), nullptr,
2364                                ExplicitSpecifier(), TSI, Loc, Loc, Loc);
2365   }
2366 
2367 private:
2368   /// Transform a constructor template parameter into a deduction guide template
2369   /// parameter, rebuilding any internal references to earlier parameters and
2370   /// renumbering as we go.
transformTemplateParameter__anon8a5f675e0811::ConvertConstructorToDeductionGuideTransform2371   NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
2372                                         MultiLevelTemplateArgumentList &Args) {
2373     if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
2374       // TemplateTypeParmDecl's index cannot be changed after creation, so
2375       // substitute it directly.
2376       auto *NewTTP = TemplateTypeParmDecl::Create(
2377           SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
2378           /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
2379           TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
2380           TTP->isParameterPack(), TTP->hasTypeConstraint(),
2381           TTP->isExpandedParameterPack()
2382               ? std::optional<unsigned>(TTP->getNumExpansionParameters())
2383               : std::nullopt);
2384       if (const auto *TC = TTP->getTypeConstraint())
2385         SemaRef.SubstTypeConstraint(NewTTP, TC, Args,
2386                                     /*EvaluateConstraint*/ true);
2387       if (TTP->hasDefaultArgument()) {
2388         TypeSourceInfo *InstantiatedDefaultArg =
2389             SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2390                               TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2391         if (InstantiatedDefaultArg)
2392           NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2393       }
2394       SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
2395                                                            NewTTP);
2396       return NewTTP;
2397     }
2398 
2399     if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2400       return transformTemplateParameterImpl(TTP, Args);
2401 
2402     return transformTemplateParameterImpl(
2403         cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
2404   }
2405   template<typename TemplateParmDecl>
2406   TemplateParmDecl *
transformTemplateParameterImpl__anon8a5f675e0811::ConvertConstructorToDeductionGuideTransform2407   transformTemplateParameterImpl(TemplateParmDecl *OldParam,
2408                                  MultiLevelTemplateArgumentList &Args) {
2409     // Ask the template instantiator to do the heavy lifting for us, then adjust
2410     // the index of the parameter once it's done.
2411     auto *NewParam =
2412         cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2413     assert(NewParam->getDepth() == 0 && "unexpected template param depth");
2414     NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2415     return NewParam;
2416   }
2417 
transformFunctionProtoType__anon8a5f675e0811::ConvertConstructorToDeductionGuideTransform2418   QualType transformFunctionProtoType(
2419       TypeLocBuilder &TLB, FunctionProtoTypeLoc TL,
2420       SmallVectorImpl<ParmVarDecl *> &Params,
2421       MultiLevelTemplateArgumentList &Args,
2422       SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2423     SmallVector<QualType, 4> ParamTypes;
2424     const FunctionProtoType *T = TL.getTypePtr();
2425 
2426     //    -- The types of the function parameters are those of the constructor.
2427     for (auto *OldParam : TL.getParams()) {
2428       ParmVarDecl *NewParam =
2429           transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs);
2430       if (!NewParam)
2431         return QualType();
2432       ParamTypes.push_back(NewParam->getType());
2433       Params.push_back(NewParam);
2434     }
2435 
2436     //    -- The return type is the class template specialization designated by
2437     //       the template-name and template arguments corresponding to the
2438     //       template parameters obtained from the class template.
2439     //
2440     // We use the injected-class-name type of the primary template instead.
2441     // This has the convenient property that it is different from any type that
2442     // the user can write in a deduction-guide (because they cannot enter the
2443     // context of the template), so implicit deduction guides can never collide
2444     // with explicit ones.
2445     QualType ReturnType = DeducedType;
2446     TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2447 
2448     // Resolving a wording defect, we also inherit the variadicness of the
2449     // constructor.
2450     FunctionProtoType::ExtProtoInfo EPI;
2451     EPI.Variadic = T->isVariadic();
2452     EPI.HasTrailingReturn = true;
2453 
2454     QualType Result = SemaRef.BuildFunctionType(
2455         ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2456     if (Result.isNull())
2457       return QualType();
2458 
2459     FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2460     NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
2461     NewTL.setLParenLoc(TL.getLParenLoc());
2462     NewTL.setRParenLoc(TL.getRParenLoc());
2463     NewTL.setExceptionSpecRange(SourceRange());
2464     NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
2465     for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
2466       NewTL.setParam(I, Params[I]);
2467 
2468     return Result;
2469   }
2470 
transformFunctionTypeParam__anon8a5f675e0811::ConvertConstructorToDeductionGuideTransform2471   ParmVarDecl *transformFunctionTypeParam(
2472       ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args,
2473       llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2474     TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2475     TypeSourceInfo *NewDI;
2476     if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2477       // Expand out the one and only element in each inner pack.
2478       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2479       NewDI =
2480           SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2481                             OldParam->getLocation(), OldParam->getDeclName());
2482       if (!NewDI) return nullptr;
2483       NewDI =
2484           SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2485                                      PackTL.getTypePtr()->getNumExpansions());
2486     } else
2487       NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2488                                 OldParam->getDeclName());
2489     if (!NewDI)
2490       return nullptr;
2491 
2492     // Extract the type. This (for instance) replaces references to typedef
2493     // members of the current instantiations with the definitions of those
2494     // typedefs, avoiding triggering instantiation of the deduced type during
2495     // deduction.
2496     NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
2497                 .transform(NewDI);
2498 
2499     // Resolving a wording defect, we also inherit default arguments from the
2500     // constructor.
2501     ExprResult NewDefArg;
2502     if (OldParam->hasDefaultArg()) {
2503       // We don't care what the value is (we won't use it); just create a
2504       // placeholder to indicate there is a default argument.
2505       QualType ParamTy = NewDI->getType();
2506       NewDefArg = new (SemaRef.Context)
2507           OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(),
2508                           ParamTy.getNonLValueExprType(SemaRef.Context),
2509                           ParamTy->isLValueReferenceType()   ? VK_LValue
2510                           : ParamTy->isRValueReferenceType() ? VK_XValue
2511                                                              : VK_PRValue);
2512     }
2513 
2514     ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
2515                                                 OldParam->getInnerLocStart(),
2516                                                 OldParam->getLocation(),
2517                                                 OldParam->getIdentifier(),
2518                                                 NewDI->getType(),
2519                                                 NewDI,
2520                                                 OldParam->getStorageClass(),
2521                                                 NewDefArg.get());
2522     NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2523                            OldParam->getFunctionScopeIndex());
2524     SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2525     return NewParam;
2526   }
2527 
buildDeductionGuide__anon8a5f675e0811::ConvertConstructorToDeductionGuideTransform2528   FunctionTemplateDecl *buildDeductionGuide(
2529       TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
2530       ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart,
2531       SourceLocation Loc, SourceLocation LocEnd,
2532       llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
2533     DeclarationNameInfo Name(DeductionGuideName, Loc);
2534     ArrayRef<ParmVarDecl *> Params =
2535         TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2536 
2537     // Build the implicit deduction guide template.
2538     auto *Guide =
2539         CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2540                                       TInfo->getType(), TInfo, LocEnd, Ctor);
2541     Guide->setImplicit();
2542     Guide->setParams(Params);
2543 
2544     for (auto *Param : Params)
2545       Param->setDeclContext(Guide);
2546     for (auto *TD : MaterializedTypedefs)
2547       TD->setDeclContext(Guide);
2548 
2549     auto *GuideTemplate = FunctionTemplateDecl::Create(
2550         SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2551     GuideTemplate->setImplicit();
2552     Guide->setDescribedFunctionTemplate(GuideTemplate);
2553 
2554     if (isa<CXXRecordDecl>(DC)) {
2555       Guide->setAccess(AS_public);
2556       GuideTemplate->setAccess(AS_public);
2557     }
2558 
2559     DC->addDecl(GuideTemplate);
2560     return GuideTemplate;
2561   }
2562 };
2563 }
2564 
DeclareImplicitDeductionGuides(TemplateDecl * Template,SourceLocation Loc)2565 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2566                                           SourceLocation Loc) {
2567   if (CXXRecordDecl *DefRecord =
2568           cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2569     TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
2570     Template = DescribedTemplate ? DescribedTemplate : Template;
2571   }
2572 
2573   DeclContext *DC = Template->getDeclContext();
2574   if (DC->isDependentContext())
2575     return;
2576 
2577   ConvertConstructorToDeductionGuideTransform Transform(
2578       *this, cast<ClassTemplateDecl>(Template));
2579   if (!isCompleteType(Loc, Transform.DeducedType))
2580     return;
2581 
2582   // Check whether we've already declared deduction guides for this template.
2583   // FIXME: Consider storing a flag on the template to indicate this.
2584   auto Existing = DC->lookup(Transform.DeductionGuideName);
2585   for (auto *D : Existing)
2586     if (D->isImplicit())
2587       return;
2588 
2589   // In case we were expanding a pack when we attempted to declare deduction
2590   // guides, turn off pack expansion for everything we're about to do.
2591   ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2592   // Create a template instantiation record to track the "instantiation" of
2593   // constructors into deduction guides.
2594   // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2595   // this substitution process actually fail?
2596   InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
2597   if (BuildingDeductionGuides.isInvalid())
2598     return;
2599 
2600   // Convert declared constructors into deduction guide templates.
2601   // FIXME: Skip constructors for which deduction must necessarily fail (those
2602   // for which some class template parameter without a default argument never
2603   // appears in a deduced context).
2604   bool AddedAny = false;
2605   for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2606     D = D->getUnderlyingDecl();
2607     if (D->isInvalidDecl() || D->isImplicit())
2608       continue;
2609     D = cast<NamedDecl>(D->getCanonicalDecl());
2610 
2611     auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2612     auto *CD =
2613         dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
2614     // Class-scope explicit specializations (MS extension) do not result in
2615     // deduction guides.
2616     if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
2617       continue;
2618 
2619     // Cannot make a deduction guide when unparsed arguments are present.
2620     if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) {
2621           return !P || P->hasUnparsedDefaultArg();
2622         }))
2623       continue;
2624 
2625     Transform.transformConstructor(FTD, CD);
2626     AddedAny = true;
2627   }
2628 
2629   // C++17 [over.match.class.deduct]
2630   //    --  If C is not defined or does not declare any constructors, an
2631   //    additional function template derived as above from a hypothetical
2632   //    constructor C().
2633   if (!AddedAny)
2634     Transform.buildSimpleDeductionGuide(std::nullopt);
2635 
2636   //    -- An additional function template derived as above from a hypothetical
2637   //    constructor C(C), called the copy deduction candidate.
2638   cast<CXXDeductionGuideDecl>(
2639       cast<FunctionTemplateDecl>(
2640           Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2641           ->getTemplatedDecl())
2642       ->setIsCopyDeductionCandidate();
2643 }
2644 
2645 /// Diagnose the presence of a default template argument on a
2646 /// template parameter, which is ill-formed in certain contexts.
2647 ///
2648 /// \returns true if the default template argument should be dropped.
DiagnoseDefaultTemplateArgument(Sema & S,Sema::TemplateParamListContext TPC,SourceLocation ParamLoc,SourceRange DefArgRange)2649 static bool DiagnoseDefaultTemplateArgument(Sema &S,
2650                                             Sema::TemplateParamListContext TPC,
2651                                             SourceLocation ParamLoc,
2652                                             SourceRange DefArgRange) {
2653   switch (TPC) {
2654   case Sema::TPC_ClassTemplate:
2655   case Sema::TPC_VarTemplate:
2656   case Sema::TPC_TypeAliasTemplate:
2657     return false;
2658 
2659   case Sema::TPC_FunctionTemplate:
2660   case Sema::TPC_FriendFunctionTemplateDefinition:
2661     // C++ [temp.param]p9:
2662     //   A default template-argument shall not be specified in a
2663     //   function template declaration or a function template
2664     //   definition [...]
2665     //   If a friend function template declaration specifies a default
2666     //   template-argument, that declaration shall be a definition and shall be
2667     //   the only declaration of the function template in the translation unit.
2668     // (C++98/03 doesn't have this wording; see DR226).
2669     S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2670          diag::warn_cxx98_compat_template_parameter_default_in_function_template
2671            : diag::ext_template_parameter_default_in_function_template)
2672       << DefArgRange;
2673     return false;
2674 
2675   case Sema::TPC_ClassTemplateMember:
2676     // C++0x [temp.param]p9:
2677     //   A default template-argument shall not be specified in the
2678     //   template-parameter-lists of the definition of a member of a
2679     //   class template that appears outside of the member's class.
2680     S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2681       << DefArgRange;
2682     return true;
2683 
2684   case Sema::TPC_FriendClassTemplate:
2685   case Sema::TPC_FriendFunctionTemplate:
2686     // C++ [temp.param]p9:
2687     //   A default template-argument shall not be specified in a
2688     //   friend template declaration.
2689     S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2690       << DefArgRange;
2691     return true;
2692 
2693     // FIXME: C++0x [temp.param]p9 allows default template-arguments
2694     // for friend function templates if there is only a single
2695     // declaration (and it is a definition). Strange!
2696   }
2697 
2698   llvm_unreachable("Invalid TemplateParamListContext!");
2699 }
2700 
2701 /// Check for unexpanded parameter packs within the template parameters
2702 /// of a template template parameter, recursively.
DiagnoseUnexpandedParameterPacks(Sema & S,TemplateTemplateParmDecl * TTP)2703 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2704                                              TemplateTemplateParmDecl *TTP) {
2705   // A template template parameter which is a parameter pack is also a pack
2706   // expansion.
2707   if (TTP->isParameterPack())
2708     return false;
2709 
2710   TemplateParameterList *Params = TTP->getTemplateParameters();
2711   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2712     NamedDecl *P = Params->getParam(I);
2713     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2714       if (!TTP->isParameterPack())
2715         if (const TypeConstraint *TC = TTP->getTypeConstraint())
2716           if (TC->hasExplicitTemplateArgs())
2717             for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2718               if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2719                                                     Sema::UPPC_TypeConstraint))
2720                 return true;
2721       continue;
2722     }
2723 
2724     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2725       if (!NTTP->isParameterPack() &&
2726           S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2727                                             NTTP->getTypeSourceInfo(),
2728                                       Sema::UPPC_NonTypeTemplateParameterType))
2729         return true;
2730 
2731       continue;
2732     }
2733 
2734     if (TemplateTemplateParmDecl *InnerTTP
2735                                         = dyn_cast<TemplateTemplateParmDecl>(P))
2736       if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2737         return true;
2738   }
2739 
2740   return false;
2741 }
2742 
2743 /// Checks the validity of a template parameter list, possibly
2744 /// considering the template parameter list from a previous
2745 /// declaration.
2746 ///
2747 /// If an "old" template parameter list is provided, it must be
2748 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
2749 /// template parameter list.
2750 ///
2751 /// \param NewParams Template parameter list for a new template
2752 /// declaration. This template parameter list will be updated with any
2753 /// default arguments that are carried through from the previous
2754 /// template parameter list.
2755 ///
2756 /// \param OldParams If provided, template parameter list from a
2757 /// previous declaration of the same template. Default template
2758 /// arguments will be merged from the old template parameter list to
2759 /// the new template parameter list.
2760 ///
2761 /// \param TPC Describes the context in which we are checking the given
2762 /// template parameter list.
2763 ///
2764 /// \param SkipBody If we might have already made a prior merged definition
2765 /// of this template visible, the corresponding body-skipping information.
2766 /// Default argument redefinition is not an error when skipping such a body,
2767 /// because (under the ODR) we can assume the default arguments are the same
2768 /// as the prior merged definition.
2769 ///
2770 /// \returns true if an error occurred, false otherwise.
CheckTemplateParameterList(TemplateParameterList * NewParams,TemplateParameterList * OldParams,TemplateParamListContext TPC,SkipBodyInfo * SkipBody)2771 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2772                                       TemplateParameterList *OldParams,
2773                                       TemplateParamListContext TPC,
2774                                       SkipBodyInfo *SkipBody) {
2775   bool Invalid = false;
2776 
2777   // C++ [temp.param]p10:
2778   //   The set of default template-arguments available for use with a
2779   //   template declaration or definition is obtained by merging the
2780   //   default arguments from the definition (if in scope) and all
2781   //   declarations in scope in the same way default function
2782   //   arguments are (8.3.6).
2783   bool SawDefaultArgument = false;
2784   SourceLocation PreviousDefaultArgLoc;
2785 
2786   // Dummy initialization to avoid warnings.
2787   TemplateParameterList::iterator OldParam = NewParams->end();
2788   if (OldParams)
2789     OldParam = OldParams->begin();
2790 
2791   bool RemoveDefaultArguments = false;
2792   for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2793                                     NewParamEnd = NewParams->end();
2794        NewParam != NewParamEnd; ++NewParam) {
2795     // Whether we've seen a duplicate default argument in the same translation
2796     // unit.
2797     bool RedundantDefaultArg = false;
2798     // Whether we've found inconsis inconsitent default arguments in different
2799     // translation unit.
2800     bool InconsistentDefaultArg = false;
2801     // The name of the module which contains the inconsistent default argument.
2802     std::string PrevModuleName;
2803 
2804     SourceLocation OldDefaultLoc;
2805     SourceLocation NewDefaultLoc;
2806 
2807     // Variable used to diagnose missing default arguments
2808     bool MissingDefaultArg = false;
2809 
2810     // Variable used to diagnose non-final parameter packs
2811     bool SawParameterPack = false;
2812 
2813     if (TemplateTypeParmDecl *NewTypeParm
2814           = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2815       // Check the presence of a default argument here.
2816       if (NewTypeParm->hasDefaultArgument() &&
2817           DiagnoseDefaultTemplateArgument(*this, TPC,
2818                                           NewTypeParm->getLocation(),
2819                NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2820                                                        .getSourceRange()))
2821         NewTypeParm->removeDefaultArgument();
2822 
2823       // Merge default arguments for template type parameters.
2824       TemplateTypeParmDecl *OldTypeParm
2825           = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2826       if (NewTypeParm->isParameterPack()) {
2827         assert(!NewTypeParm->hasDefaultArgument() &&
2828                "Parameter packs can't have a default argument!");
2829         SawParameterPack = true;
2830       } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2831                  NewTypeParm->hasDefaultArgument() &&
2832                  (!SkipBody || !SkipBody->ShouldSkip)) {
2833         OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2834         NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2835         SawDefaultArgument = true;
2836 
2837         if (!OldTypeParm->getOwningModule() ||
2838             isModuleUnitOfCurrentTU(OldTypeParm->getOwningModule()))
2839           RedundantDefaultArg = true;
2840         else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2841                                                                 NewTypeParm)) {
2842           InconsistentDefaultArg = true;
2843           PrevModuleName =
2844               OldTypeParm->getImportedOwningModule()->getFullModuleName();
2845         }
2846         PreviousDefaultArgLoc = NewDefaultLoc;
2847       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2848         // Merge the default argument from the old declaration to the
2849         // new declaration.
2850         NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2851         PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2852       } else if (NewTypeParm->hasDefaultArgument()) {
2853         SawDefaultArgument = true;
2854         PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2855       } else if (SawDefaultArgument)
2856         MissingDefaultArg = true;
2857     } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2858                = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2859       // Check for unexpanded parameter packs.
2860       if (!NewNonTypeParm->isParameterPack() &&
2861           DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2862                                           NewNonTypeParm->getTypeSourceInfo(),
2863                                           UPPC_NonTypeTemplateParameterType)) {
2864         Invalid = true;
2865         continue;
2866       }
2867 
2868       // Check the presence of a default argument here.
2869       if (NewNonTypeParm->hasDefaultArgument() &&
2870           DiagnoseDefaultTemplateArgument(*this, TPC,
2871                                           NewNonTypeParm->getLocation(),
2872                     NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2873         NewNonTypeParm->removeDefaultArgument();
2874       }
2875 
2876       // Merge default arguments for non-type template parameters
2877       NonTypeTemplateParmDecl *OldNonTypeParm
2878         = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2879       if (NewNonTypeParm->isParameterPack()) {
2880         assert(!NewNonTypeParm->hasDefaultArgument() &&
2881                "Parameter packs can't have a default argument!");
2882         if (!NewNonTypeParm->isPackExpansion())
2883           SawParameterPack = true;
2884       } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2885                  NewNonTypeParm->hasDefaultArgument() &&
2886                  (!SkipBody || !SkipBody->ShouldSkip)) {
2887         OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2888         NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2889         SawDefaultArgument = true;
2890         if (!OldNonTypeParm->getOwningModule() ||
2891             isModuleUnitOfCurrentTU(OldNonTypeParm->getOwningModule()))
2892           RedundantDefaultArg = true;
2893         else if (!getASTContext().isSameDefaultTemplateArgument(
2894                      OldNonTypeParm, NewNonTypeParm)) {
2895           InconsistentDefaultArg = true;
2896           PrevModuleName =
2897               OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2898         }
2899         PreviousDefaultArgLoc = NewDefaultLoc;
2900       } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2901         // Merge the default argument from the old declaration to the
2902         // new declaration.
2903         NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2904         PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2905       } else if (NewNonTypeParm->hasDefaultArgument()) {
2906         SawDefaultArgument = true;
2907         PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2908       } else if (SawDefaultArgument)
2909         MissingDefaultArg = true;
2910     } else {
2911       TemplateTemplateParmDecl *NewTemplateParm
2912         = cast<TemplateTemplateParmDecl>(*NewParam);
2913 
2914       // Check for unexpanded parameter packs, recursively.
2915       if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2916         Invalid = true;
2917         continue;
2918       }
2919 
2920       // Check the presence of a default argument here.
2921       if (NewTemplateParm->hasDefaultArgument() &&
2922           DiagnoseDefaultTemplateArgument(*this, TPC,
2923                                           NewTemplateParm->getLocation(),
2924                      NewTemplateParm->getDefaultArgument().getSourceRange()))
2925         NewTemplateParm->removeDefaultArgument();
2926 
2927       // Merge default arguments for template template parameters
2928       TemplateTemplateParmDecl *OldTemplateParm
2929         = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2930       if (NewTemplateParm->isParameterPack()) {
2931         assert(!NewTemplateParm->hasDefaultArgument() &&
2932                "Parameter packs can't have a default argument!");
2933         if (!NewTemplateParm->isPackExpansion())
2934           SawParameterPack = true;
2935       } else if (OldTemplateParm &&
2936                  hasVisibleDefaultArgument(OldTemplateParm) &&
2937                  NewTemplateParm->hasDefaultArgument() &&
2938                  (!SkipBody || !SkipBody->ShouldSkip)) {
2939         OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2940         NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2941         SawDefaultArgument = true;
2942         if (!OldTemplateParm->getOwningModule() ||
2943             isModuleUnitOfCurrentTU(OldTemplateParm->getOwningModule()))
2944           RedundantDefaultArg = true;
2945         else if (!getASTContext().isSameDefaultTemplateArgument(
2946                      OldTemplateParm, NewTemplateParm)) {
2947           InconsistentDefaultArg = true;
2948           PrevModuleName =
2949               OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2950         }
2951         PreviousDefaultArgLoc = NewDefaultLoc;
2952       } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2953         // Merge the default argument from the old declaration to the
2954         // new declaration.
2955         NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2956         PreviousDefaultArgLoc
2957           = OldTemplateParm->getDefaultArgument().getLocation();
2958       } else if (NewTemplateParm->hasDefaultArgument()) {
2959         SawDefaultArgument = true;
2960         PreviousDefaultArgLoc
2961           = NewTemplateParm->getDefaultArgument().getLocation();
2962       } else if (SawDefaultArgument)
2963         MissingDefaultArg = true;
2964     }
2965 
2966     // C++11 [temp.param]p11:
2967     //   If a template parameter of a primary class template or alias template
2968     //   is a template parameter pack, it shall be the last template parameter.
2969     if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2970         (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2971          TPC == TPC_TypeAliasTemplate)) {
2972       Diag((*NewParam)->getLocation(),
2973            diag::err_template_param_pack_must_be_last_template_parameter);
2974       Invalid = true;
2975     }
2976 
2977     // [basic.def.odr]/13:
2978     //     There can be more than one definition of a
2979     //     ...
2980     //     default template argument
2981     //     ...
2982     //     in a program provided that each definition appears in a different
2983     //     translation unit and the definitions satisfy the [same-meaning
2984     //     criteria of the ODR].
2985     //
2986     // Simply, the design of modules allows the definition of template default
2987     // argument to be repeated across translation unit. Note that the ODR is
2988     // checked elsewhere. But it is still not allowed to repeat template default
2989     // argument in the same translation unit.
2990     if (RedundantDefaultArg) {
2991       Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2992       Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2993       Invalid = true;
2994     } else if (InconsistentDefaultArg) {
2995       // We could only diagnose about the case that the OldParam is imported.
2996       // The case NewParam is imported should be handled in ASTReader.
2997       Diag(NewDefaultLoc,
2998            diag::err_template_param_default_arg_inconsistent_redefinition);
2999       Diag(OldDefaultLoc,
3000            diag::note_template_param_prev_default_arg_in_other_module)
3001           << PrevModuleName;
3002       Invalid = true;
3003     } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
3004       // C++ [temp.param]p11:
3005       //   If a template-parameter of a class template has a default
3006       //   template-argument, each subsequent template-parameter shall either
3007       //   have a default template-argument supplied or be a template parameter
3008       //   pack.
3009       Diag((*NewParam)->getLocation(),
3010            diag::err_template_param_default_arg_missing);
3011       Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
3012       Invalid = true;
3013       RemoveDefaultArguments = true;
3014     }
3015 
3016     // If we have an old template parameter list that we're merging
3017     // in, move on to the next parameter.
3018     if (OldParams)
3019       ++OldParam;
3020   }
3021 
3022   // We were missing some default arguments at the end of the list, so remove
3023   // all of the default arguments.
3024   if (RemoveDefaultArguments) {
3025     for (TemplateParameterList::iterator NewParam = NewParams->begin(),
3026                                       NewParamEnd = NewParams->end();
3027          NewParam != NewParamEnd; ++NewParam) {
3028       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
3029         TTP->removeDefaultArgument();
3030       else if (NonTypeTemplateParmDecl *NTTP
3031                                 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
3032         NTTP->removeDefaultArgument();
3033       else
3034         cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
3035     }
3036   }
3037 
3038   return Invalid;
3039 }
3040 
3041 namespace {
3042 
3043 /// A class which looks for a use of a certain level of template
3044 /// parameter.
3045 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
3046   typedef RecursiveASTVisitor<DependencyChecker> super;
3047 
3048   unsigned Depth;
3049 
3050   // Whether we're looking for a use of a template parameter that makes the
3051   // overall construct type-dependent / a dependent type. This is strictly
3052   // best-effort for now; we may fail to match at all for a dependent type
3053   // in some cases if this is set.
3054   bool IgnoreNonTypeDependent;
3055 
3056   bool Match;
3057   SourceLocation MatchLoc;
3058 
DependencyChecker__anon8a5f675e0a11::DependencyChecker3059   DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
3060       : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
3061         Match(false) {}
3062 
DependencyChecker__anon8a5f675e0a11::DependencyChecker3063   DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
3064       : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
3065     NamedDecl *ND = Params->getParam(0);
3066     if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
3067       Depth = PD->getDepth();
3068     } else if (NonTypeTemplateParmDecl *PD =
3069                  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
3070       Depth = PD->getDepth();
3071     } else {
3072       Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
3073     }
3074   }
3075 
Matches__anon8a5f675e0a11::DependencyChecker3076   bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
3077     if (ParmDepth >= Depth) {
3078       Match = true;
3079       MatchLoc = Loc;
3080       return true;
3081     }
3082     return false;
3083   }
3084 
TraverseStmt__anon8a5f675e0a11::DependencyChecker3085   bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
3086     // Prune out non-type-dependent expressions if requested. This can
3087     // sometimes result in us failing to find a template parameter reference
3088     // (if a value-dependent expression creates a dependent type), but this
3089     // mode is best-effort only.
3090     if (auto *E = dyn_cast_or_null<Expr>(S))
3091       if (IgnoreNonTypeDependent && !E->isTypeDependent())
3092         return true;
3093     return super::TraverseStmt(S, Q);
3094   }
3095 
TraverseTypeLoc__anon8a5f675e0a11::DependencyChecker3096   bool TraverseTypeLoc(TypeLoc TL) {
3097     if (IgnoreNonTypeDependent && !TL.isNull() &&
3098         !TL.getType()->isDependentType())
3099       return true;
3100     return super::TraverseTypeLoc(TL);
3101   }
3102 
VisitTemplateTypeParmTypeLoc__anon8a5f675e0a11::DependencyChecker3103   bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3104     return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
3105   }
3106 
VisitTemplateTypeParmType__anon8a5f675e0a11::DependencyChecker3107   bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
3108     // For a best-effort search, keep looking until we find a location.
3109     return IgnoreNonTypeDependent || !Matches(T->getDepth());
3110   }
3111 
TraverseTemplateName__anon8a5f675e0a11::DependencyChecker3112   bool TraverseTemplateName(TemplateName N) {
3113     if (TemplateTemplateParmDecl *PD =
3114           dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
3115       if (Matches(PD->getDepth()))
3116         return false;
3117     return super::TraverseTemplateName(N);
3118   }
3119 
VisitDeclRefExpr__anon8a5f675e0a11::DependencyChecker3120   bool VisitDeclRefExpr(DeclRefExpr *E) {
3121     if (NonTypeTemplateParmDecl *PD =
3122           dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
3123       if (Matches(PD->getDepth(), E->getExprLoc()))
3124         return false;
3125     return super::VisitDeclRefExpr(E);
3126   }
3127 
VisitSubstTemplateTypeParmType__anon8a5f675e0a11::DependencyChecker3128   bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
3129     return TraverseType(T->getReplacementType());
3130   }
3131 
3132   bool
VisitSubstTemplateTypeParmPackType__anon8a5f675e0a11::DependencyChecker3133   VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
3134     return TraverseTemplateArgument(T->getArgumentPack());
3135   }
3136 
TraverseInjectedClassNameType__anon8a5f675e0a11::DependencyChecker3137   bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
3138     return TraverseType(T->getInjectedSpecializationType());
3139   }
3140 };
3141 } // end anonymous namespace
3142 
3143 /// Determines whether a given type depends on the given parameter
3144 /// list.
3145 static bool
DependsOnTemplateParameters(QualType T,TemplateParameterList * Params)3146 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
3147   if (!Params->size())
3148     return false;
3149 
3150   DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
3151   Checker.TraverseType(T);
3152   return Checker.Match;
3153 }
3154 
3155 // Find the source range corresponding to the named type in the given
3156 // nested-name-specifier, if any.
getRangeOfTypeInNestedNameSpecifier(ASTContext & Context,QualType T,const CXXScopeSpec & SS)3157 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
3158                                                        QualType T,
3159                                                        const CXXScopeSpec &SS) {
3160   NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
3161   while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
3162     if (const Type *CurType = NNS->getAsType()) {
3163       if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
3164         return NNSLoc.getTypeLoc().getSourceRange();
3165     } else
3166       break;
3167 
3168     NNSLoc = NNSLoc.getPrefix();
3169   }
3170 
3171   return SourceRange();
3172 }
3173 
3174 /// Match the given template parameter lists to the given scope
3175 /// specifier, returning the template parameter list that applies to the
3176 /// name.
3177 ///
3178 /// \param DeclStartLoc the start of the declaration that has a scope
3179 /// specifier or a template parameter list.
3180 ///
3181 /// \param DeclLoc The location of the declaration itself.
3182 ///
3183 /// \param SS the scope specifier that will be matched to the given template
3184 /// parameter lists. This scope specifier precedes a qualified name that is
3185 /// being declared.
3186 ///
3187 /// \param TemplateId The template-id following the scope specifier, if there
3188 /// is one. Used to check for a missing 'template<>'.
3189 ///
3190 /// \param ParamLists the template parameter lists, from the outermost to the
3191 /// innermost template parameter lists.
3192 ///
3193 /// \param IsFriend Whether to apply the slightly different rules for
3194 /// matching template parameters to scope specifiers in friend
3195 /// declarations.
3196 ///
3197 /// \param IsMemberSpecialization will be set true if the scope specifier
3198 /// denotes a fully-specialized type, and therefore this is a declaration of
3199 /// a member specialization.
3200 ///
3201 /// \returns the template parameter list, if any, that corresponds to the
3202 /// name that is preceded by the scope specifier @p SS. This template
3203 /// parameter list may have template parameters (if we're declaring a
3204 /// template) or may have no template parameters (if we're declaring a
3205 /// template specialization), or may be NULL (if what we're declaring isn't
3206 /// itself a template).
MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,SourceLocation DeclLoc,const CXXScopeSpec & SS,TemplateIdAnnotation * TemplateId,ArrayRef<TemplateParameterList * > ParamLists,bool IsFriend,bool & IsMemberSpecialization,bool & Invalid,bool SuppressDiagnostic)3207 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
3208     SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
3209     TemplateIdAnnotation *TemplateId,
3210     ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
3211     bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
3212   IsMemberSpecialization = false;
3213   Invalid = false;
3214 
3215   // The sequence of nested types to which we will match up the template
3216   // parameter lists. We first build this list by starting with the type named
3217   // by the nested-name-specifier and walking out until we run out of types.
3218   SmallVector<QualType, 4> NestedTypes;
3219   QualType T;
3220   if (SS.getScopeRep()) {
3221     if (CXXRecordDecl *Record
3222               = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
3223       T = Context.getTypeDeclType(Record);
3224     else
3225       T = QualType(SS.getScopeRep()->getAsType(), 0);
3226   }
3227 
3228   // If we found an explicit specialization that prevents us from needing
3229   // 'template<>' headers, this will be set to the location of that
3230   // explicit specialization.
3231   SourceLocation ExplicitSpecLoc;
3232 
3233   while (!T.isNull()) {
3234     NestedTypes.push_back(T);
3235 
3236     // Retrieve the parent of a record type.
3237     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3238       // If this type is an explicit specialization, we're done.
3239       if (ClassTemplateSpecializationDecl *Spec
3240           = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3241         if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
3242             Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
3243           ExplicitSpecLoc = Spec->getLocation();
3244           break;
3245         }
3246       } else if (Record->getTemplateSpecializationKind()
3247                                                 == TSK_ExplicitSpecialization) {
3248         ExplicitSpecLoc = Record->getLocation();
3249         break;
3250       }
3251 
3252       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
3253         T = Context.getTypeDeclType(Parent);
3254       else
3255         T = QualType();
3256       continue;
3257     }
3258 
3259     if (const TemplateSpecializationType *TST
3260                                      = T->getAs<TemplateSpecializationType>()) {
3261       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3262         if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
3263           T = Context.getTypeDeclType(Parent);
3264         else
3265           T = QualType();
3266         continue;
3267       }
3268     }
3269 
3270     // Look one step prior in a dependent template specialization type.
3271     if (const DependentTemplateSpecializationType *DependentTST
3272                           = T->getAs<DependentTemplateSpecializationType>()) {
3273       if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
3274         T = QualType(NNS->getAsType(), 0);
3275       else
3276         T = QualType();
3277       continue;
3278     }
3279 
3280     // Look one step prior in a dependent name type.
3281     if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
3282       if (NestedNameSpecifier *NNS = DependentName->getQualifier())
3283         T = QualType(NNS->getAsType(), 0);
3284       else
3285         T = QualType();
3286       continue;
3287     }
3288 
3289     // Retrieve the parent of an enumeration type.
3290     if (const EnumType *EnumT = T->getAs<EnumType>()) {
3291       // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
3292       // check here.
3293       EnumDecl *Enum = EnumT->getDecl();
3294 
3295       // Get to the parent type.
3296       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
3297         T = Context.getTypeDeclType(Parent);
3298       else
3299         T = QualType();
3300       continue;
3301     }
3302 
3303     T = QualType();
3304   }
3305   // Reverse the nested types list, since we want to traverse from the outermost
3306   // to the innermost while checking template-parameter-lists.
3307   std::reverse(NestedTypes.begin(), NestedTypes.end());
3308 
3309   // C++0x [temp.expl.spec]p17:
3310   //   A member or a member template may be nested within many
3311   //   enclosing class templates. In an explicit specialization for
3312   //   such a member, the member declaration shall be preceded by a
3313   //   template<> for each enclosing class template that is
3314   //   explicitly specialized.
3315   bool SawNonEmptyTemplateParameterList = false;
3316 
3317   auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
3318     if (SawNonEmptyTemplateParameterList) {
3319       if (!SuppressDiagnostic)
3320         Diag(DeclLoc, diag::err_specialize_member_of_template)
3321           << !Recovery << Range;
3322       Invalid = true;
3323       IsMemberSpecialization = false;
3324       return true;
3325     }
3326 
3327     return false;
3328   };
3329 
3330   auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
3331     // Check that we can have an explicit specialization here.
3332     if (CheckExplicitSpecialization(Range, true))
3333       return true;
3334 
3335     // We don't have a template header, but we should.
3336     SourceLocation ExpectedTemplateLoc;
3337     if (!ParamLists.empty())
3338       ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
3339     else
3340       ExpectedTemplateLoc = DeclStartLoc;
3341 
3342     if (!SuppressDiagnostic)
3343       Diag(DeclLoc, diag::err_template_spec_needs_header)
3344         << Range
3345         << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
3346     return false;
3347   };
3348 
3349   unsigned ParamIdx = 0;
3350   for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3351        ++TypeIdx) {
3352     T = NestedTypes[TypeIdx];
3353 
3354     // Whether we expect a 'template<>' header.
3355     bool NeedEmptyTemplateHeader = false;
3356 
3357     // Whether we expect a template header with parameters.
3358     bool NeedNonemptyTemplateHeader = false;
3359 
3360     // For a dependent type, the set of template parameters that we
3361     // expect to see.
3362     TemplateParameterList *ExpectedTemplateParams = nullptr;
3363 
3364     // C++0x [temp.expl.spec]p15:
3365     //   A member or a member template may be nested within many enclosing
3366     //   class templates. In an explicit specialization for such a member, the
3367     //   member declaration shall be preceded by a template<> for each
3368     //   enclosing class template that is explicitly specialized.
3369     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3370       if (ClassTemplatePartialSpecializationDecl *Partial
3371             = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3372         ExpectedTemplateParams = Partial->getTemplateParameters();
3373         NeedNonemptyTemplateHeader = true;
3374       } else if (Record->isDependentType()) {
3375         if (Record->getDescribedClassTemplate()) {
3376           ExpectedTemplateParams = Record->getDescribedClassTemplate()
3377                                                       ->getTemplateParameters();
3378           NeedNonemptyTemplateHeader = true;
3379         }
3380       } else if (ClassTemplateSpecializationDecl *Spec
3381                      = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3382         // C++0x [temp.expl.spec]p4:
3383         //   Members of an explicitly specialized class template are defined
3384         //   in the same manner as members of normal classes, and not using
3385         //   the template<> syntax.
3386         if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3387           NeedEmptyTemplateHeader = true;
3388         else
3389           continue;
3390       } else if (Record->getTemplateSpecializationKind()) {
3391         if (Record->getTemplateSpecializationKind()
3392                                                 != TSK_ExplicitSpecialization &&
3393             TypeIdx == NumTypes - 1)
3394           IsMemberSpecialization = true;
3395 
3396         continue;
3397       }
3398     } else if (const TemplateSpecializationType *TST
3399                                      = T->getAs<TemplateSpecializationType>()) {
3400       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3401         ExpectedTemplateParams = Template->getTemplateParameters();
3402         NeedNonemptyTemplateHeader = true;
3403       }
3404     } else if (T->getAs<DependentTemplateSpecializationType>()) {
3405       // FIXME:  We actually could/should check the template arguments here
3406       // against the corresponding template parameter list.
3407       NeedNonemptyTemplateHeader = false;
3408     }
3409 
3410     // C++ [temp.expl.spec]p16:
3411     //   In an explicit specialization declaration for a member of a class
3412     //   template or a member template that ap- pears in namespace scope, the
3413     //   member template and some of its enclosing class templates may remain
3414     //   unspecialized, except that the declaration shall not explicitly
3415     //   specialize a class member template if its en- closing class templates
3416     //   are not explicitly specialized as well.
3417     if (ParamIdx < ParamLists.size()) {
3418       if (ParamLists[ParamIdx]->size() == 0) {
3419         if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3420                                         false))
3421           return nullptr;
3422       } else
3423         SawNonEmptyTemplateParameterList = true;
3424     }
3425 
3426     if (NeedEmptyTemplateHeader) {
3427       // If we're on the last of the types, and we need a 'template<>' header
3428       // here, then it's a member specialization.
3429       if (TypeIdx == NumTypes - 1)
3430         IsMemberSpecialization = true;
3431 
3432       if (ParamIdx < ParamLists.size()) {
3433         if (ParamLists[ParamIdx]->size() > 0) {
3434           // The header has template parameters when it shouldn't. Complain.
3435           if (!SuppressDiagnostic)
3436             Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3437                  diag::err_template_param_list_matches_nontemplate)
3438               << T
3439               << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3440                              ParamLists[ParamIdx]->getRAngleLoc())
3441               << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3442           Invalid = true;
3443           return nullptr;
3444         }
3445 
3446         // Consume this template header.
3447         ++ParamIdx;
3448         continue;
3449       }
3450 
3451       if (!IsFriend)
3452         if (DiagnoseMissingExplicitSpecialization(
3453                 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3454           return nullptr;
3455 
3456       continue;
3457     }
3458 
3459     if (NeedNonemptyTemplateHeader) {
3460       // In friend declarations we can have template-ids which don't
3461       // depend on the corresponding template parameter lists.  But
3462       // assume that empty parameter lists are supposed to match this
3463       // template-id.
3464       if (IsFriend && T->isDependentType()) {
3465         if (ParamIdx < ParamLists.size() &&
3466             DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3467           ExpectedTemplateParams = nullptr;
3468         else
3469           continue;
3470       }
3471 
3472       if (ParamIdx < ParamLists.size()) {
3473         // Check the template parameter list, if we can.
3474         if (ExpectedTemplateParams &&
3475             !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
3476                                             ExpectedTemplateParams,
3477                                             !SuppressDiagnostic, TPL_TemplateMatch))
3478           Invalid = true;
3479 
3480         if (!Invalid &&
3481             CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3482                                        TPC_ClassTemplateMember))
3483           Invalid = true;
3484 
3485         ++ParamIdx;
3486         continue;
3487       }
3488 
3489       if (!SuppressDiagnostic)
3490         Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3491           << T
3492           << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3493       Invalid = true;
3494       continue;
3495     }
3496   }
3497 
3498   // If there were at least as many template-ids as there were template
3499   // parameter lists, then there are no template parameter lists remaining for
3500   // the declaration itself.
3501   if (ParamIdx >= ParamLists.size()) {
3502     if (TemplateId && !IsFriend) {
3503       // We don't have a template header for the declaration itself, but we
3504       // should.
3505       DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3506                                                         TemplateId->RAngleLoc));
3507 
3508       // Fabricate an empty template parameter list for the invented header.
3509       return TemplateParameterList::Create(Context, SourceLocation(),
3510                                            SourceLocation(), std::nullopt,
3511                                            SourceLocation(), nullptr);
3512     }
3513 
3514     return nullptr;
3515   }
3516 
3517   // If there were too many template parameter lists, complain about that now.
3518   if (ParamIdx < ParamLists.size() - 1) {
3519     bool HasAnyExplicitSpecHeader = false;
3520     bool AllExplicitSpecHeaders = true;
3521     for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3522       if (ParamLists[I]->size() == 0)
3523         HasAnyExplicitSpecHeader = true;
3524       else
3525         AllExplicitSpecHeaders = false;
3526     }
3527 
3528     if (!SuppressDiagnostic)
3529       Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3530            AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
3531                                   : diag::err_template_spec_extra_headers)
3532           << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3533                          ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3534 
3535     // If there was a specialization somewhere, such that 'template<>' is
3536     // not required, and there were any 'template<>' headers, note where the
3537     // specialization occurred.
3538     if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3539         !SuppressDiagnostic)
3540       Diag(ExplicitSpecLoc,
3541            diag::note_explicit_template_spec_does_not_need_header)
3542         << NestedTypes.back();
3543 
3544     // We have a template parameter list with no corresponding scope, which
3545     // means that the resulting template declaration can't be instantiated
3546     // properly (we'll end up with dependent nodes when we shouldn't).
3547     if (!AllExplicitSpecHeaders)
3548       Invalid = true;
3549   }
3550 
3551   // C++ [temp.expl.spec]p16:
3552   //   In an explicit specialization declaration for a member of a class
3553   //   template or a member template that ap- pears in namespace scope, the
3554   //   member template and some of its enclosing class templates may remain
3555   //   unspecialized, except that the declaration shall not explicitly
3556   //   specialize a class member template if its en- closing class templates
3557   //   are not explicitly specialized as well.
3558   if (ParamLists.back()->size() == 0 &&
3559       CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3560                                   false))
3561     return nullptr;
3562 
3563   // Return the last template parameter list, which corresponds to the
3564   // entity being declared.
3565   return ParamLists.back();
3566 }
3567 
NoteAllFoundTemplates(TemplateName Name)3568 void Sema::NoteAllFoundTemplates(TemplateName Name) {
3569   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3570     Diag(Template->getLocation(), diag::note_template_declared_here)
3571         << (isa<FunctionTemplateDecl>(Template)
3572                 ? 0
3573                 : isa<ClassTemplateDecl>(Template)
3574                       ? 1
3575                       : isa<VarTemplateDecl>(Template)
3576                             ? 2
3577                             : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3578         << Template->getDeclName();
3579     return;
3580   }
3581 
3582   if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3583     for (OverloadedTemplateStorage::iterator I = OST->begin(),
3584                                           IEnd = OST->end();
3585          I != IEnd; ++I)
3586       Diag((*I)->getLocation(), diag::note_template_declared_here)
3587         << 0 << (*I)->getDeclName();
3588 
3589     return;
3590   }
3591 }
3592 
3593 static QualType
checkBuiltinTemplateIdType(Sema & SemaRef,BuiltinTemplateDecl * BTD,ArrayRef<TemplateArgument> Converted,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs)3594 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3595                            ArrayRef<TemplateArgument> Converted,
3596                            SourceLocation TemplateLoc,
3597                            TemplateArgumentListInfo &TemplateArgs) {
3598   ASTContext &Context = SemaRef.getASTContext();
3599 
3600   switch (BTD->getBuiltinTemplateKind()) {
3601   case BTK__make_integer_seq: {
3602     // Specializations of __make_integer_seq<S, T, N> are treated like
3603     // S<T, 0, ..., N-1>.
3604 
3605     QualType OrigType = Converted[1].getAsType();
3606     // C++14 [inteseq.intseq]p1:
3607     //   T shall be an integer type.
3608     if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3609       SemaRef.Diag(TemplateArgs[1].getLocation(),
3610                    diag::err_integer_sequence_integral_element_type);
3611       return QualType();
3612     }
3613 
3614     TemplateArgument NumArgsArg = Converted[2];
3615     if (NumArgsArg.isDependent())
3616       return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3617                                                             Converted);
3618 
3619     TemplateArgumentListInfo SyntheticTemplateArgs;
3620     // The type argument, wrapped in substitution sugar, gets reused as the
3621     // first template argument in the synthetic template argument list.
3622     SyntheticTemplateArgs.addArgument(
3623         TemplateArgumentLoc(TemplateArgument(OrigType),
3624                             SemaRef.Context.getTrivialTypeSourceInfo(
3625                                 OrigType, TemplateArgs[1].getLocation())));
3626 
3627     if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3628       // Expand N into 0 ... N-1.
3629       for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3630            I < NumArgs; ++I) {
3631         TemplateArgument TA(Context, I, OrigType);
3632         SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3633             TA, OrigType, TemplateArgs[2].getLocation()));
3634       }
3635     } else {
3636       // C++14 [inteseq.make]p1:
3637       //   If N is negative the program is ill-formed.
3638       SemaRef.Diag(TemplateArgs[2].getLocation(),
3639                    diag::err_integer_sequence_negative_length);
3640       return QualType();
3641     }
3642 
3643     // The first template argument will be reused as the template decl that
3644     // our synthetic template arguments will be applied to.
3645     return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3646                                        TemplateLoc, SyntheticTemplateArgs);
3647   }
3648 
3649   case BTK__type_pack_element:
3650     // Specializations of
3651     //    __type_pack_element<Index, T_1, ..., T_N>
3652     // are treated like T_Index.
3653     assert(Converted.size() == 2 &&
3654       "__type_pack_element should be given an index and a parameter pack");
3655 
3656     TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3657     if (IndexArg.isDependent() || Ts.isDependent())
3658       return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3659                                                             Converted);
3660 
3661     llvm::APSInt Index = IndexArg.getAsIntegral();
3662     assert(Index >= 0 && "the index used with __type_pack_element should be of "
3663                          "type std::size_t, and hence be non-negative");
3664     // If the Index is out of bounds, the program is ill-formed.
3665     if (Index >= Ts.pack_size()) {
3666       SemaRef.Diag(TemplateArgs[0].getLocation(),
3667                    diag::err_type_pack_element_out_of_bounds);
3668       return QualType();
3669     }
3670 
3671     // We simply return the type at index `Index`.
3672     int64_t N = Index.getExtValue();
3673     return Ts.getPackAsArray()[N].getAsType();
3674   }
3675   llvm_unreachable("unexpected BuiltinTemplateDecl!");
3676 }
3677 
3678 /// Determine whether this alias template is "enable_if_t".
3679 /// libc++ >=14 uses "__enable_if_t" in C++11 mode.
isEnableIfAliasTemplate(TypeAliasTemplateDecl * AliasTemplate)3680 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3681   return AliasTemplate->getName().equals("enable_if_t") ||
3682          AliasTemplate->getName().equals("__enable_if_t");
3683 }
3684 
3685 /// Collect all of the separable terms in the given condition, which
3686 /// might be a conjunction.
3687 ///
3688 /// FIXME: The right answer is to convert the logical expression into
3689 /// disjunctive normal form, so we can find the first failed term
3690 /// within each possible clause.
collectConjunctionTerms(Expr * Clause,SmallVectorImpl<Expr * > & Terms)3691 static void collectConjunctionTerms(Expr *Clause,
3692                                     SmallVectorImpl<Expr *> &Terms) {
3693   if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3694     if (BinOp->getOpcode() == BO_LAnd) {
3695       collectConjunctionTerms(BinOp->getLHS(), Terms);
3696       collectConjunctionTerms(BinOp->getRHS(), Terms);
3697       return;
3698     }
3699   }
3700 
3701   Terms.push_back(Clause);
3702 }
3703 
3704 // The ranges-v3 library uses an odd pattern of a top-level "||" with
3705 // a left-hand side that is value-dependent but never true. Identify
3706 // the idiom and ignore that term.
lookThroughRangesV3Condition(Preprocessor & PP,Expr * Cond)3707 static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3708   // Top-level '||'.
3709   auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3710   if (!BinOp) return Cond;
3711 
3712   if (BinOp->getOpcode() != BO_LOr) return Cond;
3713 
3714   // With an inner '==' that has a literal on the right-hand side.
3715   Expr *LHS = BinOp->getLHS();
3716   auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3717   if (!InnerBinOp) return Cond;
3718 
3719   if (InnerBinOp->getOpcode() != BO_EQ ||
3720       !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3721     return Cond;
3722 
3723   // If the inner binary operation came from a macro expansion named
3724   // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3725   // of the '||', which is the real, user-provided condition.
3726   SourceLocation Loc = InnerBinOp->getExprLoc();
3727   if (!Loc.isMacroID()) return Cond;
3728 
3729   StringRef MacroName = PP.getImmediateMacroName(Loc);
3730   if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3731     return BinOp->getRHS();
3732 
3733   return Cond;
3734 }
3735 
3736 namespace {
3737 
3738 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3739 // within failing boolean expression, such as substituting template parameters
3740 // for actual types.
3741 class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3742 public:
FailedBooleanConditionPrinterHelper(const PrintingPolicy & P)3743   explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3744       : Policy(P) {}
3745 
handledStmt(Stmt * E,raw_ostream & OS)3746   bool handledStmt(Stmt *E, raw_ostream &OS) override {
3747     const auto *DR = dyn_cast<DeclRefExpr>(E);
3748     if (DR && DR->getQualifier()) {
3749       // If this is a qualified name, expand the template arguments in nested
3750       // qualifiers.
3751       DR->getQualifier()->print(OS, Policy, true);
3752       // Then print the decl itself.
3753       const ValueDecl *VD = DR->getDecl();
3754       OS << VD->getName();
3755       if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3756         // This is a template variable, print the expanded template arguments.
3757         printTemplateArgumentList(
3758             OS, IV->getTemplateArgs().asArray(), Policy,
3759             IV->getSpecializedTemplate()->getTemplateParameters());
3760       }
3761       return true;
3762     }
3763     return false;
3764   }
3765 
3766 private:
3767   const PrintingPolicy Policy;
3768 };
3769 
3770 } // end anonymous namespace
3771 
3772 std::pair<Expr *, std::string>
findFailedBooleanCondition(Expr * Cond)3773 Sema::findFailedBooleanCondition(Expr *Cond) {
3774   Cond = lookThroughRangesV3Condition(PP, Cond);
3775 
3776   // Separate out all of the terms in a conjunction.
3777   SmallVector<Expr *, 4> Terms;
3778   collectConjunctionTerms(Cond, Terms);
3779 
3780   // Determine which term failed.
3781   Expr *FailedCond = nullptr;
3782   for (Expr *Term : Terms) {
3783     Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3784 
3785     // Literals are uninteresting.
3786     if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3787         isa<IntegerLiteral>(TermAsWritten))
3788       continue;
3789 
3790     // The initialization of the parameter from the argument is
3791     // a constant-evaluated context.
3792     EnterExpressionEvaluationContext ConstantEvaluated(
3793       *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3794 
3795     bool Succeeded;
3796     if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3797         !Succeeded) {
3798       FailedCond = TermAsWritten;
3799       break;
3800     }
3801   }
3802   if (!FailedCond)
3803     FailedCond = Cond->IgnoreParenImpCasts();
3804 
3805   std::string Description;
3806   {
3807     llvm::raw_string_ostream Out(Description);
3808     PrintingPolicy Policy = getPrintingPolicy();
3809     Policy.PrintCanonicalTypes = true;
3810     FailedBooleanConditionPrinterHelper Helper(Policy);
3811     FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3812   }
3813   return { FailedCond, Description };
3814 }
3815 
CheckTemplateIdType(TemplateName Name,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs)3816 QualType Sema::CheckTemplateIdType(TemplateName Name,
3817                                    SourceLocation TemplateLoc,
3818                                    TemplateArgumentListInfo &TemplateArgs) {
3819   DependentTemplateName *DTN
3820     = Name.getUnderlying().getAsDependentTemplateName();
3821   if (DTN && DTN->isIdentifier())
3822     // When building a template-id where the template-name is dependent,
3823     // assume the template is a type template. Either our assumption is
3824     // correct, or the code is ill-formed and will be diagnosed when the
3825     // dependent name is substituted.
3826     return Context.getDependentTemplateSpecializationType(
3827         ETK_None, DTN->getQualifier(), DTN->getIdentifier(),
3828         TemplateArgs.arguments());
3829 
3830   if (Name.getAsAssumedTemplateName() &&
3831       resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
3832     return QualType();
3833 
3834   TemplateDecl *Template = Name.getAsTemplateDecl();
3835   if (!Template || isa<FunctionTemplateDecl>(Template) ||
3836       isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3837     // We might have a substituted template template parameter pack. If so,
3838     // build a template specialization type for it.
3839     if (Name.getAsSubstTemplateTemplateParmPack())
3840       return Context.getTemplateSpecializationType(Name,
3841                                                    TemplateArgs.arguments());
3842 
3843     Diag(TemplateLoc, diag::err_template_id_not_a_type)
3844       << Name;
3845     NoteAllFoundTemplates(Name);
3846     return QualType();
3847   }
3848 
3849   // Check that the template argument list is well-formed for this
3850   // template.
3851   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3852   if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false,
3853                                 SugaredConverted, CanonicalConverted,
3854                                 /*UpdateArgsWithConversions=*/true))
3855     return QualType();
3856 
3857   QualType CanonType;
3858 
3859   if (TypeAliasTemplateDecl *AliasTemplate =
3860           dyn_cast<TypeAliasTemplateDecl>(Template)) {
3861 
3862     // Find the canonical type for this type alias template specialization.
3863     TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3864     if (Pattern->isInvalidDecl())
3865       return QualType();
3866 
3867     // Only substitute for the innermost template argument list.
3868     MultiLevelTemplateArgumentList TemplateArgLists;
3869     TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted,
3870                                                /*Final=*/false);
3871     TemplateArgLists.addOuterRetainedLevels(
3872         AliasTemplate->getTemplateParameters()->getDepth());
3873 
3874     LocalInstantiationScope Scope(*this);
3875     InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3876     if (Inst.isInvalid())
3877       return QualType();
3878 
3879     CanonType = SubstType(Pattern->getUnderlyingType(),
3880                           TemplateArgLists, AliasTemplate->getLocation(),
3881                           AliasTemplate->getDeclName());
3882     if (CanonType.isNull()) {
3883       // If this was enable_if and we failed to find the nested type
3884       // within enable_if in a SFINAE context, dig out the specific
3885       // enable_if condition that failed and present that instead.
3886       if (isEnableIfAliasTemplate(AliasTemplate)) {
3887         if (auto DeductionInfo = isSFINAEContext()) {
3888           if (*DeductionInfo &&
3889               (*DeductionInfo)->hasSFINAEDiagnostic() &&
3890               (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3891                 diag::err_typename_nested_not_found_enable_if &&
3892               TemplateArgs[0].getArgument().getKind()
3893                 == TemplateArgument::Expression) {
3894             Expr *FailedCond;
3895             std::string FailedDescription;
3896             std::tie(FailedCond, FailedDescription) =
3897               findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3898 
3899             // Remove the old SFINAE diagnostic.
3900             PartialDiagnosticAt OldDiag =
3901               {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3902             (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3903 
3904             // Add a new SFINAE diagnostic specifying which condition
3905             // failed.
3906             (*DeductionInfo)->addSFINAEDiagnostic(
3907               OldDiag.first,
3908               PDiag(diag::err_typename_nested_not_found_requirement)
3909                 << FailedDescription
3910                 << FailedCond->getSourceRange());
3911           }
3912         }
3913       }
3914 
3915       return QualType();
3916     }
3917   } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3918     CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
3919                                            TemplateLoc, TemplateArgs);
3920   } else if (Name.isDependent() ||
3921              TemplateSpecializationType::anyDependentTemplateArguments(
3922                  TemplateArgs, CanonicalConverted)) {
3923     // This class template specialization is a dependent
3924     // type. Therefore, its canonical type is another class template
3925     // specialization type that contains all of the converted
3926     // arguments in canonical form. This ensures that, e.g., A<T> and
3927     // A<T, T> have identical types when A is declared as:
3928     //
3929     //   template<typename T, typename U = T> struct A;
3930     CanonType = Context.getCanonicalTemplateSpecializationType(
3931         Name, CanonicalConverted);
3932 
3933     // This might work out to be a current instantiation, in which
3934     // case the canonical type needs to be the InjectedClassNameType.
3935     //
3936     // TODO: in theory this could be a simple hashtable lookup; most
3937     // changes to CurContext don't change the set of current
3938     // instantiations.
3939     if (isa<ClassTemplateDecl>(Template)) {
3940       for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3941         // If we get out to a namespace, we're done.
3942         if (Ctx->isFileContext()) break;
3943 
3944         // If this isn't a record, keep looking.
3945         CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3946         if (!Record) continue;
3947 
3948         // Look for one of the two cases with InjectedClassNameTypes
3949         // and check whether it's the same template.
3950         if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3951             !Record->getDescribedClassTemplate())
3952           continue;
3953 
3954         // Fetch the injected class name type and check whether its
3955         // injected type is equal to the type we just built.
3956         QualType ICNT = Context.getTypeDeclType(Record);
3957         QualType Injected = cast<InjectedClassNameType>(ICNT)
3958           ->getInjectedSpecializationType();
3959 
3960         if (CanonType != Injected->getCanonicalTypeInternal())
3961           continue;
3962 
3963         // If so, the canonical type of this TST is the injected
3964         // class name type of the record we just found.
3965         assert(ICNT.isCanonical());
3966         CanonType = ICNT;
3967         break;
3968       }
3969     }
3970   } else if (ClassTemplateDecl *ClassTemplate =
3971                  dyn_cast<ClassTemplateDecl>(Template)) {
3972     // Find the class template specialization declaration that
3973     // corresponds to these arguments.
3974     void *InsertPos = nullptr;
3975     ClassTemplateSpecializationDecl *Decl =
3976         ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3977     if (!Decl) {
3978       // This is the first time we have referenced this class template
3979       // specialization. Create the canonical declaration and add it to
3980       // the set of specializations.
3981       Decl = ClassTemplateSpecializationDecl::Create(
3982           Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3983           ClassTemplate->getDeclContext(),
3984           ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3985           ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
3986           nullptr);
3987       ClassTemplate->AddSpecialization(Decl, InsertPos);
3988       if (ClassTemplate->isOutOfLine())
3989         Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3990     }
3991 
3992     if (Decl->getSpecializationKind() == TSK_Undeclared &&
3993         ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3994       InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3995       if (!Inst.isInvalid()) {
3996         MultiLevelTemplateArgumentList TemplateArgLists(Template,
3997                                                         CanonicalConverted,
3998                                                         /*Final=*/false);
3999         InstantiateAttrsForDecl(TemplateArgLists,
4000                                 ClassTemplate->getTemplatedDecl(), Decl);
4001       }
4002     }
4003 
4004     // Diagnose uses of this specialization.
4005     (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4006 
4007     CanonType = Context.getTypeDeclType(Decl);
4008     assert(isa<RecordType>(CanonType) &&
4009            "type of non-dependent specialization is not a RecordType");
4010   } else {
4011     llvm_unreachable("Unhandled template kind");
4012   }
4013 
4014   // Build the fully-sugared type for this class template
4015   // specialization, which refers back to the class template
4016   // specialization we created or found.
4017   return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
4018                                                CanonType);
4019 }
4020 
ActOnUndeclaredTypeTemplateName(Scope * S,TemplateTy & ParsedName,TemplateNameKind & TNK,SourceLocation NameLoc,IdentifierInfo * & II)4021 void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
4022                                            TemplateNameKind &TNK,
4023                                            SourceLocation NameLoc,
4024                                            IdentifierInfo *&II) {
4025   assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4026 
4027   TemplateName Name = ParsedName.get();
4028   auto *ATN = Name.getAsAssumedTemplateName();
4029   assert(ATN && "not an assumed template name");
4030   II = ATN->getDeclName().getAsIdentifierInfo();
4031 
4032   if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
4033     // Resolved to a type template name.
4034     ParsedName = TemplateTy::make(Name);
4035     TNK = TNK_Type_template;
4036   }
4037 }
4038 
resolveAssumedTemplateNameAsType(Scope * S,TemplateName & Name,SourceLocation NameLoc,bool Diagnose)4039 bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
4040                                             SourceLocation NameLoc,
4041                                             bool Diagnose) {
4042   // We assumed this undeclared identifier to be an (ADL-only) function
4043   // template name, but it was used in a context where a type was required.
4044   // Try to typo-correct it now.
4045   AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
4046   assert(ATN && "not an assumed template name");
4047 
4048   LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
4049   struct CandidateCallback : CorrectionCandidateCallback {
4050     bool ValidateCandidate(const TypoCorrection &TC) override {
4051       return TC.getCorrectionDecl() &&
4052              getAsTypeTemplateDecl(TC.getCorrectionDecl());
4053     }
4054     std::unique_ptr<CorrectionCandidateCallback> clone() override {
4055       return std::make_unique<CandidateCallback>(*this);
4056     }
4057   } FilterCCC;
4058 
4059   TypoCorrection Corrected =
4060       CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
4061                   FilterCCC, CTK_ErrorRecovery);
4062   if (Corrected && Corrected.getFoundDecl()) {
4063     diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
4064                                 << ATN->getDeclName());
4065     Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
4066     return false;
4067   }
4068 
4069   if (Diagnose)
4070     Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
4071   return true;
4072 }
4073 
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)4074 TypeResult Sema::ActOnTemplateIdType(
4075     Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4076     TemplateTy TemplateD, IdentifierInfo *TemplateII,
4077     SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
4078     ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
4079     bool IsCtorOrDtorName, bool IsClassName,
4080     ImplicitTypenameContext AllowImplicitTypename) {
4081   if (SS.isInvalid())
4082     return true;
4083 
4084   if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4085     DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4086 
4087     // C++ [temp.res]p3:
4088     //   A qualified-id that refers to a type and in which the
4089     //   nested-name-specifier depends on a template-parameter (14.6.2)
4090     //   shall be prefixed by the keyword typename to indicate that the
4091     //   qualified-id denotes a type, forming an
4092     //   elaborated-type-specifier (7.1.5.3).
4093     if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4094       // C++2a relaxes some of those restrictions in [temp.res]p5.
4095       if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4096         if (getLangOpts().CPlusPlus20)
4097           Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
4098         else
4099           Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
4100               << SS.getScopeRep() << TemplateII->getName()
4101               << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4102       } else
4103         Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
4104             << SS.getScopeRep() << TemplateII->getName();
4105 
4106       // FIXME: This is not quite correct recovery as we don't transform SS
4107       // into the corresponding dependent form (and we don't diagnose missing
4108       // 'template' keywords within SS as a result).
4109       return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4110                                TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4111                                TemplateArgsIn, RAngleLoc);
4112     }
4113 
4114     // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4115     // it's not actually allowed to be used as a type in most cases. Because
4116     // we annotate it before we know whether it's valid, we have to check for
4117     // this case here.
4118     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4119     if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4120       Diag(TemplateIILoc,
4121            TemplateKWLoc.isInvalid()
4122                ? diag::err_out_of_line_qualified_id_type_names_constructor
4123                : diag::ext_out_of_line_qualified_id_type_names_constructor)
4124         << TemplateII << 0 /*injected-class-name used as template name*/
4125         << 1 /*if any keyword was present, it was 'template'*/;
4126     }
4127   }
4128 
4129   TemplateName Template = TemplateD.get();
4130   if (Template.getAsAssumedTemplateName() &&
4131       resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
4132     return true;
4133 
4134   // Translate the parser's template argument list in our AST format.
4135   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4136   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4137 
4138   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4139     assert(SS.getScopeRep() == DTN->getQualifier());
4140     QualType T = Context.getDependentTemplateSpecializationType(
4141         ETK_None, DTN->getQualifier(), DTN->getIdentifier(),
4142         TemplateArgs.arguments());
4143     // Build type-source information.
4144     TypeLocBuilder TLB;
4145     DependentTemplateSpecializationTypeLoc SpecTL
4146       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
4147     SpecTL.setElaboratedKeywordLoc(SourceLocation());
4148     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4149     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4150     SpecTL.setTemplateNameLoc(TemplateIILoc);
4151     SpecTL.setLAngleLoc(LAngleLoc);
4152     SpecTL.setRAngleLoc(RAngleLoc);
4153     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4154       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4155     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4156   }
4157 
4158   QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
4159   if (SpecTy.isNull())
4160     return true;
4161 
4162   // Build type-source information.
4163   TypeLocBuilder TLB;
4164   TemplateSpecializationTypeLoc SpecTL =
4165       TLB.push<TemplateSpecializationTypeLoc>(SpecTy);
4166   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4167   SpecTL.setTemplateNameLoc(TemplateIILoc);
4168   SpecTL.setLAngleLoc(LAngleLoc);
4169   SpecTL.setRAngleLoc(RAngleLoc);
4170   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4171     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4172 
4173   // Create an elaborated-type-specifier containing the nested-name-specifier.
4174   QualType ElTy = getElaboratedType(
4175       ETK_None, !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
4176   ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
4177   ElabTL.setElaboratedKeywordLoc(SourceLocation());
4178   if (!ElabTL.isEmpty())
4179     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4180   return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
4181 }
4182 
ActOnTagTemplateIdType(TagUseKind TUK,TypeSpecifierType TagSpec,SourceLocation TagLoc,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,TemplateTy TemplateD,SourceLocation TemplateLoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc)4183 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4184                                         TypeSpecifierType TagSpec,
4185                                         SourceLocation TagLoc,
4186                                         CXXScopeSpec &SS,
4187                                         SourceLocation TemplateKWLoc,
4188                                         TemplateTy TemplateD,
4189                                         SourceLocation TemplateLoc,
4190                                         SourceLocation LAngleLoc,
4191                                         ASTTemplateArgsPtr TemplateArgsIn,
4192                                         SourceLocation RAngleLoc) {
4193   if (SS.isInvalid())
4194     return TypeResult(true);
4195 
4196   TemplateName Template = TemplateD.get();
4197 
4198   // Translate the parser's template argument list in our AST format.
4199   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4200   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4201 
4202   // Determine the tag kind
4203   TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4204   ElaboratedTypeKeyword Keyword
4205     = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
4206 
4207   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4208     assert(SS.getScopeRep() == DTN->getQualifier());
4209     QualType T = Context.getDependentTemplateSpecializationType(
4210         Keyword, DTN->getQualifier(), DTN->getIdentifier(),
4211         TemplateArgs.arguments());
4212 
4213     // Build type-source information.
4214     TypeLocBuilder TLB;
4215     DependentTemplateSpecializationTypeLoc SpecTL
4216       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
4217     SpecTL.setElaboratedKeywordLoc(TagLoc);
4218     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4219     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4220     SpecTL.setTemplateNameLoc(TemplateLoc);
4221     SpecTL.setLAngleLoc(LAngleLoc);
4222     SpecTL.setRAngleLoc(RAngleLoc);
4223     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4224       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4225     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4226   }
4227 
4228   if (TypeAliasTemplateDecl *TAT =
4229         dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
4230     // C++0x [dcl.type.elab]p2:
4231     //   If the identifier resolves to a typedef-name or the simple-template-id
4232     //   resolves to an alias template specialization, the
4233     //   elaborated-type-specifier is ill-formed.
4234     Diag(TemplateLoc, diag::err_tag_reference_non_tag)
4235         << TAT << NTK_TypeAliasTemplate << TagKind;
4236     Diag(TAT->getLocation(), diag::note_declared_at);
4237   }
4238 
4239   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
4240   if (Result.isNull())
4241     return TypeResult(true);
4242 
4243   // Check the tag kind
4244   if (const RecordType *RT = Result->getAs<RecordType>()) {
4245     RecordDecl *D = RT->getDecl();
4246 
4247     IdentifierInfo *Id = D->getIdentifier();
4248     assert(Id && "templated class must have an identifier");
4249 
4250     if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
4251                                       TagLoc, Id)) {
4252       Diag(TagLoc, diag::err_use_with_wrong_tag)
4253         << Result
4254         << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
4255       Diag(D->getLocation(), diag::note_previous_use);
4256     }
4257   }
4258 
4259   // Provide source-location information for the template specialization.
4260   TypeLocBuilder TLB;
4261   TemplateSpecializationTypeLoc SpecTL
4262     = TLB.push<TemplateSpecializationTypeLoc>(Result);
4263   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4264   SpecTL.setTemplateNameLoc(TemplateLoc);
4265   SpecTL.setLAngleLoc(LAngleLoc);
4266   SpecTL.setRAngleLoc(RAngleLoc);
4267   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4268     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4269 
4270   // Construct an elaborated type containing the nested-name-specifier (if any)
4271   // and tag keyword.
4272   Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
4273   ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
4274   ElabTL.setElaboratedKeywordLoc(TagLoc);
4275   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4276   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
4277 }
4278 
4279 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4280                                              NamedDecl *PrevDecl,
4281                                              SourceLocation Loc,
4282                                              bool IsPartialSpecialization);
4283 
4284 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4285 
isTemplateArgumentTemplateParameter(const TemplateArgument & Arg,unsigned Depth,unsigned Index)4286 static bool isTemplateArgumentTemplateParameter(
4287     const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
4288   switch (Arg.getKind()) {
4289   case TemplateArgument::Null:
4290   case TemplateArgument::NullPtr:
4291   case TemplateArgument::Integral:
4292   case TemplateArgument::Declaration:
4293   case TemplateArgument::Pack:
4294   case TemplateArgument::TemplateExpansion:
4295     return false;
4296 
4297   case TemplateArgument::Type: {
4298     QualType Type = Arg.getAsType();
4299     const TemplateTypeParmType *TPT =
4300         Arg.getAsType()->getAs<TemplateTypeParmType>();
4301     return TPT && !Type.hasQualifiers() &&
4302            TPT->getDepth() == Depth && TPT->getIndex() == Index;
4303   }
4304 
4305   case TemplateArgument::Expression: {
4306     DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4307     if (!DRE || !DRE->getDecl())
4308       return false;
4309     const NonTypeTemplateParmDecl *NTTP =
4310         dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4311     return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4312   }
4313 
4314   case TemplateArgument::Template:
4315     const TemplateTemplateParmDecl *TTP =
4316         dyn_cast_or_null<TemplateTemplateParmDecl>(
4317             Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4318     return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4319   }
4320   llvm_unreachable("unexpected kind of template argument");
4321 }
4322 
isSameAsPrimaryTemplate(TemplateParameterList * Params,ArrayRef<TemplateArgument> Args)4323 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4324                                     ArrayRef<TemplateArgument> Args) {
4325   if (Params->size() != Args.size())
4326     return false;
4327 
4328   unsigned Depth = Params->getDepth();
4329 
4330   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4331     TemplateArgument Arg = Args[I];
4332 
4333     // If the parameter is a pack expansion, the argument must be a pack
4334     // whose only element is a pack expansion.
4335     if (Params->getParam(I)->isParameterPack()) {
4336       if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4337           !Arg.pack_begin()->isPackExpansion())
4338         return false;
4339       Arg = Arg.pack_begin()->getPackExpansionPattern();
4340     }
4341 
4342     if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4343       return false;
4344   }
4345 
4346   return true;
4347 }
4348 
4349 template<typename PartialSpecDecl>
checkMoreSpecializedThanPrimary(Sema & S,PartialSpecDecl * Partial)4350 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4351   if (Partial->getDeclContext()->isDependentContext())
4352     return;
4353 
4354   // FIXME: Get the TDK from deduction in order to provide better diagnostics
4355   // for non-substitution-failure issues?
4356   TemplateDeductionInfo Info(Partial->getLocation());
4357   if (S.isMoreSpecializedThanPrimary(Partial, Info))
4358     return;
4359 
4360   auto *Template = Partial->getSpecializedTemplate();
4361   S.Diag(Partial->getLocation(),
4362          diag::ext_partial_spec_not_more_specialized_than_primary)
4363       << isa<VarTemplateDecl>(Template);
4364 
4365   if (Info.hasSFINAEDiagnostic()) {
4366     PartialDiagnosticAt Diag = {SourceLocation(),
4367                                 PartialDiagnostic::NullDiagnostic()};
4368     Info.takeSFINAEDiagnostic(Diag);
4369     SmallString<128> SFINAEArgString;
4370     Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4371     S.Diag(Diag.first,
4372            diag::note_partial_spec_not_more_specialized_than_primary)
4373       << SFINAEArgString;
4374   }
4375 
4376   S.Diag(Template->getLocation(), diag::note_template_decl_here);
4377   SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4378   Template->getAssociatedConstraints(TemplateAC);
4379   Partial->getAssociatedConstraints(PartialAC);
4380   S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4381                                                   TemplateAC);
4382 }
4383 
4384 static void
noteNonDeducibleParameters(Sema & S,TemplateParameterList * TemplateParams,const llvm::SmallBitVector & DeducibleParams)4385 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4386                            const llvm::SmallBitVector &DeducibleParams) {
4387   for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4388     if (!DeducibleParams[I]) {
4389       NamedDecl *Param = TemplateParams->getParam(I);
4390       if (Param->getDeclName())
4391         S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4392             << Param->getDeclName();
4393       else
4394         S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4395             << "(anonymous)";
4396     }
4397   }
4398 }
4399 
4400 
4401 template<typename PartialSpecDecl>
checkTemplatePartialSpecialization(Sema & S,PartialSpecDecl * Partial)4402 static void checkTemplatePartialSpecialization(Sema &S,
4403                                                PartialSpecDecl *Partial) {
4404   // C++1z [temp.class.spec]p8: (DR1495)
4405   //   - The specialization shall be more specialized than the primary
4406   //     template (14.5.5.2).
4407   checkMoreSpecializedThanPrimary(S, Partial);
4408 
4409   // C++ [temp.class.spec]p8: (DR1315)
4410   //   - Each template-parameter shall appear at least once in the
4411   //     template-id outside a non-deduced context.
4412   // C++1z [temp.class.spec.match]p3 (P0127R2)
4413   //   If the template arguments of a partial specialization cannot be
4414   //   deduced because of the structure of its template-parameter-list
4415   //   and the template-id, the program is ill-formed.
4416   auto *TemplateParams = Partial->getTemplateParameters();
4417   llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4418   S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4419                                TemplateParams->getDepth(), DeducibleParams);
4420 
4421   if (!DeducibleParams.all()) {
4422     unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4423     S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4424       << isa<VarTemplatePartialSpecializationDecl>(Partial)
4425       << (NumNonDeducible > 1)
4426       << SourceRange(Partial->getLocation(),
4427                      Partial->getTemplateArgsAsWritten()->RAngleLoc);
4428     noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4429   }
4430 }
4431 
CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl * Partial)4432 void Sema::CheckTemplatePartialSpecialization(
4433     ClassTemplatePartialSpecializationDecl *Partial) {
4434   checkTemplatePartialSpecialization(*this, Partial);
4435 }
4436 
CheckTemplatePartialSpecialization(VarTemplatePartialSpecializationDecl * Partial)4437 void Sema::CheckTemplatePartialSpecialization(
4438     VarTemplatePartialSpecializationDecl *Partial) {
4439   checkTemplatePartialSpecialization(*this, Partial);
4440 }
4441 
CheckDeductionGuideTemplate(FunctionTemplateDecl * TD)4442 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4443   // C++1z [temp.param]p11:
4444   //   A template parameter of a deduction guide template that does not have a
4445   //   default-argument shall be deducible from the parameter-type-list of the
4446   //   deduction guide template.
4447   auto *TemplateParams = TD->getTemplateParameters();
4448   llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4449   MarkDeducedTemplateParameters(TD, DeducibleParams);
4450   for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4451     // A parameter pack is deducible (to an empty pack).
4452     auto *Param = TemplateParams->getParam(I);
4453     if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4454       DeducibleParams[I] = true;
4455   }
4456 
4457   if (!DeducibleParams.all()) {
4458     unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4459     Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4460       << (NumNonDeducible > 1);
4461     noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4462   }
4463 }
4464 
ActOnVarTemplateSpecialization(Scope * S,Declarator & D,TypeSourceInfo * DI,SourceLocation TemplateKWLoc,TemplateParameterList * TemplateParams,StorageClass SC,bool IsPartialSpecialization)4465 DeclResult Sema::ActOnVarTemplateSpecialization(
4466     Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
4467     TemplateParameterList *TemplateParams, StorageClass SC,
4468     bool IsPartialSpecialization) {
4469   // D must be variable template id.
4470   assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4471          "Variable template specialization is declared with a template id.");
4472 
4473   TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4474   TemplateArgumentListInfo TemplateArgs =
4475       makeTemplateArgumentListInfo(*this, *TemplateId);
4476   SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4477   SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4478   SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4479 
4480   TemplateName Name = TemplateId->Template.get();
4481 
4482   // The template-id must name a variable template.
4483   VarTemplateDecl *VarTemplate =
4484       dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4485   if (!VarTemplate) {
4486     NamedDecl *FnTemplate;
4487     if (auto *OTS = Name.getAsOverloadedTemplate())
4488       FnTemplate = *OTS->begin();
4489     else
4490       FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4491     if (FnTemplate)
4492       return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4493                << FnTemplate->getDeclName();
4494     return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4495              << IsPartialSpecialization;
4496   }
4497 
4498   // Check for unexpanded parameter packs in any of the template arguments.
4499   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4500     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4501                                         UPPC_PartialSpecialization))
4502       return true;
4503 
4504   // Check that the template argument list is well-formed for this
4505   // template.
4506   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4507   if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4508                                 false, SugaredConverted, CanonicalConverted,
4509                                 /*UpdateArgsWithConversions=*/true))
4510     return true;
4511 
4512   // Find the variable template (partial) specialization declaration that
4513   // corresponds to these arguments.
4514   if (IsPartialSpecialization) {
4515     if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4516                                                TemplateArgs.size(),
4517                                                CanonicalConverted))
4518       return true;
4519 
4520     // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4521     // also do them during instantiation.
4522     if (!Name.isDependent() &&
4523         !TemplateSpecializationType::anyDependentTemplateArguments(
4524             TemplateArgs, CanonicalConverted)) {
4525       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4526           << VarTemplate->getDeclName();
4527       IsPartialSpecialization = false;
4528     }
4529 
4530     if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4531                                 CanonicalConverted) &&
4532         (!Context.getLangOpts().CPlusPlus20 ||
4533          !TemplateParams->hasAssociatedConstraints())) {
4534       // C++ [temp.class.spec]p9b3:
4535       //
4536       //   -- The argument list of the specialization shall not be identical
4537       //      to the implicit argument list of the primary template.
4538       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4539         << /*variable template*/ 1
4540         << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4541         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4542       // FIXME: Recover from this by treating the declaration as a redeclaration
4543       // of the primary template.
4544       return true;
4545     }
4546   }
4547 
4548   void *InsertPos = nullptr;
4549   VarTemplateSpecializationDecl *PrevDecl = nullptr;
4550 
4551   if (IsPartialSpecialization)
4552     PrevDecl = VarTemplate->findPartialSpecialization(
4553         CanonicalConverted, TemplateParams, InsertPos);
4554   else
4555     PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4556 
4557   VarTemplateSpecializationDecl *Specialization = nullptr;
4558 
4559   // Check whether we can declare a variable template specialization in
4560   // the current scope.
4561   if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4562                                        TemplateNameLoc,
4563                                        IsPartialSpecialization))
4564     return true;
4565 
4566   if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4567     // Since the only prior variable template specialization with these
4568     // arguments was referenced but not declared,  reuse that
4569     // declaration node as our own, updating its source location and
4570     // the list of outer template parameters to reflect our new declaration.
4571     Specialization = PrevDecl;
4572     Specialization->setLocation(TemplateNameLoc);
4573     PrevDecl = nullptr;
4574   } else if (IsPartialSpecialization) {
4575     // Create a new class template partial specialization declaration node.
4576     VarTemplatePartialSpecializationDecl *PrevPartial =
4577         cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4578     VarTemplatePartialSpecializationDecl *Partial =
4579         VarTemplatePartialSpecializationDecl::Create(
4580             Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4581             TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4582             CanonicalConverted, TemplateArgs);
4583 
4584     if (!PrevPartial)
4585       VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4586     Specialization = Partial;
4587 
4588     // If we are providing an explicit specialization of a member variable
4589     // template specialization, make a note of that.
4590     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4591       PrevPartial->setMemberSpecialization();
4592 
4593     CheckTemplatePartialSpecialization(Partial);
4594   } else {
4595     // Create a new class template specialization declaration node for
4596     // this explicit specialization or friend declaration.
4597     Specialization = VarTemplateSpecializationDecl::Create(
4598         Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4599         VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4600     Specialization->setTemplateArgsInfo(TemplateArgs);
4601 
4602     if (!PrevDecl)
4603       VarTemplate->AddSpecialization(Specialization, InsertPos);
4604   }
4605 
4606   // C++ [temp.expl.spec]p6:
4607   //   If a template, a member template or the member of a class template is
4608   //   explicitly specialized then that specialization shall be declared
4609   //   before the first use of that specialization that would cause an implicit
4610   //   instantiation to take place, in every translation unit in which such a
4611   //   use occurs; no diagnostic is required.
4612   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4613     bool Okay = false;
4614     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4615       // Is there any previous explicit specialization declaration?
4616       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4617         Okay = true;
4618         break;
4619       }
4620     }
4621 
4622     if (!Okay) {
4623       SourceRange Range(TemplateNameLoc, RAngleLoc);
4624       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4625           << Name << Range;
4626 
4627       Diag(PrevDecl->getPointOfInstantiation(),
4628            diag::note_instantiation_required_here)
4629           << (PrevDecl->getTemplateSpecializationKind() !=
4630               TSK_ImplicitInstantiation);
4631       return true;
4632     }
4633   }
4634 
4635   Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4636   Specialization->setLexicalDeclContext(CurContext);
4637 
4638   // Add the specialization into its lexical context, so that it can
4639   // be seen when iterating through the list of declarations in that
4640   // context. However, specializations are not found by name lookup.
4641   CurContext->addDecl(Specialization);
4642 
4643   // Note that this is an explicit specialization.
4644   Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4645 
4646   if (PrevDecl) {
4647     // Check that this isn't a redefinition of this specialization,
4648     // merging with previous declarations.
4649     LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
4650                           forRedeclarationInCurContext());
4651     PrevSpec.addDecl(PrevDecl);
4652     D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
4653   } else if (Specialization->isStaticDataMember() &&
4654              Specialization->isOutOfLine()) {
4655     Specialization->setAccess(VarTemplate->getAccess());
4656   }
4657 
4658   return Specialization;
4659 }
4660 
4661 namespace {
4662 /// A partial specialization whose template arguments have matched
4663 /// a given template-id.
4664 struct PartialSpecMatchResult {
4665   VarTemplatePartialSpecializationDecl *Partial;
4666   TemplateArgumentList *Args;
4667 };
4668 } // end anonymous namespace
4669 
4670 DeclResult
CheckVarTemplateId(VarTemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation TemplateNameLoc,const TemplateArgumentListInfo & TemplateArgs)4671 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4672                          SourceLocation TemplateNameLoc,
4673                          const TemplateArgumentListInfo &TemplateArgs) {
4674   assert(Template && "A variable template id without template?");
4675 
4676   // Check that the template argument list is well-formed for this template.
4677   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4678   if (CheckTemplateArgumentList(
4679           Template, TemplateNameLoc,
4680           const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4681           SugaredConverted, CanonicalConverted,
4682           /*UpdateArgsWithConversions=*/true))
4683     return true;
4684 
4685   // Produce a placeholder value if the specialization is dependent.
4686   if (Template->getDeclContext()->isDependentContext() ||
4687       TemplateSpecializationType::anyDependentTemplateArguments(
4688           TemplateArgs, CanonicalConverted))
4689     return DeclResult();
4690 
4691   // Find the variable template specialization declaration that
4692   // corresponds to these arguments.
4693   void *InsertPos = nullptr;
4694   if (VarTemplateSpecializationDecl *Spec =
4695           Template->findSpecialization(CanonicalConverted, InsertPos)) {
4696     checkSpecializationReachability(TemplateNameLoc, Spec);
4697     // If we already have a variable template specialization, return it.
4698     return Spec;
4699   }
4700 
4701   // This is the first time we have referenced this variable template
4702   // specialization. Create the canonical declaration and add it to
4703   // the set of specializations, based on the closest partial specialization
4704   // that it represents. That is,
4705   VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4706   TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
4707                                        CanonicalConverted);
4708   TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4709   bool AmbiguousPartialSpec = false;
4710   typedef PartialSpecMatchResult MatchResult;
4711   SmallVector<MatchResult, 4> Matched;
4712   SourceLocation PointOfInstantiation = TemplateNameLoc;
4713   TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4714                                             /*ForTakingAddress=*/false);
4715 
4716   // 1. Attempt to find the closest partial specialization that this
4717   // specializes, if any.
4718   // TODO: Unify with InstantiateClassTemplateSpecialization()?
4719   //       Perhaps better after unification of DeduceTemplateArguments() and
4720   //       getMoreSpecializedPartialSpecialization().
4721   SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4722   Template->getPartialSpecializations(PartialSpecs);
4723 
4724   for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4725     VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4726     TemplateDeductionInfo Info(FailedCandidates.getLocation());
4727 
4728     if (TemplateDeductionResult Result =
4729             DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4730       // Store the failed-deduction information for use in diagnostics, later.
4731       // TODO: Actually use the failed-deduction info?
4732       FailedCandidates.addCandidate().set(
4733           DeclAccessPair::make(Template, AS_public), Partial,
4734           MakeDeductionFailureInfo(Context, Result, Info));
4735       (void)Result;
4736     } else {
4737       Matched.push_back(PartialSpecMatchResult());
4738       Matched.back().Partial = Partial;
4739       Matched.back().Args = Info.takeCanonical();
4740     }
4741   }
4742 
4743   if (Matched.size() >= 1) {
4744     SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4745     if (Matched.size() == 1) {
4746       //   -- If exactly one matching specialization is found, the
4747       //      instantiation is generated from that specialization.
4748       // We don't need to do anything for this.
4749     } else {
4750       //   -- If more than one matching specialization is found, the
4751       //      partial order rules (14.5.4.2) are used to determine
4752       //      whether one of the specializations is more specialized
4753       //      than the others. If none of the specializations is more
4754       //      specialized than all of the other matching
4755       //      specializations, then the use of the variable template is
4756       //      ambiguous and the program is ill-formed.
4757       for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4758                                                  PEnd = Matched.end();
4759            P != PEnd; ++P) {
4760         if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4761                                                     PointOfInstantiation) ==
4762             P->Partial)
4763           Best = P;
4764       }
4765 
4766       // Determine if the best partial specialization is more specialized than
4767       // the others.
4768       for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4769                                                  PEnd = Matched.end();
4770            P != PEnd; ++P) {
4771         if (P != Best && getMoreSpecializedPartialSpecialization(
4772                              P->Partial, Best->Partial,
4773                              PointOfInstantiation) != Best->Partial) {
4774           AmbiguousPartialSpec = true;
4775           break;
4776         }
4777       }
4778     }
4779 
4780     // Instantiate using the best variable template partial specialization.
4781     InstantiationPattern = Best->Partial;
4782     InstantiationArgs = Best->Args;
4783   } else {
4784     //   -- If no match is found, the instantiation is generated
4785     //      from the primary template.
4786     // InstantiationPattern = Template->getTemplatedDecl();
4787   }
4788 
4789   // 2. Create the canonical declaration.
4790   // Note that we do not instantiate a definition until we see an odr-use
4791   // in DoMarkVarDeclReferenced().
4792   // FIXME: LateAttrs et al.?
4793   VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4794       Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4795       CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4796   if (!Decl)
4797     return true;
4798 
4799   if (AmbiguousPartialSpec) {
4800     // Partial ordering did not produce a clear winner. Complain.
4801     Decl->setInvalidDecl();
4802     Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4803         << Decl;
4804 
4805     // Print the matching partial specializations.
4806     for (MatchResult P : Matched)
4807       Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4808           << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4809                                              *P.Args);
4810     return true;
4811   }
4812 
4813   if (VarTemplatePartialSpecializationDecl *D =
4814           dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4815     Decl->setInstantiationOf(D, InstantiationArgs);
4816 
4817   checkSpecializationReachability(TemplateNameLoc, Decl);
4818 
4819   assert(Decl && "No variable template specialization?");
4820   return Decl;
4821 }
4822 
4823 ExprResult
CheckVarTemplateId(const CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,VarTemplateDecl * Template,SourceLocation TemplateLoc,const TemplateArgumentListInfo * TemplateArgs)4824 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4825                          const DeclarationNameInfo &NameInfo,
4826                          VarTemplateDecl *Template, SourceLocation TemplateLoc,
4827                          const TemplateArgumentListInfo *TemplateArgs) {
4828 
4829   DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4830                                        *TemplateArgs);
4831   if (Decl.isInvalid())
4832     return ExprError();
4833 
4834   if (!Decl.get())
4835     return ExprResult();
4836 
4837   VarDecl *Var = cast<VarDecl>(Decl.get());
4838   if (!Var->getTemplateSpecializationKind())
4839     Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4840                                        NameInfo.getLoc());
4841 
4842   // Build an ordinary singleton decl ref.
4843   return BuildDeclarationNameExpr(SS, NameInfo, Var,
4844                                   /*FoundD=*/nullptr, TemplateArgs);
4845 }
4846 
diagnoseMissingTemplateArguments(TemplateName Name,SourceLocation Loc)4847 void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4848                                             SourceLocation Loc) {
4849   Diag(Loc, diag::err_template_missing_args)
4850     << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4851   if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4852     Diag(TD->getLocation(), diag::note_template_decl_here)
4853       << TD->getTemplateParameters()->getSourceRange();
4854   }
4855 }
4856 
4857 ExprResult
CheckConceptTemplateId(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & ConceptNameInfo,NamedDecl * FoundDecl,ConceptDecl * NamedConcept,const TemplateArgumentListInfo * TemplateArgs)4858 Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4859                              SourceLocation TemplateKWLoc,
4860                              const DeclarationNameInfo &ConceptNameInfo,
4861                              NamedDecl *FoundDecl,
4862                              ConceptDecl *NamedConcept,
4863                              const TemplateArgumentListInfo *TemplateArgs) {
4864   assert(NamedConcept && "A concept template id without a template?");
4865 
4866   llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4867   if (CheckTemplateArgumentList(
4868           NamedConcept, ConceptNameInfo.getLoc(),
4869           const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4870           /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
4871           /*UpdateArgsWithConversions=*/false))
4872     return ExprError();
4873 
4874   auto *CSD = ImplicitConceptSpecializationDecl::Create(
4875       Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4876       CanonicalConverted);
4877   ConstraintSatisfaction Satisfaction;
4878   bool AreArgsDependent =
4879       TemplateSpecializationType::anyDependentTemplateArguments(
4880           *TemplateArgs, CanonicalConverted);
4881   MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
4882                                        /*Final=*/false);
4883   LocalInstantiationScope Scope(*this);
4884 
4885   EnterExpressionEvaluationContext EECtx{
4886       *this, ExpressionEvaluationContext::ConstantEvaluated, CSD};
4887 
4888   if (!AreArgsDependent &&
4889       CheckConstraintSatisfaction(
4890           NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
4891           SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4892                       TemplateArgs->getRAngleLoc()),
4893           Satisfaction))
4894     return ExprError();
4895 
4896   return ConceptSpecializationExpr::Create(
4897       Context,
4898       SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4899       TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4900       ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs), CSD,
4901       AreArgsDependent ? nullptr : &Satisfaction);
4902 }
4903 
BuildTemplateIdExpr(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,LookupResult & R,bool RequiresADL,const TemplateArgumentListInfo * TemplateArgs)4904 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4905                                      SourceLocation TemplateKWLoc,
4906                                      LookupResult &R,
4907                                      bool RequiresADL,
4908                                  const TemplateArgumentListInfo *TemplateArgs) {
4909   // FIXME: Can we do any checking at this point? I guess we could check the
4910   // template arguments that we have against the template name, if the template
4911   // name refers to a single template. That's not a terribly common case,
4912   // though.
4913   // foo<int> could identify a single function unambiguously
4914   // This approach does NOT work, since f<int>(1);
4915   // gets resolved prior to resorting to overload resolution
4916   // i.e., template<class T> void f(double);
4917   //       vs template<class T, class U> void f(U);
4918 
4919   // These should be filtered out by our callers.
4920   assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4921 
4922   // Non-function templates require a template argument list.
4923   if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4924     if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4925       diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4926       return ExprError();
4927     }
4928   }
4929 
4930   // In C++1y, check variable template ids.
4931   if (R.getAsSingle<VarTemplateDecl>()) {
4932     ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(),
4933                                         R.getAsSingle<VarTemplateDecl>(),
4934                                         TemplateKWLoc, TemplateArgs);
4935     if (Res.isInvalid() || Res.isUsable())
4936       return Res;
4937     // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
4938   }
4939 
4940   if (R.getAsSingle<ConceptDecl>()) {
4941     return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4942                                   R.getFoundDecl(),
4943                                   R.getAsSingle<ConceptDecl>(), TemplateArgs);
4944   }
4945 
4946   // We don't want lookup warnings at this point.
4947   R.suppressDiagnostics();
4948 
4949   UnresolvedLookupExpr *ULE
4950     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
4951                                    SS.getWithLocInContext(Context),
4952                                    TemplateKWLoc,
4953                                    R.getLookupNameInfo(),
4954                                    RequiresADL, TemplateArgs,
4955                                    R.begin(), R.end());
4956 
4957   return ULE;
4958 }
4959 
4960 // We actually only call this from template instantiation.
4961 ExprResult
BuildQualifiedTemplateIdExpr(CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * TemplateArgs)4962 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4963                                    SourceLocation TemplateKWLoc,
4964                                    const DeclarationNameInfo &NameInfo,
4965                              const TemplateArgumentListInfo *TemplateArgs) {
4966 
4967   assert(TemplateArgs || TemplateKWLoc.isValid());
4968   DeclContext *DC;
4969   if (!(DC = computeDeclContext(SS, false)) ||
4970       DC->isDependentContext() ||
4971       RequireCompleteDeclContext(SS, DC))
4972     return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4973 
4974   bool MemberOfUnknownSpecialization;
4975   LookupResult R(*this, NameInfo, LookupOrdinaryName);
4976   if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4977                          /*Entering*/false, MemberOfUnknownSpecialization,
4978                          TemplateKWLoc))
4979     return ExprError();
4980 
4981   if (R.isAmbiguous())
4982     return ExprError();
4983 
4984   if (R.empty()) {
4985     Diag(NameInfo.getLoc(), diag::err_no_member)
4986       << NameInfo.getName() << DC << SS.getRange();
4987     return ExprError();
4988   }
4989 
4990   if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4991     Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4992       << SS.getScopeRep()
4993       << NameInfo.getName().getAsString() << SS.getRange();
4994     Diag(Temp->getLocation(), diag::note_referenced_class_template);
4995     return ExprError();
4996   }
4997 
4998   return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4999 }
5000 
5001 /// Form a template name from a name that is syntactically required to name a
5002 /// template, either due to use of the 'template' keyword or because a name in
5003 /// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
5004 ///
5005 /// This action forms a template name given the name of the template and its
5006 /// optional scope specifier. This is used when the 'template' keyword is used
5007 /// or when the parsing context unambiguously treats a following '<' as
5008 /// introducing a template argument list. Note that this may produce a
5009 /// non-dependent template name if we can perform the lookup now and identify
5010 /// the named template.
5011 ///
5012 /// For example, given "x.MetaFun::template apply", the scope specifier
5013 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
5014 /// 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)5015 TemplateNameKind Sema::ActOnTemplateName(Scope *S,
5016                                          CXXScopeSpec &SS,
5017                                          SourceLocation TemplateKWLoc,
5018                                          const UnqualifiedId &Name,
5019                                          ParsedType ObjectType,
5020                                          bool EnteringContext,
5021                                          TemplateTy &Result,
5022                                          bool AllowInjectedClassName) {
5023   if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5024     Diag(TemplateKWLoc,
5025          getLangOpts().CPlusPlus11 ?
5026            diag::warn_cxx98_compat_template_outside_of_template :
5027            diag::ext_template_outside_of_template)
5028       << FixItHint::CreateRemoval(TemplateKWLoc);
5029 
5030   if (SS.isInvalid())
5031     return TNK_Non_template;
5032 
5033   // Figure out where isTemplateName is going to look.
5034   DeclContext *LookupCtx = nullptr;
5035   if (SS.isNotEmpty())
5036     LookupCtx = computeDeclContext(SS, EnteringContext);
5037   else if (ObjectType)
5038     LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5039 
5040   // C++0x [temp.names]p5:
5041   //   If a name prefixed by the keyword template is not the name of
5042   //   a template, the program is ill-formed. [Note: the keyword
5043   //   template may not be applied to non-template members of class
5044   //   templates. -end note ] [ Note: as is the case with the
5045   //   typename prefix, the template prefix is allowed in cases
5046   //   where it is not strictly necessary; i.e., when the
5047   //   nested-name-specifier or the expression on the left of the ->
5048   //   or . is not dependent on a template-parameter, or the use
5049   //   does not appear in the scope of a template. -end note]
5050   //
5051   // Note: C++03 was more strict here, because it banned the use of
5052   // the "template" keyword prior to a template-name that was not a
5053   // dependent name. C++ DR468 relaxed this requirement (the
5054   // "template" keyword is now permitted). We follow the C++0x
5055   // rules, even in C++03 mode with a warning, retroactively applying the DR.
5056   bool MemberOfUnknownSpecialization;
5057   TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5058                                         ObjectType, EnteringContext, Result,
5059                                         MemberOfUnknownSpecialization);
5060   if (TNK != TNK_Non_template) {
5061     // We resolved this to a (non-dependent) template name. Return it.
5062     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5063     if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5064         Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5065         Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5066       // C++14 [class.qual]p2:
5067       //   In a lookup in which function names are not ignored and the
5068       //   nested-name-specifier nominates a class C, if the name specified
5069       //   [...] is the injected-class-name of C, [...] the name is instead
5070       //   considered to name the constructor
5071       //
5072       // We don't get here if naming the constructor would be valid, so we
5073       // just reject immediately and recover by treating the
5074       // injected-class-name as naming the template.
5075       Diag(Name.getBeginLoc(),
5076            diag::ext_out_of_line_qualified_id_type_names_constructor)
5077           << Name.Identifier
5078           << 0 /*injected-class-name used as template name*/
5079           << TemplateKWLoc.isValid();
5080     }
5081     return TNK;
5082   }
5083 
5084   if (!MemberOfUnknownSpecialization) {
5085     // Didn't find a template name, and the lookup wasn't dependent.
5086     // Do the lookup again to determine if this is a "nothing found" case or
5087     // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5088     // need to do this.
5089     DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
5090     LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5091                    LookupOrdinaryName);
5092     bool MOUS;
5093     // Tell LookupTemplateName that we require a template so that it diagnoses
5094     // cases where it finds a non-template.
5095     RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5096                                    ? RequiredTemplateKind(TemplateKWLoc)
5097                                    : TemplateNameIsRequired;
5098     if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS,
5099                             RTK, nullptr, /*AllowTypoCorrection=*/false) &&
5100         !R.isAmbiguous()) {
5101       if (LookupCtx)
5102         Diag(Name.getBeginLoc(), diag::err_no_member)
5103             << DNI.getName() << LookupCtx << SS.getRange();
5104       else
5105         Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5106             << DNI.getName() << SS.getRange();
5107     }
5108     return TNK_Non_template;
5109   }
5110 
5111   NestedNameSpecifier *Qualifier = SS.getScopeRep();
5112 
5113   switch (Name.getKind()) {
5114   case UnqualifiedIdKind::IK_Identifier:
5115     Result = TemplateTy::make(
5116         Context.getDependentTemplateName(Qualifier, Name.Identifier));
5117     return TNK_Dependent_template_name;
5118 
5119   case UnqualifiedIdKind::IK_OperatorFunctionId:
5120     Result = TemplateTy::make(Context.getDependentTemplateName(
5121         Qualifier, Name.OperatorFunctionId.Operator));
5122     return TNK_Function_template;
5123 
5124   case UnqualifiedIdKind::IK_LiteralOperatorId:
5125     // This is a kind of template name, but can never occur in a dependent
5126     // scope (literal operators can only be declared at namespace scope).
5127     break;
5128 
5129   default:
5130     break;
5131   }
5132 
5133   // This name cannot possibly name a dependent template. Diagnose this now
5134   // rather than building a dependent template name that can never be valid.
5135   Diag(Name.getBeginLoc(),
5136        diag::err_template_kw_refers_to_dependent_non_template)
5137       << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5138       << TemplateKWLoc.isValid() << TemplateKWLoc;
5139   return TNK_Non_template;
5140 }
5141 
CheckTemplateTypeArgument(TemplateTypeParmDecl * Param,TemplateArgumentLoc & AL,SmallVectorImpl<TemplateArgument> & SugaredConverted,SmallVectorImpl<TemplateArgument> & CanonicalConverted)5142 bool Sema::CheckTemplateTypeArgument(
5143     TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
5144     SmallVectorImpl<TemplateArgument> &SugaredConverted,
5145     SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5146   const TemplateArgument &Arg = AL.getArgument();
5147   QualType ArgType;
5148   TypeSourceInfo *TSI = nullptr;
5149 
5150   // Check template type parameter.
5151   switch(Arg.getKind()) {
5152   case TemplateArgument::Type:
5153     // C++ [temp.arg.type]p1:
5154     //   A template-argument for a template-parameter which is a
5155     //   type shall be a type-id.
5156     ArgType = Arg.getAsType();
5157     TSI = AL.getTypeSourceInfo();
5158     break;
5159   case TemplateArgument::Template:
5160   case TemplateArgument::TemplateExpansion: {
5161     // We have a template type parameter but the template argument
5162     // is a template without any arguments.
5163     SourceRange SR = AL.getSourceRange();
5164     TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5165     diagnoseMissingTemplateArguments(Name, SR.getEnd());
5166     return true;
5167   }
5168   case TemplateArgument::Expression: {
5169     // We have a template type parameter but the template argument is an
5170     // expression; see if maybe it is missing the "typename" keyword.
5171     CXXScopeSpec SS;
5172     DeclarationNameInfo NameInfo;
5173 
5174    if (DependentScopeDeclRefExpr *ArgExpr =
5175                dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5176       SS.Adopt(ArgExpr->getQualifierLoc());
5177       NameInfo = ArgExpr->getNameInfo();
5178     } else if (CXXDependentScopeMemberExpr *ArgExpr =
5179                dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5180       if (ArgExpr->isImplicitAccess()) {
5181         SS.Adopt(ArgExpr->getQualifierLoc());
5182         NameInfo = ArgExpr->getMemberNameInfo();
5183       }
5184     }
5185 
5186     if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5187       LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5188       LookupParsedName(Result, CurScope, &SS);
5189 
5190       if (Result.getAsSingle<TypeDecl>() ||
5191           Result.getResultKind() ==
5192               LookupResult::NotFoundInCurrentInstantiation) {
5193         assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5194         // Suggest that the user add 'typename' before the NNS.
5195         SourceLocation Loc = AL.getSourceRange().getBegin();
5196         Diag(Loc, getLangOpts().MSVCCompat
5197                       ? diag::ext_ms_template_type_arg_missing_typename
5198                       : diag::err_template_arg_must_be_type_suggest)
5199             << FixItHint::CreateInsertion(Loc, "typename ");
5200         Diag(Param->getLocation(), diag::note_template_param_here);
5201 
5202         // Recover by synthesizing a type using the location information that we
5203         // already have.
5204         ArgType =
5205             Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
5206         TypeLocBuilder TLB;
5207         DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
5208         TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5209         TL.setQualifierLoc(SS.getWithLocInContext(Context));
5210         TL.setNameLoc(NameInfo.getLoc());
5211         TSI = TLB.getTypeSourceInfo(Context, ArgType);
5212 
5213         // Overwrite our input TemplateArgumentLoc so that we can recover
5214         // properly.
5215         AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5216                                  TemplateArgumentLocInfo(TSI));
5217 
5218         break;
5219       }
5220     }
5221     // fallthrough
5222     [[fallthrough]];
5223   }
5224   default: {
5225     // We have a template type parameter but the template argument
5226     // is not a type.
5227     SourceRange SR = AL.getSourceRange();
5228     Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5229     Diag(Param->getLocation(), diag::note_template_param_here);
5230 
5231     return true;
5232   }
5233   }
5234 
5235   if (CheckTemplateArgument(TSI))
5236     return true;
5237 
5238   // Objective-C ARC:
5239   //   If an explicitly-specified template argument type is a lifetime type
5240   //   with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5241   if (getLangOpts().ObjCAutoRefCount &&
5242       ArgType->isObjCLifetimeType() &&
5243       !ArgType.getObjCLifetime()) {
5244     Qualifiers Qs;
5245     Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5246     ArgType = Context.getQualifiedType(ArgType, Qs);
5247   }
5248 
5249   SugaredConverted.push_back(TemplateArgument(ArgType));
5250   CanonicalConverted.push_back(
5251       TemplateArgument(Context.getCanonicalType(ArgType)));
5252   return false;
5253 }
5254 
5255 /// Substitute template arguments into the default template argument for
5256 /// the given template type parameter.
5257 ///
5258 /// \param SemaRef the semantic analysis object for which we are performing
5259 /// the substitution.
5260 ///
5261 /// \param Template the template that we are synthesizing template arguments
5262 /// for.
5263 ///
5264 /// \param TemplateLoc the location of the template name that started the
5265 /// template-id we are checking.
5266 ///
5267 /// \param RAngleLoc the location of the right angle bracket ('>') that
5268 /// terminates the template-id.
5269 ///
5270 /// \param Param the template template parameter whose default we are
5271 /// substituting into.
5272 ///
5273 /// \param Converted the list of template arguments provided for template
5274 /// parameters that precede \p Param in the template parameter list.
5275 /// \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)5276 static TypeSourceInfo *SubstDefaultTemplateArgument(
5277     Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5278     SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5279     ArrayRef<TemplateArgument> SugaredConverted,
5280     ArrayRef<TemplateArgument> CanonicalConverted) {
5281   TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
5282 
5283   // If the argument type is dependent, instantiate it now based
5284   // on the previously-computed template arguments.
5285   if (ArgType->getType()->isInstantiationDependentType()) {
5286     Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5287                                      SugaredConverted,
5288                                      SourceRange(TemplateLoc, RAngleLoc));
5289     if (Inst.isInvalid())
5290       return nullptr;
5291 
5292     // Only substitute for the innermost template argument list.
5293     MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5294                                                     /*Final=*/true);
5295     for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5296       TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5297 
5298     bool ForLambdaCallOperator = false;
5299     if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5300       ForLambdaCallOperator = Rec->isLambda();
5301     Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5302                                    !ForLambdaCallOperator);
5303     ArgType =
5304         SemaRef.SubstType(ArgType, TemplateArgLists,
5305                           Param->getDefaultArgumentLoc(), Param->getDeclName());
5306   }
5307 
5308   return ArgType;
5309 }
5310 
5311 /// Substitute template arguments into the default template argument for
5312 /// the given non-type template parameter.
5313 ///
5314 /// \param SemaRef the semantic analysis object for which we are performing
5315 /// the substitution.
5316 ///
5317 /// \param Template the template that we are synthesizing template arguments
5318 /// for.
5319 ///
5320 /// \param TemplateLoc the location of the template name that started the
5321 /// template-id we are checking.
5322 ///
5323 /// \param RAngleLoc the location of the right angle bracket ('>') that
5324 /// terminates the template-id.
5325 ///
5326 /// \param Param the non-type template parameter whose default we are
5327 /// substituting into.
5328 ///
5329 /// \param Converted the list of template arguments provided for template
5330 /// parameters that precede \p Param in the template parameter list.
5331 ///
5332 /// \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)5333 static ExprResult SubstDefaultTemplateArgument(
5334     Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5335     SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5336     ArrayRef<TemplateArgument> SugaredConverted,
5337     ArrayRef<TemplateArgument> CanonicalConverted) {
5338   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5339                                    SugaredConverted,
5340                                    SourceRange(TemplateLoc, RAngleLoc));
5341   if (Inst.isInvalid())
5342     return ExprError();
5343 
5344   // Only substitute for the innermost template argument list.
5345   MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5346                                                   /*Final=*/true);
5347   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5348     TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5349 
5350   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5351   EnterExpressionEvaluationContext ConstantEvaluated(
5352       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5353   return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
5354 }
5355 
5356 /// Substitute template arguments into the default template argument for
5357 /// the given template template parameter.
5358 ///
5359 /// \param SemaRef the semantic analysis object for which we are performing
5360 /// the substitution.
5361 ///
5362 /// \param Template the template that we are synthesizing template arguments
5363 /// for.
5364 ///
5365 /// \param TemplateLoc the location of the template name that started the
5366 /// template-id we are checking.
5367 ///
5368 /// \param RAngleLoc the location of the right angle bracket ('>') that
5369 /// terminates the template-id.
5370 ///
5371 /// \param Param the template template parameter whose default we are
5372 /// substituting into.
5373 ///
5374 /// \param Converted the list of template arguments provided for template
5375 /// parameters that precede \p Param in the template parameter list.
5376 ///
5377 /// \param QualifierLoc Will be set to the nested-name-specifier (with
5378 /// source-location information) that precedes the template name.
5379 ///
5380 /// \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)5381 static TemplateName SubstDefaultTemplateArgument(
5382     Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5383     SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
5384     ArrayRef<TemplateArgument> SugaredConverted,
5385     ArrayRef<TemplateArgument> CanonicalConverted,
5386     NestedNameSpecifierLoc &QualifierLoc) {
5387   Sema::InstantiatingTemplate Inst(
5388       SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5389       SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5390   if (Inst.isInvalid())
5391     return TemplateName();
5392 
5393   // Only substitute for the innermost template argument list.
5394   MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5395                                                   /*Final=*/true);
5396   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5397     TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5398 
5399   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5400   // Substitute into the nested-name-specifier first,
5401   QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5402   if (QualifierLoc) {
5403     QualifierLoc =
5404         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
5405     if (!QualifierLoc)
5406       return TemplateName();
5407   }
5408 
5409   return SemaRef.SubstTemplateName(
5410              QualifierLoc,
5411              Param->getDefaultArgument().getArgument().getAsTemplate(),
5412              Param->getDefaultArgument().getTemplateNameLoc(),
5413              TemplateArgLists);
5414 }
5415 
5416 /// If the given template parameter has a default template
5417 /// argument, substitute into that default template argument and
5418 /// return the corresponding template argument.
SubstDefaultTemplateArgumentIfAvailable(TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,Decl * Param,ArrayRef<TemplateArgument> SugaredConverted,ArrayRef<TemplateArgument> CanonicalConverted,bool & HasDefaultArg)5419 TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5420     TemplateDecl *Template, SourceLocation TemplateLoc,
5421     SourceLocation RAngleLoc, Decl *Param,
5422     ArrayRef<TemplateArgument> SugaredConverted,
5423     ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5424   HasDefaultArg = false;
5425 
5426   if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5427     if (!hasReachableDefaultArgument(TypeParm))
5428       return TemplateArgumentLoc();
5429 
5430     HasDefaultArg = true;
5431     TypeSourceInfo *DI = SubstDefaultTemplateArgument(
5432         *this, Template, TemplateLoc, RAngleLoc, TypeParm, SugaredConverted,
5433         CanonicalConverted);
5434     if (DI)
5435       return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
5436 
5437     return TemplateArgumentLoc();
5438   }
5439 
5440   if (NonTypeTemplateParmDecl *NonTypeParm
5441         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5442     if (!hasReachableDefaultArgument(NonTypeParm))
5443       return TemplateArgumentLoc();
5444 
5445     HasDefaultArg = true;
5446     ExprResult Arg = SubstDefaultTemplateArgument(
5447         *this, Template, TemplateLoc, RAngleLoc, NonTypeParm, SugaredConverted,
5448         CanonicalConverted);
5449     if (Arg.isInvalid())
5450       return TemplateArgumentLoc();
5451 
5452     Expr *ArgE = Arg.getAs<Expr>();
5453     return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
5454   }
5455 
5456   TemplateTemplateParmDecl *TempTempParm
5457     = cast<TemplateTemplateParmDecl>(Param);
5458   if (!hasReachableDefaultArgument(TempTempParm))
5459     return TemplateArgumentLoc();
5460 
5461   HasDefaultArg = true;
5462   NestedNameSpecifierLoc QualifierLoc;
5463   TemplateName TName = SubstDefaultTemplateArgument(
5464       *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
5465       CanonicalConverted, QualifierLoc);
5466   if (TName.isNull())
5467     return TemplateArgumentLoc();
5468 
5469   return TemplateArgumentLoc(
5470       Context, TemplateArgument(TName),
5471       TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
5472       TempTempParm->getDefaultArgument().getTemplateNameLoc());
5473 }
5474 
5475 /// Convert a template-argument that we parsed as a type into a template, if
5476 /// possible. C++ permits injected-class-names to perform dual service as
5477 /// template template arguments and as template type arguments.
5478 static TemplateArgumentLoc
convertTypeTemplateArgumentToTemplate(ASTContext & Context,TypeLoc TLoc)5479 convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5480   // Extract and step over any surrounding nested-name-specifier.
5481   NestedNameSpecifierLoc QualLoc;
5482   if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5483     if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
5484       return TemplateArgumentLoc();
5485 
5486     QualLoc = ETLoc.getQualifierLoc();
5487     TLoc = ETLoc.getNamedTypeLoc();
5488   }
5489   // If this type was written as an injected-class-name, it can be used as a
5490   // template template argument.
5491   if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5492     return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5493                                QualLoc, InjLoc.getNameLoc());
5494 
5495   // If this type was written as an injected-class-name, it may have been
5496   // converted to a RecordType during instantiation. If the RecordType is
5497   // *not* wrapped in a TemplateSpecializationType and denotes a class
5498   // template specialization, it must have come from an injected-class-name.
5499   if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5500     if (auto *CTSD =
5501             dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5502       return TemplateArgumentLoc(Context,
5503                                  TemplateName(CTSD->getSpecializedTemplate()),
5504                                  QualLoc, RecLoc.getNameLoc());
5505 
5506   return TemplateArgumentLoc();
5507 }
5508 
5509 /// Check that the given template argument corresponds to the given
5510 /// template parameter.
5511 ///
5512 /// \param Param The template parameter against which the argument will be
5513 /// checked.
5514 ///
5515 /// \param Arg The template argument, which may be updated due to conversions.
5516 ///
5517 /// \param Template The template in which the template argument resides.
5518 ///
5519 /// \param TemplateLoc The location of the template name for the template
5520 /// whose argument list we're matching.
5521 ///
5522 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
5523 /// the template argument list.
5524 ///
5525 /// \param ArgumentPackIndex The index into the argument pack where this
5526 /// argument will be placed. Only valid if the parameter is a parameter pack.
5527 ///
5528 /// \param Converted The checked, converted argument will be added to the
5529 /// end of this small vector.
5530 ///
5531 /// \param CTAK Describes how we arrived at this particular template argument:
5532 /// explicitly written, deduced, etc.
5533 ///
5534 /// \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)5535 bool Sema::CheckTemplateArgument(
5536     NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
5537     SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5538     unsigned ArgumentPackIndex,
5539     SmallVectorImpl<TemplateArgument> &SugaredConverted,
5540     SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5541     CheckTemplateArgumentKind CTAK) {
5542   // Check template type parameters.
5543   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5544     return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
5545                                      CanonicalConverted);
5546 
5547   // Check non-type template parameters.
5548   if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5549     // Do substitution on the type of the non-type template parameter
5550     // with the template arguments we've seen thus far.  But if the
5551     // template has a dependent context then we cannot substitute yet.
5552     QualType NTTPType = NTTP->getType();
5553     if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5554       NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5555 
5556     if (NTTPType->isInstantiationDependentType() &&
5557         !isa<TemplateTemplateParmDecl>(Template) &&
5558         !Template->getDeclContext()->isDependentContext()) {
5559       // Do substitution on the type of the non-type template parameter.
5560       InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5561                                  SugaredConverted,
5562                                  SourceRange(TemplateLoc, RAngleLoc));
5563       if (Inst.isInvalid())
5564         return true;
5565 
5566       MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
5567                                            /*Final=*/true);
5568       // If the parameter is a pack expansion, expand this slice of the pack.
5569       if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5570         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
5571                                                            ArgumentPackIndex);
5572         NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5573                              NTTP->getDeclName());
5574       } else {
5575         NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5576                              NTTP->getDeclName());
5577       }
5578 
5579       // If that worked, check the non-type template parameter type
5580       // for validity.
5581       if (!NTTPType.isNull())
5582         NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5583                                                      NTTP->getLocation());
5584       if (NTTPType.isNull())
5585         return true;
5586     }
5587 
5588     switch (Arg.getArgument().getKind()) {
5589     case TemplateArgument::Null:
5590       llvm_unreachable("Should never see a NULL template argument here");
5591 
5592     case TemplateArgument::Expression: {
5593       Expr *E = Arg.getArgument().getAsExpr();
5594       TemplateArgument SugaredResult, CanonicalResult;
5595       unsigned CurSFINAEErrors = NumSFINAEErrors;
5596       ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
5597                                              CanonicalResult, CTAK);
5598       if (Res.isInvalid())
5599         return true;
5600       // If the current template argument causes an error, give up now.
5601       if (CurSFINAEErrors < NumSFINAEErrors)
5602         return true;
5603 
5604       // If the resulting expression is new, then use it in place of the
5605       // old expression in the template argument.
5606       if (Res.get() != E) {
5607         TemplateArgument TA(Res.get());
5608         Arg = TemplateArgumentLoc(TA, Res.get());
5609       }
5610 
5611       SugaredConverted.push_back(SugaredResult);
5612       CanonicalConverted.push_back(CanonicalResult);
5613       break;
5614     }
5615 
5616     case TemplateArgument::Declaration:
5617     case TemplateArgument::Integral:
5618     case TemplateArgument::NullPtr:
5619       // We've already checked this template argument, so just copy
5620       // it to the list of converted arguments.
5621       SugaredConverted.push_back(Arg.getArgument());
5622       CanonicalConverted.push_back(
5623           Context.getCanonicalTemplateArgument(Arg.getArgument()));
5624       break;
5625 
5626     case TemplateArgument::Template:
5627     case TemplateArgument::TemplateExpansion:
5628       // We were given a template template argument. It may not be ill-formed;
5629       // see below.
5630       if (DependentTemplateName *DTN
5631             = Arg.getArgument().getAsTemplateOrTemplatePattern()
5632                                               .getAsDependentTemplateName()) {
5633         // We have a template argument such as \c T::template X, which we
5634         // parsed as a template template argument. However, since we now
5635         // know that we need a non-type template argument, convert this
5636         // template name into an expression.
5637 
5638         DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5639                                      Arg.getTemplateNameLoc());
5640 
5641         CXXScopeSpec SS;
5642         SS.Adopt(Arg.getTemplateQualifierLoc());
5643         // FIXME: the template-template arg was a DependentTemplateName,
5644         // so it was provided with a template keyword. However, its source
5645         // location is not stored in the template argument structure.
5646         SourceLocation TemplateKWLoc;
5647         ExprResult E = DependentScopeDeclRefExpr::Create(
5648             Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5649             nullptr);
5650 
5651         // If we parsed the template argument as a pack expansion, create a
5652         // pack expansion expression.
5653         if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
5654           E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5655           if (E.isInvalid())
5656             return true;
5657         }
5658 
5659         TemplateArgument SugaredResult, CanonicalResult;
5660         E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
5661                                   CanonicalResult, CTAK_Specified);
5662         if (E.isInvalid())
5663           return true;
5664 
5665         SugaredConverted.push_back(SugaredResult);
5666         CanonicalConverted.push_back(CanonicalResult);
5667         break;
5668       }
5669 
5670       // We have a template argument that actually does refer to a class
5671       // template, alias template, or template template parameter, and
5672       // therefore cannot be a non-type template argument.
5673       Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5674         << Arg.getSourceRange();
5675 
5676       Diag(Param->getLocation(), diag::note_template_param_here);
5677       return true;
5678 
5679     case TemplateArgument::Type: {
5680       // We have a non-type template parameter but the template
5681       // argument is a type.
5682 
5683       // C++ [temp.arg]p2:
5684       //   In a template-argument, an ambiguity between a type-id and
5685       //   an expression is resolved to a type-id, regardless of the
5686       //   form of the corresponding template-parameter.
5687       //
5688       // We warn specifically about this case, since it can be rather
5689       // confusing for users.
5690       QualType T = Arg.getArgument().getAsType();
5691       SourceRange SR = Arg.getSourceRange();
5692       if (T->isFunctionType())
5693         Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5694       else
5695         Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5696       Diag(Param->getLocation(), diag::note_template_param_here);
5697       return true;
5698     }
5699 
5700     case TemplateArgument::Pack:
5701       llvm_unreachable("Caller must expand template argument packs");
5702     }
5703 
5704     return false;
5705   }
5706 
5707 
5708   // Check template template parameters.
5709   TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5710 
5711   TemplateParameterList *Params = TempParm->getTemplateParameters();
5712   if (TempParm->isExpandedParameterPack())
5713     Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5714 
5715   // Substitute into the template parameter list of the template
5716   // template parameter, since previously-supplied template arguments
5717   // may appear within the template template parameter.
5718   //
5719   // FIXME: Skip this if the parameters aren't instantiation-dependent.
5720   {
5721     // Set up a template instantiation context.
5722     LocalInstantiationScope Scope(*this);
5723     InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5724                                SugaredConverted,
5725                                SourceRange(TemplateLoc, RAngleLoc));
5726     if (Inst.isInvalid())
5727       return true;
5728 
5729     Params =
5730         SubstTemplateParams(Params, CurContext,
5731                             MultiLevelTemplateArgumentList(
5732                                 Template, SugaredConverted, /*Final=*/true),
5733                             /*EvaluateConstraints=*/false);
5734     if (!Params)
5735       return true;
5736   }
5737 
5738   // C++1z [temp.local]p1: (DR1004)
5739   //   When [the injected-class-name] is used [...] as a template-argument for
5740   //   a template template-parameter [...] it refers to the class template
5741   //   itself.
5742   if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5743     TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5744         Context, Arg.getTypeSourceInfo()->getTypeLoc());
5745     if (!ConvertedArg.getArgument().isNull())
5746       Arg = ConvertedArg;
5747   }
5748 
5749   switch (Arg.getArgument().getKind()) {
5750   case TemplateArgument::Null:
5751     llvm_unreachable("Should never see a NULL template argument here");
5752 
5753   case TemplateArgument::Template:
5754   case TemplateArgument::TemplateExpansion:
5755     if (CheckTemplateTemplateArgument(TempParm, Params, Arg))
5756       return true;
5757 
5758     SugaredConverted.push_back(Arg.getArgument());
5759     CanonicalConverted.push_back(
5760         Context.getCanonicalTemplateArgument(Arg.getArgument()));
5761     break;
5762 
5763   case TemplateArgument::Expression:
5764   case TemplateArgument::Type:
5765     // We have a template template parameter but the template
5766     // argument does not refer to a template.
5767     Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5768       << getLangOpts().CPlusPlus11;
5769     return true;
5770 
5771   case TemplateArgument::Declaration:
5772     llvm_unreachable("Declaration argument with template template parameter");
5773   case TemplateArgument::Integral:
5774     llvm_unreachable("Integral argument with template template parameter");
5775   case TemplateArgument::NullPtr:
5776     llvm_unreachable("Null pointer argument with template template parameter");
5777 
5778   case TemplateArgument::Pack:
5779     llvm_unreachable("Caller must expand template argument packs");
5780   }
5781 
5782   return false;
5783 }
5784 
5785 /// Diagnose a missing template argument.
5786 template<typename TemplateParmDecl>
diagnoseMissingArgument(Sema & S,SourceLocation Loc,TemplateDecl * TD,const TemplateParmDecl * D,TemplateArgumentListInfo & Args)5787 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5788                                     TemplateDecl *TD,
5789                                     const TemplateParmDecl *D,
5790                                     TemplateArgumentListInfo &Args) {
5791   // Dig out the most recent declaration of the template parameter; there may be
5792   // declarations of the template that are more recent than TD.
5793   D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5794                                  ->getTemplateParameters()
5795                                  ->getParam(D->getIndex()));
5796 
5797   // If there's a default argument that's not reachable, diagnose that we're
5798   // missing a module import.
5799   llvm::SmallVector<Module*, 8> Modules;
5800   if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5801     S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5802                             D->getDefaultArgumentLoc(), Modules,
5803                             Sema::MissingImportKind::DefaultArgument,
5804                             /*Recover*/true);
5805     return true;
5806   }
5807 
5808   // FIXME: If there's a more recent default argument that *is* visible,
5809   // diagnose that it was declared too late.
5810 
5811   TemplateParameterList *Params = TD->getTemplateParameters();
5812 
5813   S.Diag(Loc, diag::err_template_arg_list_different_arity)
5814     << /*not enough args*/0
5815     << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5816     << TD;
5817   S.Diag(TD->getLocation(), diag::note_template_decl_here)
5818     << Params->getSourceRange();
5819   return true;
5820 }
5821 
5822 /// Check that the given template argument list is well-formed
5823 /// for specializing the given template.
CheckTemplateArgumentList(TemplateDecl * Template,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs,bool PartialTemplateArgs,SmallVectorImpl<TemplateArgument> & SugaredConverted,SmallVectorImpl<TemplateArgument> & CanonicalConverted,bool UpdateArgsWithConversions,bool * ConstraintsNotSatisfied)5824 bool Sema::CheckTemplateArgumentList(
5825     TemplateDecl *Template, SourceLocation TemplateLoc,
5826     TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5827     SmallVectorImpl<TemplateArgument> &SugaredConverted,
5828     SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5829     bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5830 
5831   if (ConstraintsNotSatisfied)
5832     *ConstraintsNotSatisfied = false;
5833 
5834   // Make a copy of the template arguments for processing.  Only make the
5835   // changes at the end when successful in matching the arguments to the
5836   // template.
5837   TemplateArgumentListInfo NewArgs = TemplateArgs;
5838 
5839   // Make sure we get the template parameter list from the most
5840   // recent declaration, since that is the only one that is guaranteed to
5841   // have all the default template argument information.
5842   TemplateParameterList *Params =
5843       cast<TemplateDecl>(Template->getMostRecentDecl())
5844           ->getTemplateParameters();
5845 
5846   SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5847 
5848   // C++ [temp.arg]p1:
5849   //   [...] The type and form of each template-argument specified in
5850   //   a template-id shall match the type and form specified for the
5851   //   corresponding parameter declared by the template in its
5852   //   template-parameter-list.
5853   bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5854   SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5855   SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5856   unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5857   LocalInstantiationScope InstScope(*this, true);
5858   for (TemplateParameterList::iterator Param = Params->begin(),
5859                                        ParamEnd = Params->end();
5860        Param != ParamEnd; /* increment in loop */) {
5861     // If we have an expanded parameter pack, make sure we don't have too
5862     // many arguments.
5863     if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5864       if (*Expansions == SugaredArgumentPack.size()) {
5865         // We're done with this parameter pack. Pack up its arguments and add
5866         // them to the list.
5867         SugaredConverted.push_back(
5868             TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5869         SugaredArgumentPack.clear();
5870 
5871         CanonicalConverted.push_back(
5872             TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5873         CanonicalArgumentPack.clear();
5874 
5875         // This argument is assigned to the next parameter.
5876         ++Param;
5877         continue;
5878       } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5879         // Not enough arguments for this parameter pack.
5880         Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5881           << /*not enough args*/0
5882           << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5883           << Template;
5884         Diag(Template->getLocation(), diag::note_template_decl_here)
5885           << Params->getSourceRange();
5886         return true;
5887       }
5888     }
5889 
5890     if (ArgIdx < NumArgs) {
5891       // Check the template argument we were given.
5892       if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
5893                                 RAngleLoc, SugaredArgumentPack.size(),
5894                                 SugaredConverted, CanonicalConverted,
5895                                 CTAK_Specified))
5896         return true;
5897 
5898       bool PackExpansionIntoNonPack =
5899           NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5900           (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5901       if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) ||
5902                                        isa<ConceptDecl>(Template))) {
5903         // Core issue 1430: we have a pack expansion as an argument to an
5904         // alias template, and it's not part of a parameter pack. This
5905         // can't be canonicalized, so reject it now.
5906         // As for concepts - we cannot normalize constraints where this
5907         // situation exists.
5908         Diag(NewArgs[ArgIdx].getLocation(),
5909              diag::err_template_expansion_into_fixed_list)
5910           << (isa<ConceptDecl>(Template) ? 1 : 0)
5911           << NewArgs[ArgIdx].getSourceRange();
5912         Diag((*Param)->getLocation(), diag::note_template_param_here);
5913         return true;
5914       }
5915 
5916       // We're now done with this argument.
5917       ++ArgIdx;
5918 
5919       if ((*Param)->isTemplateParameterPack()) {
5920         // The template parameter was a template parameter pack, so take the
5921         // deduced argument and place it on the argument pack. Note that we
5922         // stay on the same template parameter so that we can deduce more
5923         // arguments.
5924         SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
5925         CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
5926       } else {
5927         // Move to the next template parameter.
5928         ++Param;
5929       }
5930 
5931       // If we just saw a pack expansion into a non-pack, then directly convert
5932       // the remaining arguments, because we don't know what parameters they'll
5933       // match up with.
5934       if (PackExpansionIntoNonPack) {
5935         if (!SugaredArgumentPack.empty()) {
5936           // If we were part way through filling in an expanded parameter pack,
5937           // fall back to just producing individual arguments.
5938           SugaredConverted.insert(SugaredConverted.end(),
5939                                   SugaredArgumentPack.begin(),
5940                                   SugaredArgumentPack.end());
5941           SugaredArgumentPack.clear();
5942 
5943           CanonicalConverted.insert(CanonicalConverted.end(),
5944                                     CanonicalArgumentPack.begin(),
5945                                     CanonicalArgumentPack.end());
5946           CanonicalArgumentPack.clear();
5947         }
5948 
5949         while (ArgIdx < NumArgs) {
5950           const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5951           SugaredConverted.push_back(Arg);
5952           CanonicalConverted.push_back(
5953               Context.getCanonicalTemplateArgument(Arg));
5954           ++ArgIdx;
5955         }
5956 
5957         return false;
5958       }
5959 
5960       continue;
5961     }
5962 
5963     // If we're checking a partial template argument list, we're done.
5964     if (PartialTemplateArgs) {
5965       if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
5966         SugaredConverted.push_back(
5967             TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5968         CanonicalConverted.push_back(
5969             TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5970       }
5971       return false;
5972     }
5973 
5974     // If we have a template parameter pack with no more corresponding
5975     // arguments, just break out now and we'll fill in the argument pack below.
5976     if ((*Param)->isTemplateParameterPack()) {
5977       assert(!getExpandedPackSize(*Param) &&
5978              "Should have dealt with this already");
5979 
5980       // A non-expanded parameter pack before the end of the parameter list
5981       // only occurs for an ill-formed template parameter list, unless we've
5982       // got a partial argument list for a function template, so just bail out.
5983       if (Param + 1 != ParamEnd) {
5984         assert(
5985             (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
5986             "Concept templates must have parameter packs at the end.");
5987         return true;
5988       }
5989 
5990       SugaredConverted.push_back(
5991           TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5992       SugaredArgumentPack.clear();
5993 
5994       CanonicalConverted.push_back(
5995           TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5996       CanonicalArgumentPack.clear();
5997 
5998       ++Param;
5999       continue;
6000     }
6001 
6002     // Check whether we have a default argument.
6003     TemplateArgumentLoc Arg;
6004 
6005     // Retrieve the default template argument from the template
6006     // parameter. For each kind of template parameter, we substitute the
6007     // template arguments provided thus far and any "outer" template arguments
6008     // (when the template parameter was part of a nested template) into
6009     // the default argument.
6010     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
6011       if (!hasReachableDefaultArgument(TTP))
6012         return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6013                                        NewArgs);
6014 
6015       TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(
6016           *this, Template, TemplateLoc, RAngleLoc, TTP, SugaredConverted,
6017           CanonicalConverted);
6018       if (!ArgType)
6019         return true;
6020 
6021       Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
6022                                 ArgType);
6023     } else if (NonTypeTemplateParmDecl *NTTP
6024                  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
6025       if (!hasReachableDefaultArgument(NTTP))
6026         return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6027                                        NewArgs);
6028 
6029       ExprResult E = SubstDefaultTemplateArgument(
6030           *this, Template, TemplateLoc, RAngleLoc, NTTP, SugaredConverted,
6031           CanonicalConverted);
6032       if (E.isInvalid())
6033         return true;
6034 
6035       Expr *Ex = E.getAs<Expr>();
6036       Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
6037     } else {
6038       TemplateTemplateParmDecl *TempParm
6039         = cast<TemplateTemplateParmDecl>(*Param);
6040 
6041       if (!hasReachableDefaultArgument(TempParm))
6042         return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
6043                                        NewArgs);
6044 
6045       NestedNameSpecifierLoc QualifierLoc;
6046       TemplateName Name = SubstDefaultTemplateArgument(
6047           *this, Template, TemplateLoc, RAngleLoc, TempParm, SugaredConverted,
6048           CanonicalConverted, QualifierLoc);
6049       if (Name.isNull())
6050         return true;
6051 
6052       Arg = TemplateArgumentLoc(
6053           Context, TemplateArgument(Name), QualifierLoc,
6054           TempParm->getDefaultArgument().getTemplateNameLoc());
6055     }
6056 
6057     // Introduce an instantiation record that describes where we are using
6058     // the default template argument. We're not actually instantiating a
6059     // template here, we just create this object to put a note into the
6060     // context stack.
6061     InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6062                                SugaredConverted,
6063                                SourceRange(TemplateLoc, RAngleLoc));
6064     if (Inst.isInvalid())
6065       return true;
6066 
6067     // Check the default template argument.
6068     if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6069                               SugaredConverted, CanonicalConverted,
6070                               CTAK_Specified))
6071       return true;
6072 
6073     // Core issue 150 (assumed resolution): if this is a template template
6074     // parameter, keep track of the default template arguments from the
6075     // template definition.
6076     if (isTemplateTemplateParameter)
6077       NewArgs.addArgument(Arg);
6078 
6079     // Move to the next template parameter and argument.
6080     ++Param;
6081     ++ArgIdx;
6082   }
6083 
6084   // If we're performing a partial argument substitution, allow any trailing
6085   // pack expansions; they might be empty. This can happen even if
6086   // PartialTemplateArgs is false (the list of arguments is complete but
6087   // still dependent).
6088   if (ArgIdx < NumArgs && CurrentInstantiationScope &&
6089       CurrentInstantiationScope->getPartiallySubstitutedPack()) {
6090     while (ArgIdx < NumArgs &&
6091            NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6092       const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6093       SugaredConverted.push_back(Arg);
6094       CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
6095     }
6096   }
6097 
6098   // If we have any leftover arguments, then there were too many arguments.
6099   // Complain and fail.
6100   if (ArgIdx < NumArgs) {
6101     Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6102         << /*too many args*/1
6103         << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
6104         << Template
6105         << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6106     Diag(Template->getLocation(), diag::note_template_decl_here)
6107         << Params->getSourceRange();
6108     return true;
6109   }
6110 
6111   // No problems found with the new argument list, propagate changes back
6112   // to caller.
6113   if (UpdateArgsWithConversions)
6114     TemplateArgs = std::move(NewArgs);
6115 
6116   if (!PartialTemplateArgs) {
6117     TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
6118                                            CanonicalConverted);
6119     // Setup the context/ThisScope for the case where we are needing to
6120     // re-instantiate constraints outside of normal instantiation.
6121     DeclContext *NewContext = Template->getDeclContext();
6122 
6123     // If this template is in a template, make sure we extract the templated
6124     // decl.
6125     if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6126       NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6127     auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6128 
6129     Qualifiers ThisQuals;
6130     if (const auto *Method =
6131             dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6132       ThisQuals = Method->getMethodQualifiers();
6133 
6134     ContextRAII Context(*this, NewContext);
6135     CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
6136 
6137     MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6138         Template, /*Final=*/false, &StackTemplateArgs,
6139         /*RelativeToPrimary=*/true,
6140         /*Pattern=*/nullptr,
6141         /*ForConceptInstantiation=*/true);
6142     if (EnsureTemplateArgumentListConstraints(
6143             Template, MLTAL,
6144             SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6145       if (ConstraintsNotSatisfied)
6146         *ConstraintsNotSatisfied = true;
6147       return true;
6148     }
6149   }
6150 
6151   return false;
6152 }
6153 
6154 namespace {
6155   class UnnamedLocalNoLinkageFinder
6156     : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6157   {
6158     Sema &S;
6159     SourceRange SR;
6160 
6161     typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6162 
6163   public:
UnnamedLocalNoLinkageFinder(Sema & S,SourceRange SR)6164     UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6165 
Visit(QualType T)6166     bool Visit(QualType T) {
6167       return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6168     }
6169 
6170 #define TYPE(Class, Parent) \
6171     bool Visit##Class##Type(const Class##Type *);
6172 #define ABSTRACT_TYPE(Class, Parent) \
6173     bool Visit##Class##Type(const Class##Type *) { return false; }
6174 #define NON_CANONICAL_TYPE(Class, Parent) \
6175     bool Visit##Class##Type(const Class##Type *) { return false; }
6176 #include "clang/AST/TypeNodes.inc"
6177 
6178     bool VisitTagDecl(const TagDecl *Tag);
6179     bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
6180   };
6181 } // end anonymous namespace
6182 
VisitBuiltinType(const BuiltinType *)6183 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6184   return false;
6185 }
6186 
VisitComplexType(const ComplexType * T)6187 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6188   return Visit(T->getElementType());
6189 }
6190 
VisitPointerType(const PointerType * T)6191 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6192   return Visit(T->getPointeeType());
6193 }
6194 
VisitBlockPointerType(const BlockPointerType * T)6195 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6196                                                     const BlockPointerType* T) {
6197   return Visit(T->getPointeeType());
6198 }
6199 
VisitLValueReferenceType(const LValueReferenceType * T)6200 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6201                                                 const LValueReferenceType* T) {
6202   return Visit(T->getPointeeType());
6203 }
6204 
VisitRValueReferenceType(const RValueReferenceType * T)6205 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6206                                                 const RValueReferenceType* T) {
6207   return Visit(T->getPointeeType());
6208 }
6209 
VisitMemberPointerType(const MemberPointerType * T)6210 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6211                                                   const MemberPointerType* T) {
6212   return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
6213 }
6214 
VisitConstantArrayType(const ConstantArrayType * T)6215 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6216                                                   const ConstantArrayType* T) {
6217   return Visit(T->getElementType());
6218 }
6219 
VisitIncompleteArrayType(const IncompleteArrayType * T)6220 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6221                                                  const IncompleteArrayType* T) {
6222   return Visit(T->getElementType());
6223 }
6224 
VisitVariableArrayType(const VariableArrayType * T)6225 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6226                                                    const VariableArrayType* T) {
6227   return Visit(T->getElementType());
6228 }
6229 
VisitDependentSizedArrayType(const DependentSizedArrayType * T)6230 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6231                                             const DependentSizedArrayType* T) {
6232   return Visit(T->getElementType());
6233 }
6234 
VisitDependentSizedExtVectorType(const DependentSizedExtVectorType * T)6235 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6236                                          const DependentSizedExtVectorType* T) {
6237   return Visit(T->getElementType());
6238 }
6239 
VisitDependentSizedMatrixType(const DependentSizedMatrixType * T)6240 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6241     const DependentSizedMatrixType *T) {
6242   return Visit(T->getElementType());
6243 }
6244 
VisitDependentAddressSpaceType(const DependentAddressSpaceType * T)6245 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6246     const DependentAddressSpaceType *T) {
6247   return Visit(T->getPointeeType());
6248 }
6249 
VisitVectorType(const VectorType * T)6250 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6251   return Visit(T->getElementType());
6252 }
6253 
VisitDependentVectorType(const DependentVectorType * T)6254 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6255     const DependentVectorType *T) {
6256   return Visit(T->getElementType());
6257 }
6258 
VisitExtVectorType(const ExtVectorType * T)6259 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6260   return Visit(T->getElementType());
6261 }
6262 
VisitConstantMatrixType(const ConstantMatrixType * T)6263 bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6264     const ConstantMatrixType *T) {
6265   return Visit(T->getElementType());
6266 }
6267 
VisitFunctionProtoType(const FunctionProtoType * T)6268 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6269                                                   const FunctionProtoType* T) {
6270   for (const auto &A : T->param_types()) {
6271     if (Visit(A))
6272       return true;
6273   }
6274 
6275   return Visit(T->getReturnType());
6276 }
6277 
VisitFunctionNoProtoType(const FunctionNoProtoType * T)6278 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6279                                                const FunctionNoProtoType* T) {
6280   return Visit(T->getReturnType());
6281 }
6282 
VisitUnresolvedUsingType(const UnresolvedUsingType *)6283 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6284                                                   const UnresolvedUsingType*) {
6285   return false;
6286 }
6287 
VisitTypeOfExprType(const TypeOfExprType *)6288 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6289   return false;
6290 }
6291 
VisitTypeOfType(const TypeOfType * T)6292 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6293   return Visit(T->getUnmodifiedType());
6294 }
6295 
VisitDecltypeType(const DecltypeType *)6296 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6297   return false;
6298 }
6299 
VisitUnaryTransformType(const UnaryTransformType *)6300 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6301                                                     const UnaryTransformType*) {
6302   return false;
6303 }
6304 
VisitAutoType(const AutoType * T)6305 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6306   return Visit(T->getDeducedType());
6307 }
6308 
VisitDeducedTemplateSpecializationType(const DeducedTemplateSpecializationType * T)6309 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6310     const DeducedTemplateSpecializationType *T) {
6311   return Visit(T->getDeducedType());
6312 }
6313 
VisitRecordType(const RecordType * T)6314 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6315   return VisitTagDecl(T->getDecl());
6316 }
6317 
VisitEnumType(const EnumType * T)6318 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6319   return VisitTagDecl(T->getDecl());
6320 }
6321 
VisitTemplateTypeParmType(const TemplateTypeParmType *)6322 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6323                                                  const TemplateTypeParmType*) {
6324   return false;
6325 }
6326 
VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *)6327 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6328                                         const SubstTemplateTypeParmPackType *) {
6329   return false;
6330 }
6331 
VisitTemplateSpecializationType(const TemplateSpecializationType *)6332 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6333                                             const TemplateSpecializationType*) {
6334   return false;
6335 }
6336 
VisitInjectedClassNameType(const InjectedClassNameType * T)6337 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6338                                               const InjectedClassNameType* T) {
6339   return VisitTagDecl(T->getDecl());
6340 }
6341 
VisitDependentNameType(const DependentNameType * T)6342 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6343                                                    const DependentNameType* T) {
6344   return VisitNestedNameSpecifier(T->getQualifier());
6345 }
6346 
VisitDependentTemplateSpecializationType(const DependentTemplateSpecializationType * T)6347 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6348                                  const DependentTemplateSpecializationType* T) {
6349   if (auto *Q = T->getQualifier())
6350     return VisitNestedNameSpecifier(Q);
6351   return false;
6352 }
6353 
VisitPackExpansionType(const PackExpansionType * T)6354 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6355                                                    const PackExpansionType* T) {
6356   return Visit(T->getPattern());
6357 }
6358 
VisitObjCObjectType(const ObjCObjectType *)6359 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6360   return false;
6361 }
6362 
VisitObjCInterfaceType(const ObjCInterfaceType *)6363 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6364                                                    const ObjCInterfaceType *) {
6365   return false;
6366 }
6367 
VisitObjCObjectPointerType(const ObjCObjectPointerType *)6368 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6369                                                 const ObjCObjectPointerType *) {
6370   return false;
6371 }
6372 
VisitAtomicType(const AtomicType * T)6373 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6374   return Visit(T->getValueType());
6375 }
6376 
VisitPipeType(const PipeType * T)6377 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6378   return false;
6379 }
6380 
VisitBitIntType(const BitIntType * T)6381 bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6382   return false;
6383 }
6384 
VisitDependentBitIntType(const DependentBitIntType * T)6385 bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6386     const DependentBitIntType *T) {
6387   return false;
6388 }
6389 
VisitTagDecl(const TagDecl * Tag)6390 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6391   if (Tag->getDeclContext()->isFunctionOrMethod()) {
6392     S.Diag(SR.getBegin(),
6393            S.getLangOpts().CPlusPlus11 ?
6394              diag::warn_cxx98_compat_template_arg_local_type :
6395              diag::ext_template_arg_local_type)
6396       << S.Context.getTypeDeclType(Tag) << SR;
6397     return true;
6398   }
6399 
6400   if (!Tag->hasNameForLinkage()) {
6401     S.Diag(SR.getBegin(),
6402            S.getLangOpts().CPlusPlus11 ?
6403              diag::warn_cxx98_compat_template_arg_unnamed_type :
6404              diag::ext_template_arg_unnamed_type) << SR;
6405     S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6406     return true;
6407   }
6408 
6409   return false;
6410 }
6411 
VisitNestedNameSpecifier(NestedNameSpecifier * NNS)6412 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6413                                                     NestedNameSpecifier *NNS) {
6414   assert(NNS);
6415   if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
6416     return true;
6417 
6418   switch (NNS->getKind()) {
6419   case NestedNameSpecifier::Identifier:
6420   case NestedNameSpecifier::Namespace:
6421   case NestedNameSpecifier::NamespaceAlias:
6422   case NestedNameSpecifier::Global:
6423   case NestedNameSpecifier::Super:
6424     return false;
6425 
6426   case NestedNameSpecifier::TypeSpec:
6427   case NestedNameSpecifier::TypeSpecWithTemplate:
6428     return Visit(QualType(NNS->getAsType(), 0));
6429   }
6430   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6431 }
6432 
6433 /// Check a template argument against its corresponding
6434 /// template type parameter.
6435 ///
6436 /// This routine implements the semantics of C++ [temp.arg.type]. It
6437 /// returns true if an error occurred, and false otherwise.
CheckTemplateArgument(TypeSourceInfo * ArgInfo)6438 bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6439   assert(ArgInfo && "invalid TypeSourceInfo");
6440   QualType Arg = ArgInfo->getType();
6441   SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6442   QualType CanonArg = Context.getCanonicalType(Arg);
6443 
6444   if (CanonArg->isVariablyModifiedType()) {
6445     return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6446   } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6447     return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6448   }
6449 
6450   // C++03 [temp.arg.type]p2:
6451   //   A local type, a type with no linkage, an unnamed type or a type
6452   //   compounded from any of these types shall not be used as a
6453   //   template-argument for a template type-parameter.
6454   //
6455   // C++11 allows these, and even in C++03 we allow them as an extension with
6456   // a warning.
6457   if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6458     UnnamedLocalNoLinkageFinder Finder(*this, SR);
6459     (void)Finder.Visit(CanonArg);
6460   }
6461 
6462   return false;
6463 }
6464 
6465 enum NullPointerValueKind {
6466   NPV_NotNullPointer,
6467   NPV_NullPointer,
6468   NPV_Error
6469 };
6470 
6471 /// Determine whether the given template argument is a null pointer
6472 /// value of the appropriate type.
6473 static NullPointerValueKind
isNullPointerValueTemplateArgument(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * Arg,Decl * Entity=nullptr)6474 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
6475                                    QualType ParamType, Expr *Arg,
6476                                    Decl *Entity = nullptr) {
6477   if (Arg->isValueDependent() || Arg->isTypeDependent())
6478     return NPV_NotNullPointer;
6479 
6480   // dllimport'd entities aren't constant but are available inside of template
6481   // arguments.
6482   if (Entity && Entity->hasAttr<DLLImportAttr>())
6483     return NPV_NotNullPointer;
6484 
6485   if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6486     llvm_unreachable(
6487         "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6488 
6489   if (!S.getLangOpts().CPlusPlus11)
6490     return NPV_NotNullPointer;
6491 
6492   // Determine whether we have a constant expression.
6493   ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
6494   if (ArgRV.isInvalid())
6495     return NPV_Error;
6496   Arg = ArgRV.get();
6497 
6498   Expr::EvalResult EvalResult;
6499   SmallVector<PartialDiagnosticAt, 8> Notes;
6500   EvalResult.Diag = &Notes;
6501   if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6502       EvalResult.HasSideEffects) {
6503     SourceLocation DiagLoc = Arg->getExprLoc();
6504 
6505     // If our only note is the usual "invalid subexpression" note, just point
6506     // the caret at its location rather than producing an essentially
6507     // redundant note.
6508     if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6509         diag::note_invalid_subexpr_in_const_expr) {
6510       DiagLoc = Notes[0].first;
6511       Notes.clear();
6512     }
6513 
6514     S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6515       << Arg->getType() << Arg->getSourceRange();
6516     for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6517       S.Diag(Notes[I].first, Notes[I].second);
6518 
6519     S.Diag(Param->getLocation(), diag::note_template_param_here);
6520     return NPV_Error;
6521   }
6522 
6523   // C++11 [temp.arg.nontype]p1:
6524   //   - an address constant expression of type std::nullptr_t
6525   if (Arg->getType()->isNullPtrType())
6526     return NPV_NullPointer;
6527 
6528   //   - a constant expression that evaluates to a null pointer value (4.10); or
6529   //   - a constant expression that evaluates to a null member pointer value
6530   //     (4.11); or
6531   if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6532       (EvalResult.Val.isMemberPointer() &&
6533        !EvalResult.Val.getMemberPointerDecl())) {
6534     // If our expression has an appropriate type, we've succeeded.
6535     bool ObjCLifetimeConversion;
6536     if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6537         S.IsQualificationConversion(Arg->getType(), ParamType, false,
6538                                      ObjCLifetimeConversion))
6539       return NPV_NullPointer;
6540 
6541     // The types didn't match, but we know we got a null pointer; complain,
6542     // then recover as if the types were correct.
6543     S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6544       << Arg->getType() << ParamType << Arg->getSourceRange();
6545     S.Diag(Param->getLocation(), diag::note_template_param_here);
6546     return NPV_NullPointer;
6547   }
6548 
6549   if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6550     // We found a pointer that isn't null, but doesn't refer to an object.
6551     // We could just return NPV_NotNullPointer, but we can print a better
6552     // message with the information we have here.
6553     S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6554       << EvalResult.Val.getAsString(S.Context, ParamType);
6555     S.Diag(Param->getLocation(), diag::note_template_param_here);
6556     return NPV_Error;
6557   }
6558 
6559   // If we don't have a null pointer value, but we do have a NULL pointer
6560   // constant, suggest a cast to the appropriate type.
6561   if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
6562     std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6563     S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6564         << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6565         << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
6566                                       ")");
6567     S.Diag(Param->getLocation(), diag::note_template_param_here);
6568     return NPV_NullPointer;
6569   }
6570 
6571   // FIXME: If we ever want to support general, address-constant expressions
6572   // as non-type template arguments, we should return the ExprResult here to
6573   // be interpreted by the caller.
6574   return NPV_NotNullPointer;
6575 }
6576 
6577 /// Checks whether the given template argument is compatible with its
6578 /// template parameter.
CheckTemplateArgumentIsCompatibleWithParameter(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * ArgIn,Expr * Arg,QualType ArgType)6579 static bool CheckTemplateArgumentIsCompatibleWithParameter(
6580     Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6581     Expr *Arg, QualType ArgType) {
6582   bool ObjCLifetimeConversion;
6583   if (ParamType->isPointerType() &&
6584       !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6585       S.IsQualificationConversion(ArgType, ParamType, false,
6586                                   ObjCLifetimeConversion)) {
6587     // For pointer-to-object types, qualification conversions are
6588     // permitted.
6589   } else {
6590     if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6591       if (!ParamRef->getPointeeType()->isFunctionType()) {
6592         // C++ [temp.arg.nontype]p5b3:
6593         //   For a non-type template-parameter of type reference to
6594         //   object, no conversions apply. The type referred to by the
6595         //   reference may be more cv-qualified than the (otherwise
6596         //   identical) type of the template- argument. The
6597         //   template-parameter is bound directly to the
6598         //   template-argument, which shall be an lvalue.
6599 
6600         // FIXME: Other qualifiers?
6601         unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6602         unsigned ArgQuals = ArgType.getCVRQualifiers();
6603 
6604         if ((ParamQuals | ArgQuals) != ParamQuals) {
6605           S.Diag(Arg->getBeginLoc(),
6606                  diag::err_template_arg_ref_bind_ignores_quals)
6607               << ParamType << Arg->getType() << Arg->getSourceRange();
6608           S.Diag(Param->getLocation(), diag::note_template_param_here);
6609           return true;
6610         }
6611       }
6612     }
6613 
6614     // At this point, the template argument refers to an object or
6615     // function with external linkage. We now need to check whether the
6616     // argument and parameter types are compatible.
6617     if (!S.Context.hasSameUnqualifiedType(ArgType,
6618                                           ParamType.getNonReferenceType())) {
6619       // We can't perform this conversion or binding.
6620       if (ParamType->isReferenceType())
6621         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6622             << ParamType << ArgIn->getType() << Arg->getSourceRange();
6623       else
6624         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6625             << ArgIn->getType() << ParamType << Arg->getSourceRange();
6626       S.Diag(Param->getLocation(), diag::note_template_param_here);
6627       return true;
6628     }
6629   }
6630 
6631   return false;
6632 }
6633 
6634 /// Checks whether the given template argument is the address
6635 /// 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)6636 static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6637     Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6638     TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6639   bool Invalid = false;
6640   Expr *Arg = ArgIn;
6641   QualType ArgType = Arg->getType();
6642 
6643   bool AddressTaken = false;
6644   SourceLocation AddrOpLoc;
6645   if (S.getLangOpts().MicrosoftExt) {
6646     // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6647     // dereference and address-of operators.
6648     Arg = Arg->IgnoreParenCasts();
6649 
6650     bool ExtWarnMSTemplateArg = false;
6651     UnaryOperatorKind FirstOpKind;
6652     SourceLocation FirstOpLoc;
6653     while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6654       UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6655       if (UnOpKind == UO_Deref)
6656         ExtWarnMSTemplateArg = true;
6657       if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6658         Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6659         if (!AddrOpLoc.isValid()) {
6660           FirstOpKind = UnOpKind;
6661           FirstOpLoc = UnOp->getOperatorLoc();
6662         }
6663       } else
6664         break;
6665     }
6666     if (FirstOpLoc.isValid()) {
6667       if (ExtWarnMSTemplateArg)
6668         S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6669             << ArgIn->getSourceRange();
6670 
6671       if (FirstOpKind == UO_AddrOf)
6672         AddressTaken = true;
6673       else if (Arg->getType()->isPointerType()) {
6674         // We cannot let pointers get dereferenced here, that is obviously not a
6675         // constant expression.
6676         assert(FirstOpKind == UO_Deref);
6677         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6678             << Arg->getSourceRange();
6679       }
6680     }
6681   } else {
6682     // See through any implicit casts we added to fix the type.
6683     Arg = Arg->IgnoreImpCasts();
6684 
6685     // C++ [temp.arg.nontype]p1:
6686     //
6687     //   A template-argument for a non-type, non-template
6688     //   template-parameter shall be one of: [...]
6689     //
6690     //     -- the address of an object or function with external
6691     //        linkage, including function templates and function
6692     //        template-ids but excluding non-static class members,
6693     //        expressed as & id-expression where the & is optional if
6694     //        the name refers to a function or array, or if the
6695     //        corresponding template-parameter is a reference; or
6696 
6697     // In C++98/03 mode, give an extension warning on any extra parentheses.
6698     // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6699     bool ExtraParens = false;
6700     while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6701       if (!Invalid && !ExtraParens) {
6702         S.Diag(Arg->getBeginLoc(),
6703                S.getLangOpts().CPlusPlus11
6704                    ? diag::warn_cxx98_compat_template_arg_extra_parens
6705                    : diag::ext_template_arg_extra_parens)
6706             << Arg->getSourceRange();
6707         ExtraParens = true;
6708       }
6709 
6710       Arg = Parens->getSubExpr();
6711     }
6712 
6713     while (SubstNonTypeTemplateParmExpr *subst =
6714                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6715       Arg = subst->getReplacement()->IgnoreImpCasts();
6716 
6717     if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6718       if (UnOp->getOpcode() == UO_AddrOf) {
6719         Arg = UnOp->getSubExpr();
6720         AddressTaken = true;
6721         AddrOpLoc = UnOp->getOperatorLoc();
6722       }
6723     }
6724 
6725     while (SubstNonTypeTemplateParmExpr *subst =
6726                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6727       Arg = subst->getReplacement()->IgnoreImpCasts();
6728   }
6729 
6730   ValueDecl *Entity = nullptr;
6731   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6732     Entity = DRE->getDecl();
6733   else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6734     Entity = CUE->getGuidDecl();
6735 
6736   // If our parameter has pointer type, check for a null template value.
6737   if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6738     switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6739                                                Entity)) {
6740     case NPV_NullPointer:
6741       S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6742       SugaredConverted = TemplateArgument(ParamType,
6743                                           /*isNullPtr=*/true);
6744       CanonicalConverted =
6745           TemplateArgument(S.Context.getCanonicalType(ParamType),
6746                            /*isNullPtr=*/true);
6747       return false;
6748 
6749     case NPV_Error:
6750       return true;
6751 
6752     case NPV_NotNullPointer:
6753       break;
6754     }
6755   }
6756 
6757   // Stop checking the precise nature of the argument if it is value dependent,
6758   // it should be checked when instantiated.
6759   if (Arg->isValueDependent()) {
6760     SugaredConverted = TemplateArgument(ArgIn);
6761     CanonicalConverted =
6762         S.Context.getCanonicalTemplateArgument(SugaredConverted);
6763     return false;
6764   }
6765 
6766   if (!Entity) {
6767     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6768         << Arg->getSourceRange();
6769     S.Diag(Param->getLocation(), diag::note_template_param_here);
6770     return true;
6771   }
6772 
6773   // Cannot refer to non-static data members
6774   if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6775     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6776         << Entity << Arg->getSourceRange();
6777     S.Diag(Param->getLocation(), diag::note_template_param_here);
6778     return true;
6779   }
6780 
6781   // Cannot refer to non-static member functions
6782   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6783     if (!Method->isStatic()) {
6784       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6785           << Method << Arg->getSourceRange();
6786       S.Diag(Param->getLocation(), diag::note_template_param_here);
6787       return true;
6788     }
6789   }
6790 
6791   FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6792   VarDecl *Var = dyn_cast<VarDecl>(Entity);
6793   MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6794 
6795   // A non-type template argument must refer to an object or function.
6796   if (!Func && !Var && !Guid) {
6797     // We found something, but we don't know specifically what it is.
6798     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6799         << Arg->getSourceRange();
6800     S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6801     return true;
6802   }
6803 
6804   // Address / reference template args must have external linkage in C++98.
6805   if (Entity->getFormalLinkage() == InternalLinkage) {
6806     S.Diag(Arg->getBeginLoc(),
6807            S.getLangOpts().CPlusPlus11
6808                ? diag::warn_cxx98_compat_template_arg_object_internal
6809                : diag::ext_template_arg_object_internal)
6810         << !Func << Entity << Arg->getSourceRange();
6811     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6812       << !Func;
6813   } else if (!Entity->hasLinkage()) {
6814     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6815         << !Func << Entity << Arg->getSourceRange();
6816     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6817       << !Func;
6818     return true;
6819   }
6820 
6821   if (Var) {
6822     // A value of reference type is not an object.
6823     if (Var->getType()->isReferenceType()) {
6824       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6825           << Var->getType() << Arg->getSourceRange();
6826       S.Diag(Param->getLocation(), diag::note_template_param_here);
6827       return true;
6828     }
6829 
6830     // A template argument must have static storage duration.
6831     if (Var->getTLSKind()) {
6832       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6833           << Arg->getSourceRange();
6834       S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6835       return true;
6836     }
6837   }
6838 
6839   if (AddressTaken && ParamType->isReferenceType()) {
6840     // If we originally had an address-of operator, but the
6841     // parameter has reference type, complain and (if things look
6842     // like they will work) drop the address-of operator.
6843     if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6844                                           ParamType.getNonReferenceType())) {
6845       S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6846         << ParamType;
6847       S.Diag(Param->getLocation(), diag::note_template_param_here);
6848       return true;
6849     }
6850 
6851     S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6852       << ParamType
6853       << FixItHint::CreateRemoval(AddrOpLoc);
6854     S.Diag(Param->getLocation(), diag::note_template_param_here);
6855 
6856     ArgType = Entity->getType();
6857   }
6858 
6859   // If the template parameter has pointer type, either we must have taken the
6860   // address or the argument must decay to a pointer.
6861   if (!AddressTaken && ParamType->isPointerType()) {
6862     if (Func) {
6863       // Function-to-pointer decay.
6864       ArgType = S.Context.getPointerType(Func->getType());
6865     } else if (Entity->getType()->isArrayType()) {
6866       // Array-to-pointer decay.
6867       ArgType = S.Context.getArrayDecayedType(Entity->getType());
6868     } else {
6869       // If the template parameter has pointer type but the address of
6870       // this object was not taken, complain and (possibly) recover by
6871       // taking the address of the entity.
6872       ArgType = S.Context.getPointerType(Entity->getType());
6873       if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6874         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6875           << ParamType;
6876         S.Diag(Param->getLocation(), diag::note_template_param_here);
6877         return true;
6878       }
6879 
6880       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6881         << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6882 
6883       S.Diag(Param->getLocation(), diag::note_template_param_here);
6884     }
6885   }
6886 
6887   if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6888                                                      Arg, ArgType))
6889     return true;
6890 
6891   // Create the template argument.
6892   SugaredConverted = TemplateArgument(Entity, ParamType);
6893   CanonicalConverted =
6894       TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
6895                        S.Context.getCanonicalType(ParamType));
6896   S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6897   return false;
6898 }
6899 
6900 /// Checks whether the given template argument is a pointer to
6901 /// member constant according to C++ [temp.arg.nontype]p1.
6902 static bool
CheckTemplateArgumentPointerToMember(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * & ResultArg,TemplateArgument & SugaredConverted,TemplateArgument & CanonicalConverted)6903 CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param,
6904                                      QualType ParamType, Expr *&ResultArg,
6905                                      TemplateArgument &SugaredConverted,
6906                                      TemplateArgument &CanonicalConverted) {
6907   bool Invalid = false;
6908 
6909   Expr *Arg = ResultArg;
6910   bool ObjCLifetimeConversion;
6911 
6912   // C++ [temp.arg.nontype]p1:
6913   //
6914   //   A template-argument for a non-type, non-template
6915   //   template-parameter shall be one of: [...]
6916   //
6917   //     -- a pointer to member expressed as described in 5.3.1.
6918   DeclRefExpr *DRE = nullptr;
6919 
6920   // In C++98/03 mode, give an extension warning on any extra parentheses.
6921   // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6922   bool ExtraParens = false;
6923   while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6924     if (!Invalid && !ExtraParens) {
6925       S.Diag(Arg->getBeginLoc(),
6926              S.getLangOpts().CPlusPlus11
6927                  ? diag::warn_cxx98_compat_template_arg_extra_parens
6928                  : diag::ext_template_arg_extra_parens)
6929           << Arg->getSourceRange();
6930       ExtraParens = true;
6931     }
6932 
6933     Arg = Parens->getSubExpr();
6934   }
6935 
6936   while (SubstNonTypeTemplateParmExpr *subst =
6937            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6938     Arg = subst->getReplacement()->IgnoreImpCasts();
6939 
6940   // A pointer-to-member constant written &Class::member.
6941   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6942     if (UnOp->getOpcode() == UO_AddrOf) {
6943       DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6944       if (DRE && !DRE->getQualifier())
6945         DRE = nullptr;
6946     }
6947   }
6948   // A constant of pointer-to-member type.
6949   else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6950     ValueDecl *VD = DRE->getDecl();
6951     if (VD->getType()->isMemberPointerType()) {
6952       if (isa<NonTypeTemplateParmDecl>(VD)) {
6953         if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6954           SugaredConverted = TemplateArgument(Arg);
6955           CanonicalConverted =
6956               S.Context.getCanonicalTemplateArgument(SugaredConverted);
6957         } else {
6958           SugaredConverted = TemplateArgument(VD, ParamType);
6959           CanonicalConverted =
6960               TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
6961                                S.Context.getCanonicalType(ParamType));
6962         }
6963         return Invalid;
6964       }
6965     }
6966 
6967     DRE = nullptr;
6968   }
6969 
6970   ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6971 
6972   // Check for a null pointer value.
6973   switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6974                                              Entity)) {
6975   case NPV_Error:
6976     return true;
6977   case NPV_NullPointer:
6978     S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6979     SugaredConverted = TemplateArgument(ParamType,
6980                                         /*isNullPtr*/ true);
6981     CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6982                                           /*isNullPtr*/ true);
6983     return false;
6984   case NPV_NotNullPointer:
6985     break;
6986   }
6987 
6988   if (S.IsQualificationConversion(ResultArg->getType(),
6989                                   ParamType.getNonReferenceType(), false,
6990                                   ObjCLifetimeConversion)) {
6991     ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6992                                     ResultArg->getValueKind())
6993                     .get();
6994   } else if (!S.Context.hasSameUnqualifiedType(
6995                  ResultArg->getType(), ParamType.getNonReferenceType())) {
6996     // We can't perform this conversion.
6997     S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6998         << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6999     S.Diag(Param->getLocation(), diag::note_template_param_here);
7000     return true;
7001   }
7002 
7003   if (!DRE)
7004     return S.Diag(Arg->getBeginLoc(),
7005                   diag::err_template_arg_not_pointer_to_member_form)
7006            << Arg->getSourceRange();
7007 
7008   if (isa<FieldDecl>(DRE->getDecl()) ||
7009       isa<IndirectFieldDecl>(DRE->getDecl()) ||
7010       isa<CXXMethodDecl>(DRE->getDecl())) {
7011     assert((isa<FieldDecl>(DRE->getDecl()) ||
7012             isa<IndirectFieldDecl>(DRE->getDecl()) ||
7013             !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
7014            "Only non-static member pointers can make it here");
7015 
7016     // Okay: this is the address of a non-static member, and therefore
7017     // a member pointer constant.
7018     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7019       SugaredConverted = TemplateArgument(Arg);
7020       CanonicalConverted =
7021           S.Context.getCanonicalTemplateArgument(SugaredConverted);
7022     } else {
7023       ValueDecl *D = DRE->getDecl();
7024       SugaredConverted = TemplateArgument(D, ParamType);
7025       CanonicalConverted =
7026           TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
7027                            S.Context.getCanonicalType(ParamType));
7028     }
7029     return Invalid;
7030   }
7031 
7032   // We found something else, but we don't know specifically what it is.
7033   S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7034       << Arg->getSourceRange();
7035   S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7036   return true;
7037 }
7038 
7039 /// Check a template argument against its corresponding
7040 /// non-type template parameter.
7041 ///
7042 /// This routine implements the semantics of C++ [temp.arg.nontype].
7043 /// If an error occurred, it returns ExprError(); otherwise, it
7044 /// returns the converted template argument. \p ParamType is the
7045 /// 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)7046 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
7047                                        QualType ParamType, Expr *Arg,
7048                                        TemplateArgument &SugaredConverted,
7049                                        TemplateArgument &CanonicalConverted,
7050                                        CheckTemplateArgumentKind CTAK) {
7051   SourceLocation StartLoc = Arg->getBeginLoc();
7052 
7053   // If the parameter type somehow involves auto, deduce the type now.
7054   DeducedType *DeducedT = ParamType->getContainedDeducedType();
7055   if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
7056     // During template argument deduction, we allow 'decltype(auto)' to
7057     // match an arbitrary dependent argument.
7058     // FIXME: The language rules don't say what happens in this case.
7059     // FIXME: We get an opaque dependent type out of decltype(auto) if the
7060     // expression is merely instantiation-dependent; is this enough?
7061     if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
7062       auto *AT = dyn_cast<AutoType>(DeducedT);
7063       if (AT && AT->isDecltypeAuto()) {
7064         SugaredConverted = TemplateArgument(Arg);
7065         CanonicalConverted = TemplateArgument(
7066             Context.getCanonicalTemplateArgument(SugaredConverted));
7067         return Arg;
7068       }
7069     }
7070 
7071     // When checking a deduced template argument, deduce from its type even if
7072     // the type is dependent, in order to check the types of non-type template
7073     // arguments line up properly in partial ordering.
7074     Expr *DeductionArg = Arg;
7075     if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
7076       DeductionArg = PE->getPattern();
7077     TypeSourceInfo *TSI =
7078         Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7079     if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
7080       InitializedEntity Entity =
7081           InitializedEntity::InitializeTemplateParameter(ParamType, Param);
7082       InitializationKind Kind = InitializationKind::CreateForInit(
7083           DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7084       Expr *Inits[1] = {DeductionArg};
7085       ParamType =
7086           DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
7087       if (ParamType.isNull())
7088         return ExprError();
7089     } else {
7090       TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7091                                  Param->getDepth() + 1);
7092       ParamType = QualType();
7093       TemplateDeductionResult Result =
7094           DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7095                          /*DependentDeduction=*/true,
7096                          // We do not check constraints right now because the
7097                          // immediately-declared constraint of the auto type is
7098                          // also an associated constraint, and will be checked
7099                          // along with the other associated constraints after
7100                          // checking the template argument list.
7101                          /*IgnoreConstraints=*/true);
7102       if (Result == TDK_AlreadyDiagnosed) {
7103         if (ParamType.isNull())
7104           return ExprError();
7105       } else if (Result != TDK_Success) {
7106         Diag(Arg->getExprLoc(),
7107              diag::err_non_type_template_parm_type_deduction_failure)
7108             << Param->getDeclName() << Param->getType() << Arg->getType()
7109             << Arg->getSourceRange();
7110         Diag(Param->getLocation(), diag::note_template_param_here);
7111         return ExprError();
7112       }
7113     }
7114     // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7115     // an error. The error message normally references the parameter
7116     // declaration, but here we'll pass the argument location because that's
7117     // where the parameter type is deduced.
7118     ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7119     if (ParamType.isNull()) {
7120       Diag(Param->getLocation(), diag::note_template_param_here);
7121       return ExprError();
7122     }
7123   }
7124 
7125   // We should have already dropped all cv-qualifiers by now.
7126   assert(!ParamType.hasQualifiers() &&
7127          "non-type template parameter type cannot be qualified");
7128 
7129   // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7130   if (CTAK == CTAK_Deduced &&
7131       (ParamType->isReferenceType()
7132            ? !Context.hasSameType(ParamType.getNonReferenceType(),
7133                                   Arg->getType())
7134            : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
7135     // FIXME: If either type is dependent, we skip the check. This isn't
7136     // correct, since during deduction we're supposed to have replaced each
7137     // template parameter with some unique (non-dependent) placeholder.
7138     // FIXME: If the argument type contains 'auto', we carry on and fail the
7139     // type check in order to force specific types to be more specialized than
7140     // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
7141     // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
7142     if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
7143         !Arg->getType()->getContainedDeducedType()) {
7144       SugaredConverted = TemplateArgument(Arg);
7145       CanonicalConverted = TemplateArgument(
7146           Context.getCanonicalTemplateArgument(SugaredConverted));
7147       return Arg;
7148     }
7149     // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7150     // we should actually be checking the type of the template argument in P,
7151     // not the type of the template argument deduced from A, against the
7152     // template parameter type.
7153     Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7154       << Arg->getType()
7155       << ParamType.getUnqualifiedType();
7156     Diag(Param->getLocation(), diag::note_template_param_here);
7157     return ExprError();
7158   }
7159 
7160   // If either the parameter has a dependent type or the argument is
7161   // type-dependent, there's nothing we can check now.
7162   if (ParamType->isDependentType() || Arg->isTypeDependent()) {
7163     // Force the argument to the type of the parameter to maintain invariants.
7164     auto *PE = dyn_cast<PackExpansionExpr>(Arg);
7165     if (PE)
7166       Arg = PE->getPattern();
7167     ExprResult E = ImpCastExprToType(
7168         Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7169         ParamType->isLValueReferenceType()   ? VK_LValue
7170         : ParamType->isRValueReferenceType() ? VK_XValue
7171                                              : VK_PRValue);
7172     if (E.isInvalid())
7173       return ExprError();
7174     if (PE) {
7175       // Recreate a pack expansion if we unwrapped one.
7176       E = new (Context)
7177           PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
7178                             PE->getNumExpansions());
7179     }
7180     SugaredConverted = TemplateArgument(E.get());
7181     CanonicalConverted = TemplateArgument(
7182         Context.getCanonicalTemplateArgument(SugaredConverted));
7183     return E;
7184   }
7185 
7186   // The initialization of the parameter from the argument is
7187   // a constant-evaluated context.
7188   EnterExpressionEvaluationContext ConstantEvaluated(
7189       *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7190 
7191   if (getLangOpts().CPlusPlus17) {
7192     QualType CanonParamType = Context.getCanonicalType(ParamType);
7193 
7194     // Avoid making a copy when initializing a template parameter of class type
7195     // from a template parameter object of the same type. This is going beyond
7196     // the standard, but is required for soundness: in
7197     //   template<A a> struct X { X *p; X<a> *q; };
7198     // ... we need p and q to have the same type.
7199     //
7200     // Similarly, don't inject a call to a copy constructor when initializing
7201     // from a template parameter of the same type.
7202     Expr *InnerArg = Arg->IgnoreParenImpCasts();
7203     if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7204         Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7205       NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7206       if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7207 
7208         SugaredConverted = TemplateArgument(TPO, ParamType);
7209         CanonicalConverted =
7210             TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
7211         return Arg;
7212       }
7213       if (isa<NonTypeTemplateParmDecl>(ND)) {
7214         SugaredConverted = TemplateArgument(Arg);
7215         CanonicalConverted =
7216             Context.getCanonicalTemplateArgument(SugaredConverted);
7217         return Arg;
7218       }
7219     }
7220 
7221     // C++17 [temp.arg.nontype]p1:
7222     //   A template-argument for a non-type template parameter shall be
7223     //   a converted constant expression of the type of the template-parameter.
7224     APValue Value;
7225     ExprResult ArgResult = CheckConvertedConstantExpression(
7226         Arg, ParamType, Value, CCEK_TemplateArg, Param);
7227     if (ArgResult.isInvalid())
7228       return ExprError();
7229 
7230     // For a value-dependent argument, CheckConvertedConstantExpression is
7231     // permitted (and expected) to be unable to determine a value.
7232     if (ArgResult.get()->isValueDependent()) {
7233       SugaredConverted = TemplateArgument(ArgResult.get());
7234       CanonicalConverted =
7235           Context.getCanonicalTemplateArgument(SugaredConverted);
7236       return ArgResult;
7237     }
7238 
7239     // Convert the APValue to a TemplateArgument.
7240     switch (Value.getKind()) {
7241     case APValue::None:
7242       assert(ParamType->isNullPtrType());
7243       SugaredConverted = TemplateArgument(ParamType, /*isNullPtr=*/true);
7244       CanonicalConverted = TemplateArgument(CanonParamType, /*isNullPtr=*/true);
7245       break;
7246     case APValue::Indeterminate:
7247       llvm_unreachable("result of constant evaluation should be initialized");
7248       break;
7249     case APValue::Int:
7250       assert(ParamType->isIntegralOrEnumerationType());
7251       SugaredConverted = TemplateArgument(Context, Value.getInt(), ParamType);
7252       CanonicalConverted =
7253           TemplateArgument(Context, Value.getInt(), CanonParamType);
7254       break;
7255     case APValue::MemberPointer: {
7256       assert(ParamType->isMemberPointerType());
7257 
7258       // FIXME: We need TemplateArgument representation and mangling for these.
7259       if (!Value.getMemberPointerPath().empty()) {
7260         Diag(Arg->getBeginLoc(),
7261              diag::err_template_arg_member_ptr_base_derived_not_supported)
7262             << Value.getMemberPointerDecl() << ParamType
7263             << Arg->getSourceRange();
7264         return ExprError();
7265       }
7266 
7267       auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
7268       SugaredConverted = VD ? TemplateArgument(VD, ParamType)
7269                             : TemplateArgument(ParamType, /*isNullPtr=*/true);
7270       CanonicalConverted =
7271           VD ? TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7272                                 CanonParamType)
7273              : TemplateArgument(CanonParamType, /*isNullPtr=*/true);
7274       break;
7275     }
7276     case APValue::LValue: {
7277       //   For a non-type template-parameter of pointer or reference type,
7278       //   the value of the constant expression shall not refer to
7279       assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
7280              ParamType->isNullPtrType());
7281       // -- a temporary object
7282       // -- a string literal
7283       // -- the result of a typeid expression, or
7284       // -- a predefined __func__ variable
7285       APValue::LValueBase Base = Value.getLValueBase();
7286       auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7287       if (Base &&
7288           (!VD ||
7289            isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
7290         Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7291             << Arg->getSourceRange();
7292         return ExprError();
7293       }
7294       // -- a subobject
7295       // FIXME: Until C++20
7296       if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
7297           VD && VD->getType()->isArrayType() &&
7298           Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7299           !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7300         // Per defect report (no number yet):
7301         //   ... other than a pointer to the first element of a complete array
7302         //       object.
7303       } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7304                  Value.isLValueOnePastTheEnd()) {
7305         Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7306           << Value.getAsString(Context, ParamType);
7307         return ExprError();
7308       }
7309       assert((VD || !ParamType->isReferenceType()) &&
7310              "null reference should not be a constant expression");
7311       assert((!VD || !ParamType->isNullPtrType()) &&
7312              "non-null value of type nullptr_t?");
7313 
7314       SugaredConverted = VD ? TemplateArgument(VD, ParamType)
7315                             : TemplateArgument(ParamType, /*isNullPtr=*/true);
7316       CanonicalConverted =
7317           VD ? TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7318                                 CanonParamType)
7319              : TemplateArgument(CanonParamType, /*isNullPtr=*/true);
7320       break;
7321     }
7322     case APValue::Struct:
7323     case APValue::Union: {
7324       // Get or create the corresponding template parameter object.
7325       TemplateParamObjectDecl *D =
7326           Context.getTemplateParamObjectDecl(ParamType, Value);
7327       SugaredConverted = TemplateArgument(D, ParamType);
7328       CanonicalConverted =
7329           TemplateArgument(D->getCanonicalDecl(), CanonParamType);
7330       break;
7331     }
7332     case APValue::AddrLabelDiff:
7333       return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7334     case APValue::FixedPoint:
7335     case APValue::Float:
7336     case APValue::ComplexInt:
7337     case APValue::ComplexFloat:
7338     case APValue::Vector:
7339     case APValue::Array:
7340       return Diag(StartLoc, diag::err_non_type_template_arg_unsupported)
7341              << ParamType;
7342     }
7343 
7344     return ArgResult.get();
7345   }
7346 
7347   // C++ [temp.arg.nontype]p5:
7348   //   The following conversions are performed on each expression used
7349   //   as a non-type template-argument. If a non-type
7350   //   template-argument cannot be converted to the type of the
7351   //   corresponding template-parameter then the program is
7352   //   ill-formed.
7353   if (ParamType->isIntegralOrEnumerationType()) {
7354     // C++11:
7355     //   -- for a non-type template-parameter of integral or
7356     //      enumeration type, conversions permitted in a converted
7357     //      constant expression are applied.
7358     //
7359     // C++98:
7360     //   -- for a non-type template-parameter of integral or
7361     //      enumeration type, integral promotions (4.5) and integral
7362     //      conversions (4.7) are applied.
7363 
7364     if (getLangOpts().CPlusPlus11) {
7365       // C++ [temp.arg.nontype]p1:
7366       //   A template-argument for a non-type, non-template template-parameter
7367       //   shall be one of:
7368       //
7369       //     -- for a non-type template-parameter of integral or enumeration
7370       //        type, a converted constant expression of the type of the
7371       //        template-parameter; or
7372       llvm::APSInt Value;
7373       ExprResult ArgResult =
7374         CheckConvertedConstantExpression(Arg, ParamType, Value,
7375                                          CCEK_TemplateArg);
7376       if (ArgResult.isInvalid())
7377         return ExprError();
7378 
7379       // We can't check arbitrary value-dependent arguments.
7380       if (ArgResult.get()->isValueDependent()) {
7381         SugaredConverted = TemplateArgument(ArgResult.get());
7382         CanonicalConverted =
7383             Context.getCanonicalTemplateArgument(SugaredConverted);
7384         return ArgResult;
7385       }
7386 
7387       // Widen the argument value to sizeof(parameter type). This is almost
7388       // always a no-op, except when the parameter type is bool. In
7389       // that case, this may extend the argument from 1 bit to 8 bits.
7390       QualType IntegerType = ParamType;
7391       if (const EnumType *Enum = IntegerType->getAs<EnumType>())
7392         IntegerType = Enum->getDecl()->getIntegerType();
7393       Value = Value.extOrTrunc(IntegerType->isBitIntType()
7394                                    ? Context.getIntWidth(IntegerType)
7395                                    : Context.getTypeSize(IntegerType));
7396 
7397       SugaredConverted = TemplateArgument(Context, Value, ParamType);
7398       CanonicalConverted =
7399           TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7400       return ArgResult;
7401     }
7402 
7403     ExprResult ArgResult = DefaultLvalueConversion(Arg);
7404     if (ArgResult.isInvalid())
7405       return ExprError();
7406     Arg = ArgResult.get();
7407 
7408     QualType ArgType = Arg->getType();
7409 
7410     // C++ [temp.arg.nontype]p1:
7411     //   A template-argument for a non-type, non-template
7412     //   template-parameter shall be one of:
7413     //
7414     //     -- an integral constant-expression of integral or enumeration
7415     //        type; or
7416     //     -- the name of a non-type template-parameter; or
7417     llvm::APSInt Value;
7418     if (!ArgType->isIntegralOrEnumerationType()) {
7419       Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7420           << ArgType << Arg->getSourceRange();
7421       Diag(Param->getLocation(), diag::note_template_param_here);
7422       return ExprError();
7423     } else if (!Arg->isValueDependent()) {
7424       class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7425         QualType T;
7426 
7427       public:
7428         TmplArgICEDiagnoser(QualType T) : T(T) { }
7429 
7430         SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7431                                              SourceLocation Loc) override {
7432           return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7433         }
7434       } Diagnoser(ArgType);
7435 
7436       Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7437       if (!Arg)
7438         return ExprError();
7439     }
7440 
7441     // From here on out, all we care about is the unqualified form
7442     // of the argument type.
7443     ArgType = ArgType.getUnqualifiedType();
7444 
7445     // Try to convert the argument to the parameter's type.
7446     if (Context.hasSameType(ParamType, ArgType)) {
7447       // Okay: no conversion necessary
7448     } else if (ParamType->isBooleanType()) {
7449       // This is an integral-to-boolean conversion.
7450       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7451     } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7452                !ParamType->isEnumeralType()) {
7453       // This is an integral promotion or conversion.
7454       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7455     } else {
7456       // We can't perform this conversion.
7457       Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7458           << Arg->getType() << ParamType << Arg->getSourceRange();
7459       Diag(Param->getLocation(), diag::note_template_param_here);
7460       return ExprError();
7461     }
7462 
7463     // Add the value of this argument to the list of converted
7464     // arguments. We use the bitwidth and signedness of the template
7465     // parameter.
7466     if (Arg->isValueDependent()) {
7467       // The argument is value-dependent. Create a new
7468       // TemplateArgument with the converted expression.
7469       SugaredConverted = TemplateArgument(Arg);
7470       CanonicalConverted =
7471           Context.getCanonicalTemplateArgument(SugaredConverted);
7472       return Arg;
7473     }
7474 
7475     QualType IntegerType = ParamType;
7476     if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
7477       IntegerType = Enum->getDecl()->getIntegerType();
7478     }
7479 
7480     if (ParamType->isBooleanType()) {
7481       // Value must be zero or one.
7482       Value = Value != 0;
7483       unsigned AllowedBits = Context.getTypeSize(IntegerType);
7484       if (Value.getBitWidth() != AllowedBits)
7485         Value = Value.extOrTrunc(AllowedBits);
7486       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7487     } else {
7488       llvm::APSInt OldValue = Value;
7489 
7490       // Coerce the template argument's value to the value it will have
7491       // based on the template parameter's type.
7492       unsigned AllowedBits = IntegerType->isBitIntType()
7493                                  ? Context.getIntWidth(IntegerType)
7494                                  : Context.getTypeSize(IntegerType);
7495       if (Value.getBitWidth() != AllowedBits)
7496         Value = Value.extOrTrunc(AllowedBits);
7497       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7498 
7499       // Complain if an unsigned parameter received a negative value.
7500       if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7501           (OldValue.isSigned() && OldValue.isNegative())) {
7502         Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7503             << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7504             << Arg->getSourceRange();
7505         Diag(Param->getLocation(), diag::note_template_param_here);
7506       }
7507 
7508       // Complain if we overflowed the template parameter's type.
7509       unsigned RequiredBits;
7510       if (IntegerType->isUnsignedIntegerOrEnumerationType())
7511         RequiredBits = OldValue.getActiveBits();
7512       else if (OldValue.isUnsigned())
7513         RequiredBits = OldValue.getActiveBits() + 1;
7514       else
7515         RequiredBits = OldValue.getMinSignedBits();
7516       if (RequiredBits > AllowedBits) {
7517         Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7518             << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7519             << Arg->getSourceRange();
7520         Diag(Param->getLocation(), diag::note_template_param_here);
7521       }
7522     }
7523 
7524     QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7525     SugaredConverted = TemplateArgument(Context, Value, T);
7526     CanonicalConverted =
7527         TemplateArgument(Context, Value, Context.getCanonicalType(T));
7528     return Arg;
7529   }
7530 
7531   QualType ArgType = Arg->getType();
7532   DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7533 
7534   // Handle pointer-to-function, reference-to-function, and
7535   // pointer-to-member-function all in (roughly) the same way.
7536   if (// -- For a non-type template-parameter of type pointer to
7537       //    function, only the function-to-pointer conversion (4.3) is
7538       //    applied. If the template-argument represents a set of
7539       //    overloaded functions (or a pointer to such), the matching
7540       //    function is selected from the set (13.4).
7541       (ParamType->isPointerType() &&
7542        ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7543       // -- For a non-type template-parameter of type reference to
7544       //    function, no conversions apply. If the template-argument
7545       //    represents a set of overloaded functions, the matching
7546       //    function is selected from the set (13.4).
7547       (ParamType->isReferenceType() &&
7548        ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7549       // -- For a non-type template-parameter of type pointer to
7550       //    member function, no conversions apply. If the
7551       //    template-argument represents a set of overloaded member
7552       //    functions, the matching member function is selected from
7553       //    the set (13.4).
7554       (ParamType->isMemberPointerType() &&
7555        ParamType->castAs<MemberPointerType>()->getPointeeType()
7556          ->isFunctionType())) {
7557 
7558     if (Arg->getType() == Context.OverloadTy) {
7559       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7560                                                                 true,
7561                                                                 FoundResult)) {
7562         if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7563           return ExprError();
7564 
7565         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7566         ArgType = Arg->getType();
7567       } else
7568         return ExprError();
7569     }
7570 
7571     if (!ParamType->isMemberPointerType()) {
7572       if (CheckTemplateArgumentAddressOfObjectOrFunction(
7573               *this, Param, ParamType, Arg, SugaredConverted,
7574               CanonicalConverted))
7575         return ExprError();
7576       return Arg;
7577     }
7578 
7579     if (CheckTemplateArgumentPointerToMember(
7580             *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7581       return ExprError();
7582     return Arg;
7583   }
7584 
7585   if (ParamType->isPointerType()) {
7586     //   -- for a non-type template-parameter of type pointer to
7587     //      object, qualification conversions (4.4) and the
7588     //      array-to-pointer conversion (4.2) are applied.
7589     // C++0x also allows a value of std::nullptr_t.
7590     assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7591            "Only object pointers allowed here");
7592 
7593     if (CheckTemplateArgumentAddressOfObjectOrFunction(
7594             *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7595       return ExprError();
7596     return Arg;
7597   }
7598 
7599   if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7600     //   -- For a non-type template-parameter of type reference to
7601     //      object, no conversions apply. The type referred to by the
7602     //      reference may be more cv-qualified than the (otherwise
7603     //      identical) type of the template-argument. The
7604     //      template-parameter is bound directly to the
7605     //      template-argument, which must be an lvalue.
7606     assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7607            "Only object references allowed here");
7608 
7609     if (Arg->getType() == Context.OverloadTy) {
7610       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
7611                                                  ParamRefType->getPointeeType(),
7612                                                                 true,
7613                                                                 FoundResult)) {
7614         if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7615           return ExprError();
7616 
7617         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7618         ArgType = Arg->getType();
7619       } else
7620         return ExprError();
7621     }
7622 
7623     if (CheckTemplateArgumentAddressOfObjectOrFunction(
7624             *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7625       return ExprError();
7626     return Arg;
7627   }
7628 
7629   // Deal with parameters of type std::nullptr_t.
7630   if (ParamType->isNullPtrType()) {
7631     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7632       SugaredConverted = TemplateArgument(Arg);
7633       CanonicalConverted =
7634           Context.getCanonicalTemplateArgument(SugaredConverted);
7635       return Arg;
7636     }
7637 
7638     switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7639     case NPV_NotNullPointer:
7640       Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7641         << Arg->getType() << ParamType;
7642       Diag(Param->getLocation(), diag::note_template_param_here);
7643       return ExprError();
7644 
7645     case NPV_Error:
7646       return ExprError();
7647 
7648     case NPV_NullPointer:
7649       Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7650       SugaredConverted = TemplateArgument(ParamType,
7651                                           /*isNullPtr=*/true);
7652       CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7653                                             /*isNullPtr=*/true);
7654       return Arg;
7655     }
7656   }
7657 
7658   //     -- For a non-type template-parameter of type pointer to data
7659   //        member, qualification conversions (4.4) are applied.
7660   assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7661 
7662   if (CheckTemplateArgumentPointerToMember(
7663           *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7664     return ExprError();
7665   return Arg;
7666 }
7667 
7668 static void DiagnoseTemplateParameterListArityMismatch(
7669     Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7670     Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7671 
7672 /// Check a template argument against its corresponding
7673 /// template template parameter.
7674 ///
7675 /// This routine implements the semantics of C++ [temp.arg.template].
7676 /// It returns true if an error occurred, and false otherwise.
CheckTemplateTemplateArgument(TemplateTemplateParmDecl * Param,TemplateParameterList * Params,TemplateArgumentLoc & Arg)7677 bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7678                                          TemplateParameterList *Params,
7679                                          TemplateArgumentLoc &Arg) {
7680   TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7681   TemplateDecl *Template = Name.getAsTemplateDecl();
7682   if (!Template) {
7683     // Any dependent template name is fine.
7684     assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7685     return false;
7686   }
7687 
7688   if (Template->isInvalidDecl())
7689     return true;
7690 
7691   // C++0x [temp.arg.template]p1:
7692   //   A template-argument for a template template-parameter shall be
7693   //   the name of a class template or an alias template, expressed as an
7694   //   id-expression. When the template-argument names a class template, only
7695   //   primary class templates are considered when matching the
7696   //   template template argument with the corresponding parameter;
7697   //   partial specializations are not considered even if their
7698   //   parameter lists match that of the template template parameter.
7699   //
7700   // Note that we also allow template template parameters here, which
7701   // will happen when we are dealing with, e.g., class template
7702   // partial specializations.
7703   if (!isa<ClassTemplateDecl>(Template) &&
7704       !isa<TemplateTemplateParmDecl>(Template) &&
7705       !isa<TypeAliasTemplateDecl>(Template) &&
7706       !isa<BuiltinTemplateDecl>(Template)) {
7707     assert(isa<FunctionTemplateDecl>(Template) &&
7708            "Only function templates are possible here");
7709     Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7710     Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7711       << Template;
7712   }
7713 
7714   // C++1z [temp.arg.template]p3: (DR 150)
7715   //   A template-argument matches a template template-parameter P when P
7716   //   is at least as specialized as the template-argument A.
7717   // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a
7718   //  defect report resolution from C++17 and shouldn't be introduced by
7719   //  concepts.
7720   if (getLangOpts().RelaxedTemplateTemplateArgs) {
7721     // Quick check for the common case:
7722     //   If P contains a parameter pack, then A [...] matches P if each of A's
7723     //   template parameters matches the corresponding template parameter in
7724     //   the template-parameter-list of P.
7725     if (TemplateParameterListsAreEqual(
7726             Template->getTemplateParameters(), Params, false,
7727             TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) &&
7728         // If the argument has no associated constraints, then the parameter is
7729         // definitely at least as specialized as the argument.
7730         // Otherwise - we need a more thorough check.
7731         !Template->hasAssociatedConstraints())
7732       return false;
7733 
7734     if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
7735                                                           Arg.getLocation())) {
7736       // P2113
7737       // C++20[temp.func.order]p2
7738       //   [...] If both deductions succeed, the partial ordering selects the
7739       // more constrained template (if one exists) as determined below.
7740       SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7741       Params->getAssociatedConstraints(ParamsAC);
7742       // C++2a[temp.arg.template]p3
7743       //   [...] In this comparison, if P is unconstrained, the constraints on A
7744       //   are not considered.
7745       if (ParamsAC.empty())
7746         return false;
7747 
7748       Template->getAssociatedConstraints(TemplateAC);
7749 
7750       bool IsParamAtLeastAsConstrained;
7751       if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7752                                  IsParamAtLeastAsConstrained))
7753         return true;
7754       if (!IsParamAtLeastAsConstrained) {
7755         Diag(Arg.getLocation(),
7756              diag::err_template_template_parameter_not_at_least_as_constrained)
7757             << Template << Param << Arg.getSourceRange();
7758         Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7759         Diag(Template->getLocation(), diag::note_entity_declared_at)
7760             << Template;
7761         MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7762                                                       TemplateAC);
7763         return true;
7764       }
7765       return false;
7766     }
7767     // FIXME: Produce better diagnostics for deduction failures.
7768   }
7769 
7770   return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
7771                                          Params,
7772                                          true,
7773                                          TPL_TemplateTemplateArgumentMatch,
7774                                          Arg.getLocation());
7775 }
7776 
7777 /// Given a non-type template argument that refers to a
7778 /// declaration and the type of its corresponding non-type template
7779 /// parameter, produce an expression that properly refers to that
7780 /// declaration.
7781 ExprResult
BuildExpressionFromDeclTemplateArgument(const TemplateArgument & Arg,QualType ParamType,SourceLocation Loc)7782 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7783                                               QualType ParamType,
7784                                               SourceLocation Loc) {
7785   // C++ [temp.param]p8:
7786   //
7787   //   A non-type template-parameter of type "array of T" or
7788   //   "function returning T" is adjusted to be of type "pointer to
7789   //   T" or "pointer to function returning T", respectively.
7790   if (ParamType->isArrayType())
7791     ParamType = Context.getArrayDecayedType(ParamType);
7792   else if (ParamType->isFunctionType())
7793     ParamType = Context.getPointerType(ParamType);
7794 
7795   // For a NULL non-type template argument, return nullptr casted to the
7796   // parameter's type.
7797   if (Arg.getKind() == TemplateArgument::NullPtr) {
7798     return ImpCastExprToType(
7799              new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7800                              ParamType,
7801                              ParamType->getAs<MemberPointerType>()
7802                                ? CK_NullToMemberPointer
7803                                : CK_NullToPointer);
7804   }
7805   assert(Arg.getKind() == TemplateArgument::Declaration &&
7806          "Only declaration template arguments permitted here");
7807 
7808   ValueDecl *VD = Arg.getAsDecl();
7809 
7810   CXXScopeSpec SS;
7811   if (ParamType->isMemberPointerType()) {
7812     // If this is a pointer to member, we need to use a qualified name to
7813     // form a suitable pointer-to-member constant.
7814     assert(VD->getDeclContext()->isRecord() &&
7815            (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7816             isa<IndirectFieldDecl>(VD)));
7817     QualType ClassType
7818       = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
7819     NestedNameSpecifier *Qualifier
7820       = NestedNameSpecifier::Create(Context, nullptr, false,
7821                                     ClassType.getTypePtr());
7822     SS.MakeTrivial(Context, Qualifier, Loc);
7823   }
7824 
7825   ExprResult RefExpr = BuildDeclarationNameExpr(
7826       SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7827   if (RefExpr.isInvalid())
7828     return ExprError();
7829 
7830   // For a pointer, the argument declaration is the pointee. Take its address.
7831   QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7832   if (ParamType->isPointerType() && !ElemT.isNull() &&
7833       Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7834     // Decay an array argument if we want a pointer to its first element.
7835     RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7836     if (RefExpr.isInvalid())
7837       return ExprError();
7838   } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7839     // For any other pointer, take the address (or form a pointer-to-member).
7840     RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7841     if (RefExpr.isInvalid())
7842       return ExprError();
7843   } else if (ParamType->isRecordType()) {
7844     assert(isa<TemplateParamObjectDecl>(VD) &&
7845            "arg for class template param not a template parameter object");
7846     // No conversions apply in this case.
7847     return RefExpr;
7848   } else {
7849     assert(ParamType->isReferenceType() &&
7850            "unexpected type for decl template argument");
7851   }
7852 
7853   // At this point we should have the right value category.
7854   assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7855          "value kind mismatch for non-type template argument");
7856 
7857   // The type of the template parameter can differ from the type of the
7858   // argument in various ways; convert it now if necessary.
7859   QualType DestExprType = ParamType.getNonLValueExprType(Context);
7860   if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7861     CastKind CK;
7862     QualType Ignored;
7863     if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7864         IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7865       CK = CK_NoOp;
7866     } else if (ParamType->isVoidPointerType() &&
7867                RefExpr.get()->getType()->isPointerType()) {
7868       CK = CK_BitCast;
7869     } else {
7870       // FIXME: Pointers to members can need conversion derived-to-base or
7871       // base-to-derived conversions. We currently don't retain enough
7872       // information to convert properly (we need to track a cast path or
7873       // subobject number in the template argument).
7874       llvm_unreachable(
7875           "unexpected conversion required for non-type template argument");
7876     }
7877     RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7878                                 RefExpr.get()->getValueKind());
7879   }
7880 
7881   return RefExpr;
7882 }
7883 
7884 /// Construct a new expression that refers to the given
7885 /// integral template argument with the given source-location
7886 /// information.
7887 ///
7888 /// This routine takes care of the mapping from an integral template
7889 /// argument (which may have any integral type) to the appropriate
7890 /// literal value.
7891 ExprResult
BuildExpressionFromIntegralTemplateArgument(const TemplateArgument & Arg,SourceLocation Loc)7892 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7893                                                   SourceLocation Loc) {
7894   assert(Arg.getKind() == TemplateArgument::Integral &&
7895          "Operation is only valid for integral template arguments");
7896   QualType OrigT = Arg.getIntegralType();
7897 
7898   // If this is an enum type that we're instantiating, we need to use an integer
7899   // type the same size as the enumerator.  We don't want to build an
7900   // IntegerLiteral with enum type.  The integer type of an enum type can be of
7901   // any integral type with C++11 enum classes, make sure we create the right
7902   // type of literal for it.
7903   QualType T = OrigT;
7904   if (const EnumType *ET = OrigT->getAs<EnumType>())
7905     T = ET->getDecl()->getIntegerType();
7906 
7907   Expr *E;
7908   if (T->isAnyCharacterType()) {
7909     CharacterLiteral::CharacterKind Kind;
7910     if (T->isWideCharType())
7911       Kind = CharacterLiteral::Wide;
7912     else if (T->isChar8Type() && getLangOpts().Char8)
7913       Kind = CharacterLiteral::UTF8;
7914     else if (T->isChar16Type())
7915       Kind = CharacterLiteral::UTF16;
7916     else if (T->isChar32Type())
7917       Kind = CharacterLiteral::UTF32;
7918     else
7919       Kind = CharacterLiteral::Ascii;
7920 
7921     E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
7922                                        Kind, T, Loc);
7923   } else if (T->isBooleanType()) {
7924     E = CXXBoolLiteralExpr::Create(Context, Arg.getAsIntegral().getBoolValue(),
7925                                    T, Loc);
7926   } else if (T->isNullPtrType()) {
7927     E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
7928   } else {
7929     E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
7930   }
7931 
7932   if (OrigT->isEnumeralType()) {
7933     // FIXME: This is a hack. We need a better way to handle substituted
7934     // non-type template parameters.
7935     E = CStyleCastExpr::Create(Context, OrigT, VK_PRValue, CK_IntegralCast, E,
7936                                nullptr, CurFPFeatureOverrides(),
7937                                Context.getTrivialTypeSourceInfo(OrigT, Loc),
7938                                Loc, Loc);
7939   }
7940 
7941   return E;
7942 }
7943 
7944 /// Match two template parameters within template parameter lists.
MatchTemplateParameterKind(Sema & S,NamedDecl * New,const NamedDecl * NewInstFrom,NamedDecl * Old,const NamedDecl * OldInstFrom,bool Complain,Sema::TemplateParameterListEqualKind Kind,SourceLocation TemplateArgLoc,bool PartialOrdering)7945 static bool MatchTemplateParameterKind(
7946     Sema &S, NamedDecl *New, const NamedDecl *NewInstFrom, NamedDecl *Old,
7947     const NamedDecl *OldInstFrom, bool Complain,
7948     Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc,
7949     bool PartialOrdering) {
7950   // Check the actual kind (type, non-type, template).
7951   if (Old->getKind() != New->getKind()) {
7952     if (Complain) {
7953       unsigned NextDiag = diag::err_template_param_different_kind;
7954       if (TemplateArgLoc.isValid()) {
7955         S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7956         NextDiag = diag::note_template_param_different_kind;
7957       }
7958       S.Diag(New->getLocation(), NextDiag)
7959         << (Kind != Sema::TPL_TemplateMatch);
7960       S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7961         << (Kind != Sema::TPL_TemplateMatch);
7962     }
7963 
7964     return false;
7965   }
7966 
7967   // Check that both are parameter packs or neither are parameter packs.
7968   // However, if we are matching a template template argument to a
7969   // template template parameter, the template template parameter can have
7970   // a parameter pack where the template template argument does not.
7971   if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7972       !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
7973         Old->isTemplateParameterPack())) {
7974     if (Complain) {
7975       unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7976       if (TemplateArgLoc.isValid()) {
7977         S.Diag(TemplateArgLoc,
7978              diag::err_template_arg_template_params_mismatch);
7979         NextDiag = diag::note_template_parameter_pack_non_pack;
7980       }
7981 
7982       unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7983                       : isa<NonTypeTemplateParmDecl>(New)? 1
7984                       : 2;
7985       S.Diag(New->getLocation(), NextDiag)
7986         << ParamKind << New->isParameterPack();
7987       S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7988         << ParamKind << Old->isParameterPack();
7989     }
7990 
7991     return false;
7992   }
7993 
7994   // For non-type template parameters, check the type of the parameter.
7995   if (NonTypeTemplateParmDecl *OldNTTP
7996                                     = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7997     NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7998 
7999     // If we are matching a template template argument to a template
8000     // template parameter and one of the non-type template parameter types
8001     // is dependent, then we must wait until template instantiation time
8002     // to actually compare the arguments.
8003     if (Kind != Sema::TPL_TemplateTemplateArgumentMatch ||
8004         (!OldNTTP->getType()->isDependentType() &&
8005          !NewNTTP->getType()->isDependentType()))
8006       if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
8007         if (Complain) {
8008           unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8009           if (TemplateArgLoc.isValid()) {
8010             S.Diag(TemplateArgLoc,
8011                    diag::err_template_arg_template_params_mismatch);
8012             NextDiag = diag::note_template_nontype_parm_different_type;
8013           }
8014           S.Diag(NewNTTP->getLocation(), NextDiag)
8015             << NewNTTP->getType()
8016             << (Kind != Sema::TPL_TemplateMatch);
8017           S.Diag(OldNTTP->getLocation(),
8018                  diag::note_template_nontype_parm_prev_declaration)
8019             << OldNTTP->getType();
8020         }
8021 
8022         return false;
8023       }
8024   }
8025   // For template template parameters, check the template parameter types.
8026   // The template parameter lists of template template
8027   // parameters must agree.
8028   else if (TemplateTemplateParmDecl *OldTTP
8029                                     = dyn_cast<TemplateTemplateParmDecl>(Old)) {
8030     TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
8031     if (!S.TemplateParameterListsAreEqual(
8032             NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8033             OldTTP->getTemplateParameters(), Complain,
8034             (Kind == Sema::TPL_TemplateMatch
8035                  ? Sema::TPL_TemplateTemplateParmMatch
8036                  : Kind),
8037             TemplateArgLoc, PartialOrdering))
8038       return false;
8039   }
8040 
8041   if (!PartialOrdering && Kind != Sema::TPL_TemplateTemplateArgumentMatch &&
8042       !isa<TemplateTemplateParmDecl>(Old)) {
8043     const Expr *NewC = nullptr, *OldC = nullptr;
8044 
8045     if (isa<TemplateTypeParmDecl>(New)) {
8046       if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8047         NewC = TC->getImmediatelyDeclaredConstraint();
8048       if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8049         OldC = TC->getImmediatelyDeclaredConstraint();
8050     } else if (isa<NonTypeTemplateParmDecl>(New)) {
8051       if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8052                               ->getPlaceholderTypeConstraint())
8053         NewC = E;
8054       if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8055                               ->getPlaceholderTypeConstraint())
8056         OldC = E;
8057     } else
8058       llvm_unreachable("unexpected template parameter type");
8059 
8060     auto Diagnose = [&] {
8061       S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8062            diag::err_template_different_type_constraint);
8063       S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8064            diag::note_template_prev_declaration) << /*declaration*/0;
8065     };
8066 
8067     if (!NewC != !OldC) {
8068       if (Complain)
8069         Diagnose();
8070       return false;
8071     }
8072 
8073     if (NewC) {
8074       if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8075                                            NewC)) {
8076         if (Complain)
8077           Diagnose();
8078         return false;
8079       }
8080     }
8081   }
8082 
8083   return true;
8084 }
8085 
8086 /// Diagnose a known arity mismatch when comparing template argument
8087 /// lists.
8088 static
DiagnoseTemplateParameterListArityMismatch(Sema & S,TemplateParameterList * New,TemplateParameterList * Old,Sema::TemplateParameterListEqualKind Kind,SourceLocation TemplateArgLoc)8089 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8090                                                 TemplateParameterList *New,
8091                                                 TemplateParameterList *Old,
8092                                       Sema::TemplateParameterListEqualKind Kind,
8093                                                 SourceLocation TemplateArgLoc) {
8094   unsigned NextDiag = diag::err_template_param_list_different_arity;
8095   if (TemplateArgLoc.isValid()) {
8096     S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8097     NextDiag = diag::note_template_param_list_different_arity;
8098   }
8099   S.Diag(New->getTemplateLoc(), NextDiag)
8100     << (New->size() > Old->size())
8101     << (Kind != Sema::TPL_TemplateMatch)
8102     << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8103   S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8104     << (Kind != Sema::TPL_TemplateMatch)
8105     << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8106 }
8107 
8108 /// Determine whether the given template parameter lists are
8109 /// equivalent.
8110 ///
8111 /// \param New  The new template parameter list, typically written in the
8112 /// source code as part of a new template declaration.
8113 ///
8114 /// \param Old  The old template parameter list, typically found via
8115 /// name lookup of the template declared with this template parameter
8116 /// list.
8117 ///
8118 /// \param Complain  If true, this routine will produce a diagnostic if
8119 /// the template parameter lists are not equivalent.
8120 ///
8121 /// \param Kind describes how we are to match the template parameter lists.
8122 ///
8123 /// \param TemplateArgLoc If this source location is valid, then we
8124 /// are actually checking the template parameter list of a template
8125 /// argument (New) against the template parameter list of its
8126 /// corresponding template template parameter (Old). We produce
8127 /// slightly different diagnostics in this scenario.
8128 ///
8129 /// \returns True if the template parameter lists are equal, false
8130 /// otherwise.
TemplateParameterListsAreEqual(const NamedDecl * NewInstFrom,TemplateParameterList * New,const NamedDecl * OldInstFrom,TemplateParameterList * Old,bool Complain,TemplateParameterListEqualKind Kind,SourceLocation TemplateArgLoc,bool PartialOrdering)8131 bool Sema::TemplateParameterListsAreEqual(
8132     const NamedDecl *NewInstFrom, TemplateParameterList *New,
8133     const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8134     TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc,
8135     bool PartialOrdering) {
8136   if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
8137     if (Complain)
8138       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8139                                                  TemplateArgLoc);
8140 
8141     return false;
8142   }
8143 
8144   // C++0x [temp.arg.template]p3:
8145   //   A template-argument matches a template template-parameter (call it P)
8146   //   when each of the template parameters in the template-parameter-list of
8147   //   the template-argument's corresponding class template or alias template
8148   //   (call it A) matches the corresponding template parameter in the
8149   //   template-parameter-list of P. [...]
8150   TemplateParameterList::iterator NewParm = New->begin();
8151   TemplateParameterList::iterator NewParmEnd = New->end();
8152   for (TemplateParameterList::iterator OldParm = Old->begin(),
8153                                     OldParmEnd = Old->end();
8154        OldParm != OldParmEnd; ++OldParm) {
8155     if (Kind != TPL_TemplateTemplateArgumentMatch ||
8156         !(*OldParm)->isTemplateParameterPack()) {
8157       if (NewParm == NewParmEnd) {
8158         if (Complain)
8159           DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8160                                                      TemplateArgLoc);
8161 
8162         return false;
8163       }
8164 
8165       if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8166                                       OldInstFrom, Complain, Kind,
8167                                       TemplateArgLoc, PartialOrdering))
8168         return false;
8169 
8170       ++NewParm;
8171       continue;
8172     }
8173 
8174     // C++0x [temp.arg.template]p3:
8175     //   [...] When P's template- parameter-list contains a template parameter
8176     //   pack (14.5.3), the template parameter pack will match zero or more
8177     //   template parameters or template parameter packs in the
8178     //   template-parameter-list of A with the same type and form as the
8179     //   template parameter pack in P (ignoring whether those template
8180     //   parameters are template parameter packs).
8181     for (; NewParm != NewParmEnd; ++NewParm) {
8182       if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8183                                       OldInstFrom, Complain, Kind,
8184                                       TemplateArgLoc, PartialOrdering))
8185         return false;
8186     }
8187   }
8188 
8189   // Make sure we exhausted all of the arguments.
8190   if (NewParm != NewParmEnd) {
8191     if (Complain)
8192       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8193                                                  TemplateArgLoc);
8194 
8195     return false;
8196   }
8197 
8198   if (!PartialOrdering && Kind != TPL_TemplateTemplateArgumentMatch) {
8199     const Expr *NewRC = New->getRequiresClause();
8200     const Expr *OldRC = Old->getRequiresClause();
8201 
8202     auto Diagnose = [&] {
8203       Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8204            diag::err_template_different_requires_clause);
8205       Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8206            diag::note_template_prev_declaration) << /*declaration*/0;
8207     };
8208 
8209     if (!NewRC != !OldRC) {
8210       if (Complain)
8211         Diagnose();
8212       return false;
8213     }
8214 
8215     if (NewRC) {
8216       if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8217                                          NewRC)) {
8218         if (Complain)
8219           Diagnose();
8220         return false;
8221       }
8222     }
8223   }
8224 
8225   return true;
8226 }
8227 
8228 /// Check whether a template can be declared within this scope.
8229 ///
8230 /// If the template declaration is valid in this scope, returns
8231 /// false. Otherwise, issues a diagnostic and returns true.
8232 bool
CheckTemplateDeclScope(Scope * S,TemplateParameterList * TemplateParams)8233 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8234   if (!S)
8235     return false;
8236 
8237   // Find the nearest enclosing declaration scope.
8238   while ((S->getFlags() & Scope::DeclScope) == 0 ||
8239          (S->getFlags() & Scope::TemplateParamScope) != 0)
8240     S = S->getParent();
8241 
8242   // C++ [temp.pre]p6: [P2096]
8243   //   A template, explicit specialization, or partial specialization shall not
8244   //   have C linkage.
8245   DeclContext *Ctx = S->getEntity();
8246   if (Ctx && Ctx->isExternCContext()) {
8247     Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
8248         << TemplateParams->getSourceRange();
8249     if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8250       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8251     return true;
8252   }
8253   Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8254 
8255   // C++ [temp]p2:
8256   //   A template-declaration can appear only as a namespace scope or
8257   //   class scope declaration.
8258   // C++ [temp.expl.spec]p3:
8259   //   An explicit specialization may be declared in any scope in which the
8260   //   corresponding primary template may be defined.
8261   // C++ [temp.class.spec]p6: [P2096]
8262   //   A partial specialization may be declared in any scope in which the
8263   //   corresponding primary template may be defined.
8264   if (Ctx) {
8265     if (Ctx->isFileContext())
8266       return false;
8267     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8268       // C++ [temp.mem]p2:
8269       //   A local class shall not have member templates.
8270       if (RD->isLocalClass())
8271         return Diag(TemplateParams->getTemplateLoc(),
8272                     diag::err_template_inside_local_class)
8273           << TemplateParams->getSourceRange();
8274       else
8275         return false;
8276     }
8277   }
8278 
8279   return Diag(TemplateParams->getTemplateLoc(),
8280               diag::err_template_outside_namespace_or_class_scope)
8281     << TemplateParams->getSourceRange();
8282 }
8283 
8284 /// Determine what kind of template specialization the given declaration
8285 /// is.
getTemplateSpecializationKind(Decl * D)8286 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8287   if (!D)
8288     return TSK_Undeclared;
8289 
8290   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8291     return Record->getTemplateSpecializationKind();
8292   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8293     return Function->getTemplateSpecializationKind();
8294   if (VarDecl *Var = dyn_cast<VarDecl>(D))
8295     return Var->getTemplateSpecializationKind();
8296 
8297   return TSK_Undeclared;
8298 }
8299 
8300 /// Check whether a specialization is well-formed in the current
8301 /// context.
8302 ///
8303 /// This routine determines whether a template specialization can be declared
8304 /// in the current context (C++ [temp.expl.spec]p2).
8305 ///
8306 /// \param S the semantic analysis object for which this check is being
8307 /// performed.
8308 ///
8309 /// \param Specialized the entity being specialized or instantiated, which
8310 /// may be a kind of template (class template, function template, etc.) or
8311 /// a member of a class template (member function, static data member,
8312 /// member class).
8313 ///
8314 /// \param PrevDecl the previous declaration of this entity, if any.
8315 ///
8316 /// \param Loc the location of the explicit specialization or instantiation of
8317 /// this entity.
8318 ///
8319 /// \param IsPartialSpecialization whether this is a partial specialization of
8320 /// a class template.
8321 ///
8322 /// \returns true if there was an error that we cannot recover from, false
8323 /// otherwise.
CheckTemplateSpecializationScope(Sema & S,NamedDecl * Specialized,NamedDecl * PrevDecl,SourceLocation Loc,bool IsPartialSpecialization)8324 static bool CheckTemplateSpecializationScope(Sema &S,
8325                                              NamedDecl *Specialized,
8326                                              NamedDecl *PrevDecl,
8327                                              SourceLocation Loc,
8328                                              bool IsPartialSpecialization) {
8329   // Keep these "kind" numbers in sync with the %select statements in the
8330   // various diagnostics emitted by this routine.
8331   int EntityKind = 0;
8332   if (isa<ClassTemplateDecl>(Specialized))
8333     EntityKind = IsPartialSpecialization? 1 : 0;
8334   else if (isa<VarTemplateDecl>(Specialized))
8335     EntityKind = IsPartialSpecialization ? 3 : 2;
8336   else if (isa<FunctionTemplateDecl>(Specialized))
8337     EntityKind = 4;
8338   else if (isa<CXXMethodDecl>(Specialized))
8339     EntityKind = 5;
8340   else if (isa<VarDecl>(Specialized))
8341     EntityKind = 6;
8342   else if (isa<RecordDecl>(Specialized))
8343     EntityKind = 7;
8344   else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8345     EntityKind = 8;
8346   else {
8347     S.Diag(Loc, diag::err_template_spec_unknown_kind)
8348       << S.getLangOpts().CPlusPlus11;
8349     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8350     return true;
8351   }
8352 
8353   // C++ [temp.expl.spec]p2:
8354   //   An explicit specialization may be declared in any scope in which
8355   //   the corresponding primary template may be defined.
8356   if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8357     S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8358       << Specialized;
8359     return true;
8360   }
8361 
8362   // C++ [temp.class.spec]p6:
8363   //   A class template partial specialization may be declared in any
8364   //   scope in which the primary template may be defined.
8365   DeclContext *SpecializedContext =
8366       Specialized->getDeclContext()->getRedeclContext();
8367   DeclContext *DC = S.CurContext->getRedeclContext();
8368 
8369   // Make sure that this redeclaration (or definition) occurs in the same
8370   // scope or an enclosing namespace.
8371   if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8372                             : DC->Equals(SpecializedContext))) {
8373     if (isa<TranslationUnitDecl>(SpecializedContext))
8374       S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8375         << EntityKind << Specialized;
8376     else {
8377       auto *ND = cast<NamedDecl>(SpecializedContext);
8378       int Diag = diag::err_template_spec_redecl_out_of_scope;
8379       if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8380         Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8381       S.Diag(Loc, Diag) << EntityKind << Specialized
8382                         << ND << isa<CXXRecordDecl>(ND);
8383     }
8384 
8385     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8386 
8387     // Don't allow specializing in the wrong class during error recovery.
8388     // Otherwise, things can go horribly wrong.
8389     if (DC->isRecord())
8390       return true;
8391   }
8392 
8393   return false;
8394 }
8395 
findTemplateParameterInType(unsigned Depth,Expr * E)8396 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8397   if (!E->isTypeDependent())
8398     return SourceLocation();
8399   DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8400   Checker.TraverseStmt(E);
8401   if (Checker.MatchLoc.isInvalid())
8402     return E->getSourceRange();
8403   return Checker.MatchLoc;
8404 }
8405 
findTemplateParameter(unsigned Depth,TypeLoc TL)8406 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8407   if (!TL.getType()->isDependentType())
8408     return SourceLocation();
8409   DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8410   Checker.TraverseTypeLoc(TL);
8411   if (Checker.MatchLoc.isInvalid())
8412     return TL.getSourceRange();
8413   return Checker.MatchLoc;
8414 }
8415 
8416 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8417 /// that checks non-type template partial specialization arguments.
CheckNonTypeTemplatePartialSpecializationArgs(Sema & S,SourceLocation TemplateNameLoc,NonTypeTemplateParmDecl * Param,const TemplateArgument * Args,unsigned NumArgs,bool IsDefaultArgument)8418 static bool CheckNonTypeTemplatePartialSpecializationArgs(
8419     Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8420     const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8421   for (unsigned I = 0; I != NumArgs; ++I) {
8422     if (Args[I].getKind() == TemplateArgument::Pack) {
8423       if (CheckNonTypeTemplatePartialSpecializationArgs(
8424               S, TemplateNameLoc, Param, Args[I].pack_begin(),
8425               Args[I].pack_size(), IsDefaultArgument))
8426         return true;
8427 
8428       continue;
8429     }
8430 
8431     if (Args[I].getKind() != TemplateArgument::Expression)
8432       continue;
8433 
8434     Expr *ArgExpr = Args[I].getAsExpr();
8435 
8436     // We can have a pack expansion of any of the bullets below.
8437     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8438       ArgExpr = Expansion->getPattern();
8439 
8440     // Strip off any implicit casts we added as part of type checking.
8441     while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8442       ArgExpr = ICE->getSubExpr();
8443 
8444     // C++ [temp.class.spec]p8:
8445     //   A non-type argument is non-specialized if it is the name of a
8446     //   non-type parameter. All other non-type arguments are
8447     //   specialized.
8448     //
8449     // Below, we check the two conditions that only apply to
8450     // specialized non-type arguments, so skip any non-specialized
8451     // arguments.
8452     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8453       if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8454         continue;
8455 
8456     // C++ [temp.class.spec]p9:
8457     //   Within the argument list of a class template partial
8458     //   specialization, the following restrictions apply:
8459     //     -- A partially specialized non-type argument expression
8460     //        shall not involve a template parameter of the partial
8461     //        specialization except when the argument expression is a
8462     //        simple identifier.
8463     //     -- The type of a template parameter corresponding to a
8464     //        specialized non-type argument shall not be dependent on a
8465     //        parameter of the specialization.
8466     // DR1315 removes the first bullet, leaving an incoherent set of rules.
8467     // We implement a compromise between the original rules and DR1315:
8468     //     --  A specialized non-type template argument shall not be
8469     //         type-dependent and the corresponding template parameter
8470     //         shall have a non-dependent type.
8471     SourceRange ParamUseRange =
8472         findTemplateParameterInType(Param->getDepth(), ArgExpr);
8473     if (ParamUseRange.isValid()) {
8474       if (IsDefaultArgument) {
8475         S.Diag(TemplateNameLoc,
8476                diag::err_dependent_non_type_arg_in_partial_spec);
8477         S.Diag(ParamUseRange.getBegin(),
8478                diag::note_dependent_non_type_default_arg_in_partial_spec)
8479           << ParamUseRange;
8480       } else {
8481         S.Diag(ParamUseRange.getBegin(),
8482                diag::err_dependent_non_type_arg_in_partial_spec)
8483           << ParamUseRange;
8484       }
8485       return true;
8486     }
8487 
8488     ParamUseRange = findTemplateParameter(
8489         Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8490     if (ParamUseRange.isValid()) {
8491       S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8492              diag::err_dependent_typed_non_type_arg_in_partial_spec)
8493           << Param->getType();
8494       S.Diag(Param->getLocation(), diag::note_template_param_here)
8495         << (IsDefaultArgument ? ParamUseRange : SourceRange())
8496         << ParamUseRange;
8497       return true;
8498     }
8499   }
8500 
8501   return false;
8502 }
8503 
8504 /// Check the non-type template arguments of a class template
8505 /// partial specialization according to C++ [temp.class.spec]p9.
8506 ///
8507 /// \param TemplateNameLoc the location of the template name.
8508 /// \param PrimaryTemplate the template parameters of the primary class
8509 ///        template.
8510 /// \param NumExplicit the number of explicitly-specified template arguments.
8511 /// \param TemplateArgs the template arguments of the class template
8512 ///        partial specialization.
8513 ///
8514 /// \returns \c true if there was an error, \c false otherwise.
CheckTemplatePartialSpecializationArgs(SourceLocation TemplateNameLoc,TemplateDecl * PrimaryTemplate,unsigned NumExplicit,ArrayRef<TemplateArgument> TemplateArgs)8515 bool Sema::CheckTemplatePartialSpecializationArgs(
8516     SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8517     unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8518   // We have to be conservative when checking a template in a dependent
8519   // context.
8520   if (PrimaryTemplate->getDeclContext()->isDependentContext())
8521     return false;
8522 
8523   TemplateParameterList *TemplateParams =
8524       PrimaryTemplate->getTemplateParameters();
8525   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8526     NonTypeTemplateParmDecl *Param
8527       = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8528     if (!Param)
8529       continue;
8530 
8531     if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8532                                                       Param, &TemplateArgs[I],
8533                                                       1, I >= NumExplicit))
8534       return true;
8535   }
8536 
8537   return false;
8538 }
8539 
ActOnClassTemplateSpecialization(Scope * S,unsigned TagSpec,TagUseKind TUK,SourceLocation KWLoc,SourceLocation ModulePrivateLoc,CXXScopeSpec & SS,TemplateIdAnnotation & TemplateId,const ParsedAttributesView & Attr,MultiTemplateParamsArg TemplateParameterLists,SkipBodyInfo * SkipBody)8540 DeclResult Sema::ActOnClassTemplateSpecialization(
8541     Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8542     SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8543     TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8544     MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8545   assert(TUK != TUK_Reference && "References are not specializations");
8546 
8547   // NOTE: KWLoc is the location of the tag keyword. This will instead
8548   // store the location of the outermost template keyword in the declaration.
8549   SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
8550     ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
8551   SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8552   SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8553   SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8554 
8555   // Find the class template we're specializing
8556   TemplateName Name = TemplateId.Template.get();
8557   ClassTemplateDecl *ClassTemplate
8558     = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8559 
8560   if (!ClassTemplate) {
8561     Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8562       << (Name.getAsTemplateDecl() &&
8563           isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8564     return true;
8565   }
8566 
8567   bool isMemberSpecialization = false;
8568   bool isPartialSpecialization = false;
8569 
8570   // Check the validity of the template headers that introduce this
8571   // template.
8572   // FIXME: We probably shouldn't complain about these headers for
8573   // friend declarations.
8574   bool Invalid = false;
8575   TemplateParameterList *TemplateParams =
8576       MatchTemplateParametersToScopeSpecifier(
8577           KWLoc, TemplateNameLoc, SS, &TemplateId,
8578           TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
8579           Invalid);
8580   if (Invalid)
8581     return true;
8582 
8583   // Check that we can declare a template specialization here.
8584   if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8585     return true;
8586 
8587   if (TemplateParams && TemplateParams->size() > 0) {
8588     isPartialSpecialization = true;
8589 
8590     if (TUK == TUK_Friend) {
8591       Diag(KWLoc, diag::err_partial_specialization_friend)
8592         << SourceRange(LAngleLoc, RAngleLoc);
8593       return true;
8594     }
8595 
8596     // C++ [temp.class.spec]p10:
8597     //   The template parameter list of a specialization shall not
8598     //   contain default template argument values.
8599     for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8600       Decl *Param = TemplateParams->getParam(I);
8601       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8602         if (TTP->hasDefaultArgument()) {
8603           Diag(TTP->getDefaultArgumentLoc(),
8604                diag::err_default_arg_in_partial_spec);
8605           TTP->removeDefaultArgument();
8606         }
8607       } else if (NonTypeTemplateParmDecl *NTTP
8608                    = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8609         if (Expr *DefArg = NTTP->getDefaultArgument()) {
8610           Diag(NTTP->getDefaultArgumentLoc(),
8611                diag::err_default_arg_in_partial_spec)
8612             << DefArg->getSourceRange();
8613           NTTP->removeDefaultArgument();
8614         }
8615       } else {
8616         TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8617         if (TTP->hasDefaultArgument()) {
8618           Diag(TTP->getDefaultArgument().getLocation(),
8619                diag::err_default_arg_in_partial_spec)
8620             << TTP->getDefaultArgument().getSourceRange();
8621           TTP->removeDefaultArgument();
8622         }
8623       }
8624     }
8625   } else if (TemplateParams) {
8626     if (TUK == TUK_Friend)
8627       Diag(KWLoc, diag::err_template_spec_friend)
8628         << FixItHint::CreateRemoval(
8629                                 SourceRange(TemplateParams->getTemplateLoc(),
8630                                             TemplateParams->getRAngleLoc()))
8631         << SourceRange(LAngleLoc, RAngleLoc);
8632   } else {
8633     assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
8634   }
8635 
8636   // Check that the specialization uses the same tag kind as the
8637   // original template.
8638   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8639   assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
8640   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8641                                     Kind, TUK == TUK_Definition, KWLoc,
8642                                     ClassTemplate->getIdentifier())) {
8643     Diag(KWLoc, diag::err_use_with_wrong_tag)
8644       << ClassTemplate
8645       << FixItHint::CreateReplacement(KWLoc,
8646                             ClassTemplate->getTemplatedDecl()->getKindName());
8647     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8648          diag::note_previous_use);
8649     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8650   }
8651 
8652   // Translate the parser's template argument list in our AST format.
8653   TemplateArgumentListInfo TemplateArgs =
8654       makeTemplateArgumentListInfo(*this, TemplateId);
8655 
8656   // Check for unexpanded parameter packs in any of the template arguments.
8657   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8658     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8659                                         UPPC_PartialSpecialization))
8660       return true;
8661 
8662   // Check that the template argument list is well-formed for this
8663   // template.
8664   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
8665   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8666                                 false, SugaredConverted, CanonicalConverted,
8667                                 /*UpdateArgsWithConversions=*/true))
8668     return true;
8669 
8670   // Find the class template (partial) specialization declaration that
8671   // corresponds to these arguments.
8672   if (isPartialSpecialization) {
8673     if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
8674                                                TemplateArgs.size(),
8675                                                CanonicalConverted))
8676       return true;
8677 
8678     // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8679     // also do it during instantiation.
8680     if (!Name.isDependent() &&
8681         !TemplateSpecializationType::anyDependentTemplateArguments(
8682             TemplateArgs, CanonicalConverted)) {
8683       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8684         << ClassTemplate->getDeclName();
8685       isPartialSpecialization = false;
8686     }
8687   }
8688 
8689   void *InsertPos = nullptr;
8690   ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8691 
8692   if (isPartialSpecialization)
8693     PrevDecl = ClassTemplate->findPartialSpecialization(
8694         CanonicalConverted, TemplateParams, InsertPos);
8695   else
8696     PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
8697 
8698   ClassTemplateSpecializationDecl *Specialization = nullptr;
8699 
8700   // Check whether we can declare a class template specialization in
8701   // the current scope.
8702   if (TUK != TUK_Friend &&
8703       CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
8704                                        TemplateNameLoc,
8705                                        isPartialSpecialization))
8706     return true;
8707 
8708   // The canonical type
8709   QualType CanonType;
8710   if (isPartialSpecialization) {
8711     // Build the canonical type that describes the converted template
8712     // arguments of the class template partial specialization.
8713     TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8714     CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8715                                                       CanonicalConverted);
8716 
8717     if (Context.hasSameType(CanonType,
8718                         ClassTemplate->getInjectedClassNameSpecialization()) &&
8719         (!Context.getLangOpts().CPlusPlus20 ||
8720          !TemplateParams->hasAssociatedConstraints())) {
8721       // C++ [temp.class.spec]p9b3:
8722       //
8723       //   -- The argument list of the specialization shall not be identical
8724       //      to the implicit argument list of the primary template.
8725       //
8726       // This rule has since been removed, because it's redundant given DR1495,
8727       // but we keep it because it produces better diagnostics and recovery.
8728       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8729         << /*class template*/0 << (TUK == TUK_Definition)
8730         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8731       return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
8732                                 ClassTemplate->getIdentifier(),
8733                                 TemplateNameLoc,
8734                                 Attr,
8735                                 TemplateParams,
8736                                 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
8737                                 /*FriendLoc*/SourceLocation(),
8738                                 TemplateParameterLists.size() - 1,
8739                                 TemplateParameterLists.data());
8740     }
8741 
8742     // Create a new class template partial specialization declaration node.
8743     ClassTemplatePartialSpecializationDecl *PrevPartial
8744       = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8745     ClassTemplatePartialSpecializationDecl *Partial =
8746         ClassTemplatePartialSpecializationDecl::Create(
8747             Context, Kind, ClassTemplate->getDeclContext(), KWLoc,
8748             TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted,
8749             TemplateArgs, CanonType, PrevPartial);
8750     SetNestedNameSpecifier(*this, Partial, SS);
8751     if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8752       Partial->setTemplateParameterListsInfo(
8753           Context, TemplateParameterLists.drop_back(1));
8754     }
8755 
8756     if (!PrevPartial)
8757       ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8758     Specialization = Partial;
8759 
8760     // If we are providing an explicit specialization of a member class
8761     // template specialization, make a note of that.
8762     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8763       PrevPartial->setMemberSpecialization();
8764 
8765     CheckTemplatePartialSpecialization(Partial);
8766   } else {
8767     // Create a new class template specialization declaration node for
8768     // this explicit specialization or friend declaration.
8769     Specialization = ClassTemplateSpecializationDecl::Create(
8770         Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8771         ClassTemplate, CanonicalConverted, PrevDecl);
8772     SetNestedNameSpecifier(*this, Specialization, SS);
8773     if (TemplateParameterLists.size() > 0) {
8774       Specialization->setTemplateParameterListsInfo(Context,
8775                                                     TemplateParameterLists);
8776     }
8777 
8778     if (!PrevDecl)
8779       ClassTemplate->AddSpecialization(Specialization, InsertPos);
8780 
8781     if (CurContext->isDependentContext()) {
8782       TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8783       CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8784                                                         CanonicalConverted);
8785     } else {
8786       CanonType = Context.getTypeDeclType(Specialization);
8787     }
8788   }
8789 
8790   // C++ [temp.expl.spec]p6:
8791   //   If a template, a member template or the member of a class template is
8792   //   explicitly specialized then that specialization shall be declared
8793   //   before the first use of that specialization that would cause an implicit
8794   //   instantiation to take place, in every translation unit in which such a
8795   //   use occurs; no diagnostic is required.
8796   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8797     bool Okay = false;
8798     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8799       // Is there any previous explicit specialization declaration?
8800       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8801         Okay = true;
8802         break;
8803       }
8804     }
8805 
8806     if (!Okay) {
8807       SourceRange Range(TemplateNameLoc, RAngleLoc);
8808       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8809         << Context.getTypeDeclType(Specialization) << Range;
8810 
8811       Diag(PrevDecl->getPointOfInstantiation(),
8812            diag::note_instantiation_required_here)
8813         << (PrevDecl->getTemplateSpecializationKind()
8814                                                 != TSK_ImplicitInstantiation);
8815       return true;
8816     }
8817   }
8818 
8819   // If this is not a friend, note that this is an explicit specialization.
8820   if (TUK != TUK_Friend)
8821     Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8822 
8823   // Check that this isn't a redefinition of this specialization.
8824   if (TUK == TUK_Definition) {
8825     RecordDecl *Def = Specialization->getDefinition();
8826     NamedDecl *Hidden = nullptr;
8827     if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8828       SkipBody->ShouldSkip = true;
8829       SkipBody->Previous = Def;
8830       makeMergedDefinitionVisible(Hidden);
8831     } else if (Def) {
8832       SourceRange Range(TemplateNameLoc, RAngleLoc);
8833       Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8834       Diag(Def->getLocation(), diag::note_previous_definition);
8835       Specialization->setInvalidDecl();
8836       return true;
8837     }
8838   }
8839 
8840   ProcessDeclAttributeList(S, Specialization, Attr);
8841 
8842   // Add alignment attributes if necessary; these attributes are checked when
8843   // the ASTContext lays out the structure.
8844   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8845     AddAlignmentAttributesForRecord(Specialization);
8846     AddMsStructLayoutForRecord(Specialization);
8847   }
8848 
8849   if (ModulePrivateLoc.isValid())
8850     Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8851       << (isPartialSpecialization? 1 : 0)
8852       << FixItHint::CreateRemoval(ModulePrivateLoc);
8853 
8854   // Build the fully-sugared type for this class template
8855   // specialization as the user wrote in the specialization
8856   // itself. This means that we'll pretty-print the type retrieved
8857   // from the specialization's declaration the way that the user
8858   // actually wrote the specialization, rather than formatting the
8859   // name based on the "canonical" representation used to store the
8860   // template arguments in the specialization.
8861   TypeSourceInfo *WrittenTy
8862     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8863                                                 TemplateArgs, CanonType);
8864   if (TUK != TUK_Friend) {
8865     Specialization->setTypeAsWritten(WrittenTy);
8866     Specialization->setTemplateKeywordLoc(TemplateKWLoc);
8867   }
8868 
8869   // C++ [temp.expl.spec]p9:
8870   //   A template explicit specialization is in the scope of the
8871   //   namespace in which the template was defined.
8872   //
8873   // We actually implement this paragraph where we set the semantic
8874   // context (in the creation of the ClassTemplateSpecializationDecl),
8875   // but we also maintain the lexical context where the actual
8876   // definition occurs.
8877   Specialization->setLexicalDeclContext(CurContext);
8878 
8879   // We may be starting the definition of this specialization.
8880   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
8881     Specialization->startDefinition();
8882 
8883   if (TUK == TUK_Friend) {
8884     FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
8885                                             TemplateNameLoc,
8886                                             WrittenTy,
8887                                             /*FIXME:*/KWLoc);
8888     Friend->setAccess(AS_public);
8889     CurContext->addDecl(Friend);
8890   } else {
8891     // Add the specialization into its lexical context, so that it can
8892     // be seen when iterating through the list of declarations in that
8893     // context. However, specializations are not found by name lookup.
8894     CurContext->addDecl(Specialization);
8895   }
8896 
8897   if (SkipBody && SkipBody->ShouldSkip)
8898     return SkipBody->Previous;
8899 
8900   return Specialization;
8901 }
8902 
ActOnTemplateDeclarator(Scope * S,MultiTemplateParamsArg TemplateParameterLists,Declarator & D)8903 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
8904                               MultiTemplateParamsArg TemplateParameterLists,
8905                                     Declarator &D) {
8906   Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8907   ActOnDocumentableDecl(NewDecl);
8908   return NewDecl;
8909 }
8910 
ActOnConceptDefinition(Scope * S,MultiTemplateParamsArg TemplateParameterLists,IdentifierInfo * Name,SourceLocation NameLoc,Expr * ConstraintExpr)8911 Decl *Sema::ActOnConceptDefinition(Scope *S,
8912                               MultiTemplateParamsArg TemplateParameterLists,
8913                                    IdentifierInfo *Name, SourceLocation NameLoc,
8914                                    Expr *ConstraintExpr) {
8915   DeclContext *DC = CurContext;
8916 
8917   if (!DC->getRedeclContext()->isFileContext()) {
8918     Diag(NameLoc,
8919       diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8920     return nullptr;
8921   }
8922 
8923   if (TemplateParameterLists.size() > 1) {
8924     Diag(NameLoc, diag::err_concept_extra_headers);
8925     return nullptr;
8926   }
8927 
8928   TemplateParameterList *Params = TemplateParameterLists.front();
8929 
8930   if (Params->size() == 0) {
8931     Diag(NameLoc, diag::err_concept_no_parameters);
8932     return nullptr;
8933   }
8934 
8935   // Ensure that the parameter pack, if present, is the last parameter in the
8936   // template.
8937   for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
8938                                              ParamEnd = Params->end();
8939        ParamIt != ParamEnd; ++ParamIt) {
8940     Decl const *Param = *ParamIt;
8941     if (Param->isParameterPack()) {
8942       if (++ParamIt == ParamEnd)
8943         break;
8944       Diag(Param->getLocation(),
8945            diag::err_template_param_pack_must_be_last_template_parameter);
8946       return nullptr;
8947     }
8948   }
8949 
8950   if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
8951     return nullptr;
8952 
8953   ConceptDecl *NewDecl =
8954       ConceptDecl::Create(Context, DC, NameLoc, Name, Params, ConstraintExpr);
8955 
8956   if (NewDecl->hasAssociatedConstraints()) {
8957     // C++2a [temp.concept]p4:
8958     // A concept shall not have associated constraints.
8959     Diag(NameLoc, diag::err_concept_no_associated_constraints);
8960     NewDecl->setInvalidDecl();
8961   }
8962 
8963   // Check for conflicting previous declaration.
8964   DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
8965   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8966                         forRedeclarationInCurContext());
8967   LookupName(Previous, S);
8968   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
8969                        /*AllowInlineNamespace*/false);
8970   bool AddToScope = true;
8971   CheckConceptRedefinition(NewDecl, Previous, AddToScope);
8972 
8973   ActOnDocumentableDecl(NewDecl);
8974   if (AddToScope)
8975     PushOnScopeChains(NewDecl, S);
8976   return NewDecl;
8977 }
8978 
CheckConceptRedefinition(ConceptDecl * NewDecl,LookupResult & Previous,bool & AddToScope)8979 void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
8980                                     LookupResult &Previous, bool &AddToScope) {
8981   AddToScope = true;
8982 
8983   if (Previous.empty())
8984     return;
8985 
8986   auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
8987   if (!OldConcept) {
8988     auto *Old = Previous.getRepresentativeDecl();
8989     Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
8990         << NewDecl->getDeclName();
8991     notePreviousDefinition(Old, NewDecl->getLocation());
8992     AddToScope = false;
8993     return;
8994   }
8995   // Check if we can merge with a concept declaration.
8996   bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
8997   if (!IsSame) {
8998     Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
8999         << NewDecl->getDeclName();
9000     notePreviousDefinition(OldConcept, NewDecl->getLocation());
9001     AddToScope = false;
9002     return;
9003   }
9004   if (hasReachableDefinition(OldConcept) &&
9005       IsRedefinitionInModule(NewDecl, OldConcept)) {
9006     Diag(NewDecl->getLocation(), diag::err_redefinition)
9007         << NewDecl->getDeclName();
9008     notePreviousDefinition(OldConcept, NewDecl->getLocation());
9009     AddToScope = false;
9010     return;
9011   }
9012   if (!Previous.isSingleResult()) {
9013     // FIXME: we should produce an error in case of ambig and failed lookups.
9014     //        Other decls (e.g. namespaces) also have this shortcoming.
9015     return;
9016   }
9017   // We unwrap canonical decl late to check for module visibility.
9018   Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9019 }
9020 
9021 /// \brief Strips various properties off an implicit instantiation
9022 /// that has just been explicitly specialized.
StripImplicitInstantiation(NamedDecl * D,bool MinGW)9023 static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9024   if (MinGW || (isa<FunctionDecl>(D) &&
9025                 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())) {
9026     D->dropAttr<DLLImportAttr>();
9027     D->dropAttr<DLLExportAttr>();
9028   }
9029 
9030   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9031     FD->setInlineSpecified(false);
9032 }
9033 
9034 /// Compute the diagnostic location for an explicit instantiation
9035 //  declaration or definition.
DiagLocForExplicitInstantiation(NamedDecl * D,SourceLocation PointOfInstantiation)9036 static SourceLocation DiagLocForExplicitInstantiation(
9037     NamedDecl* D, SourceLocation PointOfInstantiation) {
9038   // Explicit instantiations following a specialization have no effect and
9039   // hence no PointOfInstantiation. In that case, walk decl backwards
9040   // until a valid name loc is found.
9041   SourceLocation PrevDiagLoc = PointOfInstantiation;
9042   for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9043        Prev = Prev->getPreviousDecl()) {
9044     PrevDiagLoc = Prev->getLocation();
9045   }
9046   assert(PrevDiagLoc.isValid() &&
9047          "Explicit instantiation without point of instantiation?");
9048   return PrevDiagLoc;
9049 }
9050 
9051 /// Diagnose cases where we have an explicit template specialization
9052 /// before/after an explicit template instantiation, producing diagnostics
9053 /// for those cases where they are required and determining whether the
9054 /// new specialization/instantiation will have any effect.
9055 ///
9056 /// \param NewLoc the location of the new explicit specialization or
9057 /// instantiation.
9058 ///
9059 /// \param NewTSK the kind of the new explicit specialization or instantiation.
9060 ///
9061 /// \param PrevDecl the previous declaration of the entity.
9062 ///
9063 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
9064 ///
9065 /// \param PrevPointOfInstantiation if valid, indicates where the previous
9066 /// declaration was instantiated (either implicitly or explicitly).
9067 ///
9068 /// \param HasNoEffect will be set to true to indicate that the new
9069 /// specialization or instantiation has no effect and should be ignored.
9070 ///
9071 /// \returns true if there was an error that should prevent the introduction of
9072 /// the new declaration into the AST, false otherwise.
9073 bool
CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,TemplateSpecializationKind NewTSK,NamedDecl * PrevDecl,TemplateSpecializationKind PrevTSK,SourceLocation PrevPointOfInstantiation,bool & HasNoEffect)9074 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9075                                              TemplateSpecializationKind NewTSK,
9076                                              NamedDecl *PrevDecl,
9077                                              TemplateSpecializationKind PrevTSK,
9078                                         SourceLocation PrevPointOfInstantiation,
9079                                              bool &HasNoEffect) {
9080   HasNoEffect = false;
9081 
9082   switch (NewTSK) {
9083   case TSK_Undeclared:
9084   case TSK_ImplicitInstantiation:
9085     assert(
9086         (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9087         "previous declaration must be implicit!");
9088     return false;
9089 
9090   case TSK_ExplicitSpecialization:
9091     switch (PrevTSK) {
9092     case TSK_Undeclared:
9093     case TSK_ExplicitSpecialization:
9094       // Okay, we're just specializing something that is either already
9095       // explicitly specialized or has merely been mentioned without any
9096       // instantiation.
9097       return false;
9098 
9099     case TSK_ImplicitInstantiation:
9100       if (PrevPointOfInstantiation.isInvalid()) {
9101         // The declaration itself has not actually been instantiated, so it is
9102         // still okay to specialize it.
9103         StripImplicitInstantiation(
9104             PrevDecl,
9105             Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
9106         return false;
9107       }
9108       // Fall through
9109       [[fallthrough]];
9110 
9111     case TSK_ExplicitInstantiationDeclaration:
9112     case TSK_ExplicitInstantiationDefinition:
9113       assert((PrevTSK == TSK_ImplicitInstantiation ||
9114               PrevPointOfInstantiation.isValid()) &&
9115              "Explicit instantiation without point of instantiation?");
9116 
9117       // C++ [temp.expl.spec]p6:
9118       //   If a template, a member template or the member of a class template
9119       //   is explicitly specialized then that specialization shall be declared
9120       //   before the first use of that specialization that would cause an
9121       //   implicit instantiation to take place, in every translation unit in
9122       //   which such a use occurs; no diagnostic is required.
9123       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9124         // Is there any previous explicit specialization declaration?
9125         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
9126           return false;
9127       }
9128 
9129       Diag(NewLoc, diag::err_specialization_after_instantiation)
9130         << PrevDecl;
9131       Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9132         << (PrevTSK != TSK_ImplicitInstantiation);
9133 
9134       return true;
9135     }
9136     llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9137 
9138   case TSK_ExplicitInstantiationDeclaration:
9139     switch (PrevTSK) {
9140     case TSK_ExplicitInstantiationDeclaration:
9141       // This explicit instantiation declaration is redundant (that's okay).
9142       HasNoEffect = true;
9143       return false;
9144 
9145     case TSK_Undeclared:
9146     case TSK_ImplicitInstantiation:
9147       // We're explicitly instantiating something that may have already been
9148       // implicitly instantiated; that's fine.
9149       return false;
9150 
9151     case TSK_ExplicitSpecialization:
9152       // C++0x [temp.explicit]p4:
9153       //   For a given set of template parameters, if an explicit instantiation
9154       //   of a template appears after a declaration of an explicit
9155       //   specialization for that template, the explicit instantiation has no
9156       //   effect.
9157       HasNoEffect = true;
9158       return false;
9159 
9160     case TSK_ExplicitInstantiationDefinition:
9161       // C++0x [temp.explicit]p10:
9162       //   If an entity is the subject of both an explicit instantiation
9163       //   declaration and an explicit instantiation definition in the same
9164       //   translation unit, the definition shall follow the declaration.
9165       Diag(NewLoc,
9166            diag::err_explicit_instantiation_declaration_after_definition);
9167 
9168       // Explicit instantiations following a specialization have no effect and
9169       // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9170       // until a valid name loc is found.
9171       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9172            diag::note_explicit_instantiation_definition_here);
9173       HasNoEffect = true;
9174       return false;
9175     }
9176     llvm_unreachable("Unexpected TemplateSpecializationKind!");
9177 
9178   case TSK_ExplicitInstantiationDefinition:
9179     switch (PrevTSK) {
9180     case TSK_Undeclared:
9181     case TSK_ImplicitInstantiation:
9182       // We're explicitly instantiating something that may have already been
9183       // implicitly instantiated; that's fine.
9184       return false;
9185 
9186     case TSK_ExplicitSpecialization:
9187       // C++ DR 259, C++0x [temp.explicit]p4:
9188       //   For a given set of template parameters, if an explicit
9189       //   instantiation of a template appears after a declaration of
9190       //   an explicit specialization for that template, the explicit
9191       //   instantiation has no effect.
9192       Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9193         << PrevDecl;
9194       Diag(PrevDecl->getLocation(),
9195            diag::note_previous_template_specialization);
9196       HasNoEffect = true;
9197       return false;
9198 
9199     case TSK_ExplicitInstantiationDeclaration:
9200       // We're explicitly instantiating a definition for something for which we
9201       // were previously asked to suppress instantiations. That's fine.
9202 
9203       // C++0x [temp.explicit]p4:
9204       //   For a given set of template parameters, if an explicit instantiation
9205       //   of a template appears after a declaration of an explicit
9206       //   specialization for that template, the explicit instantiation has no
9207       //   effect.
9208       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9209         // Is there any previous explicit specialization declaration?
9210         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
9211           HasNoEffect = true;
9212           break;
9213         }
9214       }
9215 
9216       return false;
9217 
9218     case TSK_ExplicitInstantiationDefinition:
9219       // C++0x [temp.spec]p5:
9220       //   For a given template and a given set of template-arguments,
9221       //     - an explicit instantiation definition shall appear at most once
9222       //       in a program,
9223 
9224       // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9225       Diag(NewLoc, (getLangOpts().MSVCCompat)
9226                        ? diag::ext_explicit_instantiation_duplicate
9227                        : diag::err_explicit_instantiation_duplicate)
9228           << PrevDecl;
9229       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9230            diag::note_previous_explicit_instantiation);
9231       HasNoEffect = true;
9232       return false;
9233     }
9234   }
9235 
9236   llvm_unreachable("Missing specialization/instantiation case?");
9237 }
9238 
9239 /// Perform semantic analysis for the given dependent function
9240 /// template specialization.
9241 ///
9242 /// The only possible way to get a dependent function template specialization
9243 /// is with a friend declaration, like so:
9244 ///
9245 /// \code
9246 ///   template \<class T> void foo(T);
9247 ///   template \<class T> class A {
9248 ///     friend void foo<>(T);
9249 ///   };
9250 /// \endcode
9251 ///
9252 /// There really isn't any useful analysis we can do here, so we
9253 /// just store the information.
9254 bool
CheckDependentFunctionTemplateSpecialization(FunctionDecl * FD,const TemplateArgumentListInfo & ExplicitTemplateArgs,LookupResult & Previous)9255 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
9256                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
9257                                                    LookupResult &Previous) {
9258   // Remove anything from Previous that isn't a function template in
9259   // the correct context.
9260   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9261   LookupResult::Filter F = Previous.makeFilter();
9262   enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9263   SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9264   while (F.hasNext()) {
9265     NamedDecl *D = F.next()->getUnderlyingDecl();
9266     if (!isa<FunctionTemplateDecl>(D)) {
9267       F.erase();
9268       DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9269       continue;
9270     }
9271 
9272     if (!FDLookupContext->InEnclosingNamespaceSetOf(
9273             D->getDeclContext()->getRedeclContext())) {
9274       F.erase();
9275       DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9276       continue;
9277     }
9278   }
9279   F.done();
9280 
9281   if (Previous.empty()) {
9282     Diag(FD->getLocation(),
9283          diag::err_dependent_function_template_spec_no_match);
9284     for (auto &P : DiscardedCandidates)
9285       Diag(P.second->getLocation(),
9286            diag::note_dependent_function_template_spec_discard_reason)
9287           << P.first;
9288     return true;
9289   }
9290 
9291   FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
9292                                          ExplicitTemplateArgs);
9293   return false;
9294 }
9295 
9296 /// Perform semantic analysis for the given function template
9297 /// specialization.
9298 ///
9299 /// This routine performs all of the semantic analysis required for an
9300 /// explicit function template specialization. On successful completion,
9301 /// the function declaration \p FD will become a function template
9302 /// specialization.
9303 ///
9304 /// \param FD the function declaration, which will be updated to become a
9305 /// function template specialization.
9306 ///
9307 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
9308 /// if any. Note that this may be valid info even when 0 arguments are
9309 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
9310 /// as it anyway contains info on the angle brackets locations.
9311 ///
9312 /// \param Previous the set of declarations that may be specialized by
9313 /// this function specialization.
9314 ///
9315 /// \param QualifiedFriend whether this is a lookup for a qualified friend
9316 /// declaration with no explicit template argument list that might be
9317 /// befriending a function template specialization.
CheckFunctionTemplateSpecialization(FunctionDecl * FD,TemplateArgumentListInfo * ExplicitTemplateArgs,LookupResult & Previous,bool QualifiedFriend)9318 bool Sema::CheckFunctionTemplateSpecialization(
9319     FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9320     LookupResult &Previous, bool QualifiedFriend) {
9321   // The set of function template specializations that could match this
9322   // explicit function template specialization.
9323   UnresolvedSet<8> Candidates;
9324   TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9325                                             /*ForTakingAddress=*/false);
9326 
9327   llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9328       ConvertedTemplateArgs;
9329 
9330   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9331   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9332          I != E; ++I) {
9333     NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9334     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9335       // Only consider templates found within the same semantic lookup scope as
9336       // FD.
9337       if (!FDLookupContext->InEnclosingNamespaceSetOf(
9338                                 Ovl->getDeclContext()->getRedeclContext()))
9339         continue;
9340 
9341       // When matching a constexpr member function template specialization
9342       // against the primary template, we don't yet know whether the
9343       // specialization has an implicit 'const' (because we don't know whether
9344       // it will be a static member function until we know which template it
9345       // specializes), so adjust it now assuming it specializes this template.
9346       QualType FT = FD->getType();
9347       if (FD->isConstexpr()) {
9348         CXXMethodDecl *OldMD =
9349           dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9350         if (OldMD && OldMD->isConst()) {
9351           const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9352           FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9353           EPI.TypeQuals.addConst();
9354           FT = Context.getFunctionType(FPT->getReturnType(),
9355                                        FPT->getParamTypes(), EPI);
9356         }
9357       }
9358 
9359       TemplateArgumentListInfo Args;
9360       if (ExplicitTemplateArgs)
9361         Args = *ExplicitTemplateArgs;
9362 
9363       // C++ [temp.expl.spec]p11:
9364       //   A trailing template-argument can be left unspecified in the
9365       //   template-id naming an explicit function template specialization
9366       //   provided it can be deduced from the function argument type.
9367       // Perform template argument deduction to determine whether we may be
9368       // specializing this template.
9369       // FIXME: It is somewhat wasteful to build
9370       TemplateDeductionInfo Info(FailedCandidates.getLocation());
9371       FunctionDecl *Specialization = nullptr;
9372       if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9373               cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9374               ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
9375               Info)) {
9376         // Template argument deduction failed; record why it failed, so
9377         // that we can provide nifty diagnostics.
9378         FailedCandidates.addCandidate().set(
9379             I.getPair(), FunTmpl->getTemplatedDecl(),
9380             MakeDeductionFailureInfo(Context, TDK, Info));
9381         (void)TDK;
9382         continue;
9383       }
9384 
9385       // Target attributes are part of the cuda function signature, so
9386       // the deduced template's cuda target must match that of the
9387       // specialization.  Given that C++ template deduction does not
9388       // take target attributes into account, we reject candidates
9389       // here that have a different target.
9390       if (LangOpts.CUDA &&
9391           IdentifyCUDATarget(Specialization,
9392                              /* IgnoreImplicitHDAttr = */ true) !=
9393               IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9394         FailedCandidates.addCandidate().set(
9395             I.getPair(), FunTmpl->getTemplatedDecl(),
9396             MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9397         continue;
9398       }
9399 
9400       // Record this candidate.
9401       if (ExplicitTemplateArgs)
9402         ConvertedTemplateArgs[Specialization] = std::move(Args);
9403       Candidates.addDecl(Specialization, I.getAccess());
9404     }
9405   }
9406 
9407   // For a qualified friend declaration (with no explicit marker to indicate
9408   // that a template specialization was intended), note all (template and
9409   // non-template) candidates.
9410   if (QualifiedFriend && Candidates.empty()) {
9411     Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9412         << FD->getDeclName() << FDLookupContext;
9413     // FIXME: We should form a single candidate list and diagnose all
9414     // candidates at once, to get proper sorting and limiting.
9415     for (auto *OldND : Previous) {
9416       if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9417         NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9418     }
9419     FailedCandidates.NoteCandidates(*this, FD->getLocation());
9420     return true;
9421   }
9422 
9423   // Find the most specialized function template.
9424   UnresolvedSetIterator Result = getMostSpecialized(
9425       Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9426       PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9427       PDiag(diag::err_function_template_spec_ambiguous)
9428           << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9429       PDiag(diag::note_function_template_spec_matched));
9430 
9431   if (Result == Candidates.end())
9432     return true;
9433 
9434   // Ignore access information;  it doesn't figure into redeclaration checking.
9435   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
9436 
9437   FunctionTemplateSpecializationInfo *SpecInfo
9438     = Specialization->getTemplateSpecializationInfo();
9439   assert(SpecInfo && "Function template specialization info missing?");
9440 
9441   // Note: do not overwrite location info if previous template
9442   // specialization kind was explicit.
9443   TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9444   if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9445     Specialization->setLocation(FD->getLocation());
9446     Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9447     // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9448     // function can differ from the template declaration with respect to
9449     // the constexpr specifier.
9450     // FIXME: We need an update record for this AST mutation.
9451     // FIXME: What if there are multiple such prior declarations (for instance,
9452     // from different modules)?
9453     Specialization->setConstexprKind(FD->getConstexprKind());
9454   }
9455 
9456   // FIXME: Check if the prior specialization has a point of instantiation.
9457   // If so, we have run afoul of .
9458 
9459   // If this is a friend declaration, then we're not really declaring
9460   // an explicit specialization.
9461   bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9462 
9463   // Check the scope of this explicit specialization.
9464   if (!isFriend &&
9465       CheckTemplateSpecializationScope(*this,
9466                                        Specialization->getPrimaryTemplate(),
9467                                        Specialization, FD->getLocation(),
9468                                        false))
9469     return true;
9470 
9471   // C++ [temp.expl.spec]p6:
9472   //   If a template, a member template or the member of a class template is
9473   //   explicitly specialized then that specialization shall be declared
9474   //   before the first use of that specialization that would cause an implicit
9475   //   instantiation to take place, in every translation unit in which such a
9476   //   use occurs; no diagnostic is required.
9477   bool HasNoEffect = false;
9478   if (!isFriend &&
9479       CheckSpecializationInstantiationRedecl(FD->getLocation(),
9480                                              TSK_ExplicitSpecialization,
9481                                              Specialization,
9482                                    SpecInfo->getTemplateSpecializationKind(),
9483                                          SpecInfo->getPointOfInstantiation(),
9484                                              HasNoEffect))
9485     return true;
9486 
9487   // Mark the prior declaration as an explicit specialization, so that later
9488   // clients know that this is an explicit specialization.
9489   if (!isFriend) {
9490     // Since explicit specializations do not inherit '=delete' from their
9491     // primary function template - check if the 'specialization' that was
9492     // implicitly generated (during template argument deduction for partial
9493     // ordering) from the most specialized of all the function templates that
9494     // 'FD' could have been specializing, has a 'deleted' definition.  If so,
9495     // first check that it was implicitly generated during template argument
9496     // deduction by making sure it wasn't referenced, and then reset the deleted
9497     // flag to not-deleted, so that we can inherit that information from 'FD'.
9498     if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9499         !Specialization->getCanonicalDecl()->isReferenced()) {
9500       // FIXME: This assert will not hold in the presence of modules.
9501       assert(
9502           Specialization->getCanonicalDecl() == Specialization &&
9503           "This must be the only existing declaration of this specialization");
9504       // FIXME: We need an update record for this AST mutation.
9505       Specialization->setDeletedAsWritten(false);
9506     }
9507     // FIXME: We need an update record for this AST mutation.
9508     SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9509     MarkUnusedFileScopedDecl(Specialization);
9510   }
9511 
9512   // Turn the given function declaration into a function template
9513   // specialization, with the template arguments from the previous
9514   // specialization.
9515   // Take copies of (semantic and syntactic) template argument lists.
9516   const TemplateArgumentList* TemplArgs = new (Context)
9517     TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
9518   FD->setFunctionTemplateSpecialization(
9519       Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9520       SpecInfo->getTemplateSpecializationKind(),
9521       ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9522 
9523   // A function template specialization inherits the target attributes
9524   // of its template.  (We require the attributes explicitly in the
9525   // code to match, but a template may have implicit attributes by
9526   // virtue e.g. of being constexpr, and it passes these implicit
9527   // attributes on to its specializations.)
9528   if (LangOpts.CUDA)
9529     inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
9530 
9531   // The "previous declaration" for this function template specialization is
9532   // the prior function template specialization.
9533   Previous.clear();
9534   Previous.addDecl(Specialization);
9535   return false;
9536 }
9537 
9538 /// Perform semantic analysis for the given non-template member
9539 /// specialization.
9540 ///
9541 /// This routine performs all of the semantic analysis required for an
9542 /// explicit member function specialization. On successful completion,
9543 /// the function declaration \p FD will become a member function
9544 /// specialization.
9545 ///
9546 /// \param Member the member declaration, which will be updated to become a
9547 /// specialization.
9548 ///
9549 /// \param Previous the set of declarations, one of which may be specialized
9550 /// by this function specialization;  the set will be modified to contain the
9551 /// redeclared member.
9552 bool
CheckMemberSpecialization(NamedDecl * Member,LookupResult & Previous)9553 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9554   assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
9555 
9556   // Try to find the member we are instantiating.
9557   NamedDecl *FoundInstantiation = nullptr;
9558   NamedDecl *Instantiation = nullptr;
9559   NamedDecl *InstantiatedFrom = nullptr;
9560   MemberSpecializationInfo *MSInfo = nullptr;
9561 
9562   if (Previous.empty()) {
9563     // Nowhere to look anyway.
9564   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9565     for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9566            I != E; ++I) {
9567       NamedDecl *D = (*I)->getUnderlyingDecl();
9568       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
9569         QualType Adjusted = Function->getType();
9570         if (!hasExplicitCallingConv(Adjusted))
9571           Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9572         // This doesn't handle deduced return types, but both function
9573         // declarations should be undeduced at this point.
9574         if (Context.hasSameType(Adjusted, Method->getType())) {
9575           FoundInstantiation = *I;
9576           Instantiation = Method;
9577           InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
9578           MSInfo = Method->getMemberSpecializationInfo();
9579           break;
9580         }
9581       }
9582     }
9583   } else if (isa<VarDecl>(Member)) {
9584     VarDecl *PrevVar;
9585     if (Previous.isSingleResult() &&
9586         (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9587       if (PrevVar->isStaticDataMember()) {
9588         FoundInstantiation = Previous.getRepresentativeDecl();
9589         Instantiation = PrevVar;
9590         InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9591         MSInfo = PrevVar->getMemberSpecializationInfo();
9592       }
9593   } else if (isa<RecordDecl>(Member)) {
9594     CXXRecordDecl *PrevRecord;
9595     if (Previous.isSingleResult() &&
9596         (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9597       FoundInstantiation = Previous.getRepresentativeDecl();
9598       Instantiation = PrevRecord;
9599       InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9600       MSInfo = PrevRecord->getMemberSpecializationInfo();
9601     }
9602   } else if (isa<EnumDecl>(Member)) {
9603     EnumDecl *PrevEnum;
9604     if (Previous.isSingleResult() &&
9605         (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9606       FoundInstantiation = Previous.getRepresentativeDecl();
9607       Instantiation = PrevEnum;
9608       InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9609       MSInfo = PrevEnum->getMemberSpecializationInfo();
9610     }
9611   }
9612 
9613   if (!Instantiation) {
9614     // There is no previous declaration that matches. Since member
9615     // specializations are always out-of-line, the caller will complain about
9616     // this mismatch later.
9617     return false;
9618   }
9619 
9620   // A member specialization in a friend declaration isn't really declaring
9621   // an explicit specialization, just identifying a specific (possibly implicit)
9622   // specialization. Don't change the template specialization kind.
9623   //
9624   // FIXME: Is this really valid? Other compilers reject.
9625   if (Member->getFriendObjectKind() != Decl::FOK_None) {
9626     // Preserve instantiation information.
9627     if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9628       cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9629                                       cast<CXXMethodDecl>(InstantiatedFrom),
9630         cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
9631     } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9632       cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9633                                       cast<CXXRecordDecl>(InstantiatedFrom),
9634         cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
9635     }
9636 
9637     Previous.clear();
9638     Previous.addDecl(FoundInstantiation);
9639     return false;
9640   }
9641 
9642   // Make sure that this is a specialization of a member.
9643   if (!InstantiatedFrom) {
9644     Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9645       << Member;
9646     Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9647     return true;
9648   }
9649 
9650   // C++ [temp.expl.spec]p6:
9651   //   If a template, a member template or the member of a class template is
9652   //   explicitly specialized then that specialization shall be declared
9653   //   before the first use of that specialization that would cause an implicit
9654   //   instantiation to take place, in every translation unit in which such a
9655   //   use occurs; no diagnostic is required.
9656   assert(MSInfo && "Member specialization info missing?");
9657 
9658   bool HasNoEffect = false;
9659   if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
9660                                              TSK_ExplicitSpecialization,
9661                                              Instantiation,
9662                                      MSInfo->getTemplateSpecializationKind(),
9663                                            MSInfo->getPointOfInstantiation(),
9664                                              HasNoEffect))
9665     return true;
9666 
9667   // Check the scope of this explicit specialization.
9668   if (CheckTemplateSpecializationScope(*this,
9669                                        InstantiatedFrom,
9670                                        Instantiation, Member->getLocation(),
9671                                        false))
9672     return true;
9673 
9674   // Note that this member specialization is an "instantiation of" the
9675   // corresponding member of the original template.
9676   if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9677     FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9678     if (InstantiationFunction->getTemplateSpecializationKind() ==
9679           TSK_ImplicitInstantiation) {
9680       // Explicit specializations of member functions of class templates do not
9681       // inherit '=delete' from the member function they are specializing.
9682       if (InstantiationFunction->isDeleted()) {
9683         // FIXME: This assert will not hold in the presence of modules.
9684         assert(InstantiationFunction->getCanonicalDecl() ==
9685                InstantiationFunction);
9686         // FIXME: We need an update record for this AST mutation.
9687         InstantiationFunction->setDeletedAsWritten(false);
9688       }
9689     }
9690 
9691     MemberFunction->setInstantiationOfMemberFunction(
9692         cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9693   } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9694     MemberVar->setInstantiationOfStaticDataMember(
9695         cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9696   } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9697     MemberClass->setInstantiationOfMemberClass(
9698         cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9699   } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9700     MemberEnum->setInstantiationOfMemberEnum(
9701         cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9702   } else {
9703     llvm_unreachable("unknown member specialization kind");
9704   }
9705 
9706   // Save the caller the trouble of having to figure out which declaration
9707   // this specialization matches.
9708   Previous.clear();
9709   Previous.addDecl(FoundInstantiation);
9710   return false;
9711 }
9712 
9713 /// Complete the explicit specialization of a member of a class template by
9714 /// updating the instantiated member to be marked as an explicit specialization.
9715 ///
9716 /// \param OrigD The member declaration instantiated from the template.
9717 /// \param Loc The location of the explicit specialization of the member.
9718 template<typename DeclT>
completeMemberSpecializationImpl(Sema & S,DeclT * OrigD,SourceLocation Loc)9719 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9720                                              SourceLocation Loc) {
9721   if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9722     return;
9723 
9724   // FIXME: Inform AST mutation listeners of this AST mutation.
9725   // FIXME: If there are multiple in-class declarations of the member (from
9726   // multiple modules, or a declaration and later definition of a member type),
9727   // should we update all of them?
9728   OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9729   OrigD->setLocation(Loc);
9730 }
9731 
CompleteMemberSpecialization(NamedDecl * Member,LookupResult & Previous)9732 void Sema::CompleteMemberSpecialization(NamedDecl *Member,
9733                                         LookupResult &Previous) {
9734   NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9735   if (Instantiation == Member)
9736     return;
9737 
9738   if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9739     completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9740   else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9741     completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9742   else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9743     completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9744   else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9745     completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9746   else
9747     llvm_unreachable("unknown member specialization kind");
9748 }
9749 
9750 /// Check the scope of an explicit instantiation.
9751 ///
9752 /// \returns true if a serious error occurs, false otherwise.
CheckExplicitInstantiationScope(Sema & S,NamedDecl * D,SourceLocation InstLoc,bool WasQualifiedName)9753 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
9754                                             SourceLocation InstLoc,
9755                                             bool WasQualifiedName) {
9756   DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
9757   DeclContext *CurContext = S.CurContext->getRedeclContext();
9758 
9759   if (CurContext->isRecord()) {
9760     S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9761       << D;
9762     return true;
9763   }
9764 
9765   // C++11 [temp.explicit]p3:
9766   //   An explicit instantiation shall appear in an enclosing namespace of its
9767   //   template. If the name declared in the explicit instantiation is an
9768   //   unqualified name, the explicit instantiation shall appear in the
9769   //   namespace where its template is declared or, if that namespace is inline
9770   //   (7.3.1), any namespace from its enclosing namespace set.
9771   //
9772   // This is DR275, which we do not retroactively apply to C++98/03.
9773   if (WasQualifiedName) {
9774     if (CurContext->Encloses(OrigContext))
9775       return false;
9776   } else {
9777     if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9778       return false;
9779   }
9780 
9781   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9782     if (WasQualifiedName)
9783       S.Diag(InstLoc,
9784              S.getLangOpts().CPlusPlus11?
9785                diag::err_explicit_instantiation_out_of_scope :
9786                diag::warn_explicit_instantiation_out_of_scope_0x)
9787         << D << NS;
9788     else
9789       S.Diag(InstLoc,
9790              S.getLangOpts().CPlusPlus11?
9791                diag::err_explicit_instantiation_unqualified_wrong_namespace :
9792                diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9793         << D << NS;
9794   } else
9795     S.Diag(InstLoc,
9796            S.getLangOpts().CPlusPlus11?
9797              diag::err_explicit_instantiation_must_be_global :
9798              diag::warn_explicit_instantiation_must_be_global_0x)
9799       << D;
9800   S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9801   return false;
9802 }
9803 
9804 /// Common checks for whether an explicit instantiation of \p D is valid.
CheckExplicitInstantiation(Sema & S,NamedDecl * D,SourceLocation InstLoc,bool WasQualifiedName,TemplateSpecializationKind TSK)9805 static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
9806                                        SourceLocation InstLoc,
9807                                        bool WasQualifiedName,
9808                                        TemplateSpecializationKind TSK) {
9809   // C++ [temp.explicit]p13:
9810   //   An explicit instantiation declaration shall not name a specialization of
9811   //   a template with internal linkage.
9812   if (TSK == TSK_ExplicitInstantiationDeclaration &&
9813       D->getFormalLinkage() == InternalLinkage) {
9814     S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9815     return true;
9816   }
9817 
9818   // C++11 [temp.explicit]p3: [DR 275]
9819   //   An explicit instantiation shall appear in an enclosing namespace of its
9820   //   template.
9821   if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9822     return true;
9823 
9824   return false;
9825 }
9826 
9827 /// Determine whether the given scope specifier has a template-id in it.
ScopeSpecifierHasTemplateId(const CXXScopeSpec & SS)9828 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
9829   if (!SS.isSet())
9830     return false;
9831 
9832   // C++11 [temp.explicit]p3:
9833   //   If the explicit instantiation is for a member function, a member class
9834   //   or a static data member of a class template specialization, the name of
9835   //   the class template specialization in the qualified-id for the member
9836   //   name shall be a simple-template-id.
9837   //
9838   // C++98 has the same restriction, just worded differently.
9839   for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9840        NNS = NNS->getPrefix())
9841     if (const Type *T = NNS->getAsType())
9842       if (isa<TemplateSpecializationType>(T))
9843         return true;
9844 
9845   return false;
9846 }
9847 
9848 /// Make a dllexport or dllimport attr on a class template specialization take
9849 /// effect.
dllExportImportClassTemplateSpecialization(Sema & S,ClassTemplateSpecializationDecl * Def)9850 static void dllExportImportClassTemplateSpecialization(
9851     Sema &S, ClassTemplateSpecializationDecl *Def) {
9852   auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
9853   assert(A && "dllExportImportClassTemplateSpecialization called "
9854               "on Def without dllexport or dllimport");
9855 
9856   // We reject explicit instantiations in class scope, so there should
9857   // never be any delayed exported classes to worry about.
9858   assert(S.DelayedDllExportClasses.empty() &&
9859          "delayed exports present at explicit instantiation");
9860   S.checkClassLevelDLLAttribute(Def);
9861 
9862   // Propagate attribute to base class templates.
9863   for (auto &B : Def->bases()) {
9864     if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9865             B.getType()->getAsCXXRecordDecl()))
9866       S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
9867   }
9868 
9869   S.referenceDLLExportedClassMethods();
9870 }
9871 
9872 // 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)9873 DeclResult Sema::ActOnExplicitInstantiation(
9874     Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9875     unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9876     TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9877     SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9878     SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9879   // Find the class template we're specializing
9880   TemplateName Name = TemplateD.get();
9881   TemplateDecl *TD = Name.getAsTemplateDecl();
9882   // Check that the specialization uses the same tag kind as the
9883   // original template.
9884   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9885   assert(Kind != TTK_Enum &&
9886          "Invalid enum tag in class template explicit instantiation!");
9887 
9888   ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
9889 
9890   if (!ClassTemplate) {
9891     NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9892     Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
9893     Diag(TD->getLocation(), diag::note_previous_use);
9894     return true;
9895   }
9896 
9897   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9898                                     Kind, /*isDefinition*/false, KWLoc,
9899                                     ClassTemplate->getIdentifier())) {
9900     Diag(KWLoc, diag::err_use_with_wrong_tag)
9901       << ClassTemplate
9902       << FixItHint::CreateReplacement(KWLoc,
9903                             ClassTemplate->getTemplatedDecl()->getKindName());
9904     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9905          diag::note_previous_use);
9906     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9907   }
9908 
9909   // C++0x [temp.explicit]p2:
9910   //   There are two forms of explicit instantiation: an explicit instantiation
9911   //   definition and an explicit instantiation declaration. An explicit
9912   //   instantiation declaration begins with the extern keyword. [...]
9913   TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9914                                        ? TSK_ExplicitInstantiationDefinition
9915                                        : TSK_ExplicitInstantiationDeclaration;
9916 
9917   if (TSK == TSK_ExplicitInstantiationDeclaration &&
9918       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9919     // Check for dllexport class template instantiation declarations,
9920     // except for MinGW mode.
9921     for (const ParsedAttr &AL : Attr) {
9922       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9923         Diag(ExternLoc,
9924              diag::warn_attribute_dllexport_explicit_instantiation_decl);
9925         Diag(AL.getLoc(), diag::note_attribute);
9926         break;
9927       }
9928     }
9929 
9930     if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9931       Diag(ExternLoc,
9932            diag::warn_attribute_dllexport_explicit_instantiation_decl);
9933       Diag(A->getLocation(), diag::note_attribute);
9934     }
9935   }
9936 
9937   // In MSVC mode, dllimported explicit instantiation definitions are treated as
9938   // instantiation declarations for most purposes.
9939   bool DLLImportExplicitInstantiationDef = false;
9940   if (TSK == TSK_ExplicitInstantiationDefinition &&
9941       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9942     // Check for dllimport class template instantiation definitions.
9943     bool DLLImport =
9944         ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9945     for (const ParsedAttr &AL : Attr) {
9946       if (AL.getKind() == ParsedAttr::AT_DLLImport)
9947         DLLImport = true;
9948       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9949         // dllexport trumps dllimport here.
9950         DLLImport = false;
9951         break;
9952       }
9953     }
9954     if (DLLImport) {
9955       TSK = TSK_ExplicitInstantiationDeclaration;
9956       DLLImportExplicitInstantiationDef = true;
9957     }
9958   }
9959 
9960   // Translate the parser's template argument list in our AST format.
9961   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9962   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9963 
9964   // Check that the template argument list is well-formed for this
9965   // template.
9966   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
9967   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
9968                                 false, SugaredConverted, CanonicalConverted,
9969                                 /*UpdateArgsWithConversions=*/true))
9970     return true;
9971 
9972   // Find the class template specialization declaration that
9973   // corresponds to these arguments.
9974   void *InsertPos = nullptr;
9975   ClassTemplateSpecializationDecl *PrevDecl =
9976       ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
9977 
9978   TemplateSpecializationKind PrevDecl_TSK
9979     = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9980 
9981   if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9982       Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9983     // Check for dllexport class template instantiation definitions in MinGW
9984     // mode, if a previous declaration of the instantiation was seen.
9985     for (const ParsedAttr &AL : Attr) {
9986       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9987         Diag(AL.getLoc(),
9988              diag::warn_attribute_dllexport_explicit_instantiation_def);
9989         break;
9990       }
9991     }
9992   }
9993 
9994   if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9995                                  SS.isSet(), TSK))
9996     return true;
9997 
9998   ClassTemplateSpecializationDecl *Specialization = nullptr;
9999 
10000   bool HasNoEffect = false;
10001   if (PrevDecl) {
10002     if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10003                                                PrevDecl, PrevDecl_TSK,
10004                                             PrevDecl->getPointOfInstantiation(),
10005                                                HasNoEffect))
10006       return PrevDecl;
10007 
10008     // Even though HasNoEffect == true means that this explicit instantiation
10009     // has no effect on semantics, we go on to put its syntax in the AST.
10010 
10011     if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10012         PrevDecl_TSK == TSK_Undeclared) {
10013       // Since the only prior class template specialization with these
10014       // arguments was referenced but not declared, reuse that
10015       // declaration node as our own, updating the source location
10016       // for the template name to reflect our new declaration.
10017       // (Other source locations will be updated later.)
10018       Specialization = PrevDecl;
10019       Specialization->setLocation(TemplateNameLoc);
10020       PrevDecl = nullptr;
10021     }
10022 
10023     if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10024         DLLImportExplicitInstantiationDef) {
10025       // The new specialization might add a dllimport attribute.
10026       HasNoEffect = false;
10027     }
10028   }
10029 
10030   if (!Specialization) {
10031     // Create a new class template specialization declaration node for
10032     // this explicit specialization.
10033     Specialization = ClassTemplateSpecializationDecl::Create(
10034         Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10035         ClassTemplate, CanonicalConverted, PrevDecl);
10036     SetNestedNameSpecifier(*this, Specialization, SS);
10037 
10038     if (!HasNoEffect && !PrevDecl) {
10039       // Insert the new specialization.
10040       ClassTemplate->AddSpecialization(Specialization, InsertPos);
10041     }
10042   }
10043 
10044   // Build the fully-sugared type for this explicit instantiation as
10045   // the user wrote in the explicit instantiation itself. This means
10046   // that we'll pretty-print the type retrieved from the
10047   // specialization's declaration the way that the user actually wrote
10048   // the explicit instantiation, rather than formatting the name based
10049   // on the "canonical" representation used to store the template
10050   // arguments in the specialization.
10051   TypeSourceInfo *WrittenTy
10052     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
10053                                                 TemplateArgs,
10054                                   Context.getTypeDeclType(Specialization));
10055   Specialization->setTypeAsWritten(WrittenTy);
10056 
10057   // Set source locations for keywords.
10058   Specialization->setExternLoc(ExternLoc);
10059   Specialization->setTemplateKeywordLoc(TemplateLoc);
10060   Specialization->setBraceRange(SourceRange());
10061 
10062   bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10063   ProcessDeclAttributeList(S, Specialization, Attr);
10064 
10065   // Add the explicit instantiation into its lexical context. However,
10066   // since explicit instantiations are never found by name lookup, we
10067   // just put it into the declaration context directly.
10068   Specialization->setLexicalDeclContext(CurContext);
10069   CurContext->addDecl(Specialization);
10070 
10071   // Syntax is now OK, so return if it has no other effect on semantics.
10072   if (HasNoEffect) {
10073     // Set the template specialization kind.
10074     Specialization->setTemplateSpecializationKind(TSK);
10075     return Specialization;
10076   }
10077 
10078   // C++ [temp.explicit]p3:
10079   //   A definition of a class template or class member template
10080   //   shall be in scope at the point of the explicit instantiation of
10081   //   the class template or class member template.
10082   //
10083   // This check comes when we actually try to perform the
10084   // instantiation.
10085   ClassTemplateSpecializationDecl *Def
10086     = cast_or_null<ClassTemplateSpecializationDecl>(
10087                                               Specialization->getDefinition());
10088   if (!Def)
10089     InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
10090   else if (TSK == TSK_ExplicitInstantiationDefinition) {
10091     MarkVTableUsed(TemplateNameLoc, Specialization, true);
10092     Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10093   }
10094 
10095   // Instantiate the members of this class template specialization.
10096   Def = cast_or_null<ClassTemplateSpecializationDecl>(
10097                                        Specialization->getDefinition());
10098   if (Def) {
10099     TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10100     // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10101     // TSK_ExplicitInstantiationDefinition
10102     if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10103         (TSK == TSK_ExplicitInstantiationDefinition ||
10104          DLLImportExplicitInstantiationDef)) {
10105       // FIXME: Need to notify the ASTMutationListener that we did this.
10106       Def->setTemplateSpecializationKind(TSK);
10107 
10108       if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10109           (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
10110            !Context.getTargetInfo().getTriple().isPS())) {
10111         // An explicit instantiation definition can add a dll attribute to a
10112         // template with a previous instantiation declaration. MinGW doesn't
10113         // allow this.
10114         auto *A = cast<InheritableAttr>(
10115             getDLLAttr(Specialization)->clone(getASTContext()));
10116         A->setInherited(true);
10117         Def->addAttr(A);
10118         dllExportImportClassTemplateSpecialization(*this, Def);
10119       }
10120     }
10121 
10122     // Fix a TSK_ImplicitInstantiation followed by a
10123     // TSK_ExplicitInstantiationDefinition
10124     bool NewlyDLLExported =
10125         !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10126     if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10127         (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
10128          !Context.getTargetInfo().getTriple().isPS())) {
10129       // An explicit instantiation definition can add a dll attribute to a
10130       // template with a previous implicit instantiation. MinGW doesn't allow
10131       // this. We limit clang to only adding dllexport, to avoid potentially
10132       // strange codegen behavior. For example, if we extend this conditional
10133       // to dllimport, and we have a source file calling a method on an
10134       // implicitly instantiated template class instance and then declaring a
10135       // dllimport explicit instantiation definition for the same template
10136       // class, the codegen for the method call will not respect the dllimport,
10137       // while it will with cl. The Def will already have the DLL attribute,
10138       // since the Def and Specialization will be the same in the case of
10139       // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10140       // attribute to the Specialization; we just need to make it take effect.
10141       assert(Def == Specialization &&
10142              "Def and Specialization should match for implicit instantiation");
10143       dllExportImportClassTemplateSpecialization(*this, Def);
10144     }
10145 
10146     // In MinGW mode, export the template instantiation if the declaration
10147     // was marked dllexport.
10148     if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10149         Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10150         PrevDecl->hasAttr<DLLExportAttr>()) {
10151       dllExportImportClassTemplateSpecialization(*this, Def);
10152     }
10153 
10154     if (Def->hasAttr<MSInheritanceAttr>()) {
10155       Specialization->addAttr(Def->getAttr<MSInheritanceAttr>());
10156       Consumer.AssignInheritanceModel(Specialization);
10157     }
10158 
10159     // Set the template specialization kind. Make sure it is set before
10160     // instantiating the members which will trigger ASTConsumer callbacks.
10161     Specialization->setTemplateSpecializationKind(TSK);
10162     InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10163   } else {
10164 
10165     // Set the template specialization kind.
10166     Specialization->setTemplateSpecializationKind(TSK);
10167   }
10168 
10169   return Specialization;
10170 }
10171 
10172 // Explicit instantiation of a member class of a class template.
10173 DeclResult
ActOnExplicitInstantiation(Scope * S,SourceLocation ExternLoc,SourceLocation TemplateLoc,unsigned TagSpec,SourceLocation KWLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,const ParsedAttributesView & Attr)10174 Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10175                                  SourceLocation TemplateLoc, unsigned TagSpec,
10176                                  SourceLocation KWLoc, CXXScopeSpec &SS,
10177                                  IdentifierInfo *Name, SourceLocation NameLoc,
10178                                  const ParsedAttributesView &Attr) {
10179 
10180   bool Owned = false;
10181   bool IsDependent = false;
10182   Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name,
10183                NameLoc, Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10184                MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10185                false, TypeResult(), /*IsTypeSpecifier*/ false,
10186                /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get();
10187   assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10188 
10189   if (!TagD)
10190     return true;
10191 
10192   TagDecl *Tag = cast<TagDecl>(TagD);
10193   assert(!Tag->isEnum() && "shouldn't see enumerations here");
10194 
10195   if (Tag->isInvalidDecl())
10196     return true;
10197 
10198   CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
10199   CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10200   if (!Pattern) {
10201     Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10202       << Context.getTypeDeclType(Record);
10203     Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10204     return true;
10205   }
10206 
10207   // C++0x [temp.explicit]p2:
10208   //   If the explicit instantiation is for a class or member class, the
10209   //   elaborated-type-specifier in the declaration shall include a
10210   //   simple-template-id.
10211   //
10212   // C++98 has the same restriction, just worded differently.
10213   if (!ScopeSpecifierHasTemplateId(SS))
10214     Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10215       << Record << SS.getRange();
10216 
10217   // C++0x [temp.explicit]p2:
10218   //   There are two forms of explicit instantiation: an explicit instantiation
10219   //   definition and an explicit instantiation declaration. An explicit
10220   //   instantiation declaration begins with the extern keyword. [...]
10221   TemplateSpecializationKind TSK
10222     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10223                            : TSK_ExplicitInstantiationDeclaration;
10224 
10225   CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10226 
10227   // Verify that it is okay to explicitly instantiate here.
10228   CXXRecordDecl *PrevDecl
10229     = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10230   if (!PrevDecl && Record->getDefinition())
10231     PrevDecl = Record;
10232   if (PrevDecl) {
10233     MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10234     bool HasNoEffect = false;
10235     assert(MSInfo && "No member specialization information?");
10236     if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10237                                                PrevDecl,
10238                                         MSInfo->getTemplateSpecializationKind(),
10239                                              MSInfo->getPointOfInstantiation(),
10240                                                HasNoEffect))
10241       return true;
10242     if (HasNoEffect)
10243       return TagD;
10244   }
10245 
10246   CXXRecordDecl *RecordDef
10247     = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10248   if (!RecordDef) {
10249     // C++ [temp.explicit]p3:
10250     //   A definition of a member class of a class template shall be in scope
10251     //   at the point of an explicit instantiation of the member class.
10252     CXXRecordDecl *Def
10253       = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10254     if (!Def) {
10255       Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10256         << 0 << Record->getDeclName() << Record->getDeclContext();
10257       Diag(Pattern->getLocation(), diag::note_forward_declaration)
10258         << Pattern;
10259       return true;
10260     } else {
10261       if (InstantiateClass(NameLoc, Record, Def,
10262                            getTemplateInstantiationArgs(Record),
10263                            TSK))
10264         return true;
10265 
10266       RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10267       if (!RecordDef)
10268         return true;
10269     }
10270   }
10271 
10272   // Instantiate all of the members of the class.
10273   InstantiateClassMembers(NameLoc, RecordDef,
10274                           getTemplateInstantiationArgs(Record), TSK);
10275 
10276   if (TSK == TSK_ExplicitInstantiationDefinition)
10277     MarkVTableUsed(NameLoc, RecordDef, true);
10278 
10279   // FIXME: We don't have any representation for explicit instantiations of
10280   // member classes. Such a representation is not needed for compilation, but it
10281   // should be available for clients that want to see all of the declarations in
10282   // the source code.
10283   return TagD;
10284 }
10285 
ActOnExplicitInstantiation(Scope * S,SourceLocation ExternLoc,SourceLocation TemplateLoc,Declarator & D)10286 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10287                                             SourceLocation ExternLoc,
10288                                             SourceLocation TemplateLoc,
10289                                             Declarator &D) {
10290   // Explicit instantiations always require a name.
10291   // TODO: check if/when DNInfo should replace Name.
10292   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10293   DeclarationName Name = NameInfo.getName();
10294   if (!Name) {
10295     if (!D.isInvalidType())
10296       Diag(D.getDeclSpec().getBeginLoc(),
10297            diag::err_explicit_instantiation_requires_name)
10298           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10299 
10300     return true;
10301   }
10302 
10303   // The scope passed in may not be a decl scope.  Zip up the scope tree until
10304   // we find one that is.
10305   while ((S->getFlags() & Scope::DeclScope) == 0 ||
10306          (S->getFlags() & Scope::TemplateParamScope) != 0)
10307     S = S->getParent();
10308 
10309   // Determine the type of the declaration.
10310   TypeSourceInfo *T = GetTypeForDeclarator(D, S);
10311   QualType R = T->getType();
10312   if (R.isNull())
10313     return true;
10314 
10315   // C++ [dcl.stc]p1:
10316   //   A storage-class-specifier shall not be specified in [...] an explicit
10317   //   instantiation (14.7.2) directive.
10318   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10319     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10320       << Name;
10321     return true;
10322   } else if (D.getDeclSpec().getStorageClassSpec()
10323                                                 != DeclSpec::SCS_unspecified) {
10324     // Complain about then remove the storage class specifier.
10325     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10326       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10327 
10328     D.getMutableDeclSpec().ClearStorageClassSpecs();
10329   }
10330 
10331   // C++0x [temp.explicit]p1:
10332   //   [...] An explicit instantiation of a function template shall not use the
10333   //   inline or constexpr specifiers.
10334   // Presumably, this also applies to member functions of class templates as
10335   // well.
10336   if (D.getDeclSpec().isInlineSpecified())
10337     Diag(D.getDeclSpec().getInlineSpecLoc(),
10338          getLangOpts().CPlusPlus11 ?
10339            diag::err_explicit_instantiation_inline :
10340            diag::warn_explicit_instantiation_inline_0x)
10341       << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10342   if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10343     // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10344     // not already specified.
10345     Diag(D.getDeclSpec().getConstexprSpecLoc(),
10346          diag::err_explicit_instantiation_constexpr);
10347 
10348   // A deduction guide is not on the list of entities that can be explicitly
10349   // instantiated.
10350   if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10351     Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10352         << /*explicit instantiation*/ 0;
10353     return true;
10354   }
10355 
10356   // C++0x [temp.explicit]p2:
10357   //   There are two forms of explicit instantiation: an explicit instantiation
10358   //   definition and an explicit instantiation declaration. An explicit
10359   //   instantiation declaration begins with the extern keyword. [...]
10360   TemplateSpecializationKind TSK
10361     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10362                            : TSK_ExplicitInstantiationDeclaration;
10363 
10364   LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10365   LookupParsedName(Previous, S, &D.getCXXScopeSpec());
10366 
10367   if (!R->isFunctionType()) {
10368     // C++ [temp.explicit]p1:
10369     //   A [...] static data member of a class template can be explicitly
10370     //   instantiated from the member definition associated with its class
10371     //   template.
10372     // C++1y [temp.explicit]p1:
10373     //   A [...] variable [...] template specialization can be explicitly
10374     //   instantiated from its template.
10375     if (Previous.isAmbiguous())
10376       return true;
10377 
10378     VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10379     VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10380 
10381     if (!PrevTemplate) {
10382       if (!Prev || !Prev->isStaticDataMember()) {
10383         // We expect to see a static data member here.
10384         Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10385             << Name;
10386         for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10387              P != PEnd; ++P)
10388           Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10389         return true;
10390       }
10391 
10392       if (!Prev->getInstantiatedFromStaticDataMember()) {
10393         // FIXME: Check for explicit specialization?
10394         Diag(D.getIdentifierLoc(),
10395              diag::err_explicit_instantiation_data_member_not_instantiated)
10396             << Prev;
10397         Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10398         // FIXME: Can we provide a note showing where this was declared?
10399         return true;
10400       }
10401     } else {
10402       // Explicitly instantiate a variable template.
10403 
10404       // C++1y [dcl.spec.auto]p6:
10405       //   ... A program that uses auto or decltype(auto) in a context not
10406       //   explicitly allowed in this section is ill-formed.
10407       //
10408       // This includes auto-typed variable template instantiations.
10409       if (R->isUndeducedType()) {
10410         Diag(T->getTypeLoc().getBeginLoc(),
10411              diag::err_auto_not_allowed_var_inst);
10412         return true;
10413       }
10414 
10415       if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10416         // C++1y [temp.explicit]p3:
10417         //   If the explicit instantiation is for a variable, the unqualified-id
10418         //   in the declaration shall be a template-id.
10419         Diag(D.getIdentifierLoc(),
10420              diag::err_explicit_instantiation_without_template_id)
10421           << PrevTemplate;
10422         Diag(PrevTemplate->getLocation(),
10423              diag::note_explicit_instantiation_here);
10424         return true;
10425       }
10426 
10427       // Translate the parser's template argument list into our AST format.
10428       TemplateArgumentListInfo TemplateArgs =
10429           makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10430 
10431       DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
10432                                           D.getIdentifierLoc(), TemplateArgs);
10433       if (Res.isInvalid())
10434         return true;
10435 
10436       if (!Res.isUsable()) {
10437         // We somehow specified dependent template arguments in an explicit
10438         // instantiation. This should probably only happen during error
10439         // recovery.
10440         Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10441         return true;
10442       }
10443 
10444       // Ignore access control bits, we don't need them for redeclaration
10445       // checking.
10446       Prev = cast<VarDecl>(Res.get());
10447     }
10448 
10449     // C++0x [temp.explicit]p2:
10450     //   If the explicit instantiation is for a member function, a member class
10451     //   or a static data member of a class template specialization, the name of
10452     //   the class template specialization in the qualified-id for the member
10453     //   name shall be a simple-template-id.
10454     //
10455     // C++98 has the same restriction, just worded differently.
10456     //
10457     // This does not apply to variable template specializations, where the
10458     // template-id is in the unqualified-id instead.
10459     if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10460       Diag(D.getIdentifierLoc(),
10461            diag::ext_explicit_instantiation_without_qualified_id)
10462         << Prev << D.getCXXScopeSpec().getRange();
10463 
10464     CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10465 
10466     // Verify that it is okay to explicitly instantiate here.
10467     TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10468     SourceLocation POI = Prev->getPointOfInstantiation();
10469     bool HasNoEffect = false;
10470     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
10471                                                PrevTSK, POI, HasNoEffect))
10472       return true;
10473 
10474     if (!HasNoEffect) {
10475       // Instantiate static data member or variable template.
10476       Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10477       // Merge attributes.
10478       ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10479       if (TSK == TSK_ExplicitInstantiationDefinition)
10480         InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
10481     }
10482 
10483     // Check the new variable specialization against the parsed input.
10484     if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10485       Diag(T->getTypeLoc().getBeginLoc(),
10486            diag::err_invalid_var_template_spec_type)
10487           << 0 << PrevTemplate << R << Prev->getType();
10488       Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10489           << 2 << PrevTemplate->getDeclName();
10490       return true;
10491     }
10492 
10493     // FIXME: Create an ExplicitInstantiation node?
10494     return (Decl*) nullptr;
10495   }
10496 
10497   // If the declarator is a template-id, translate the parser's template
10498   // argument list into our AST format.
10499   bool HasExplicitTemplateArgs = false;
10500   TemplateArgumentListInfo TemplateArgs;
10501   if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10502     TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10503     HasExplicitTemplateArgs = true;
10504   }
10505 
10506   // C++ [temp.explicit]p1:
10507   //   A [...] function [...] can be explicitly instantiated from its template.
10508   //   A member function [...] of a class template can be explicitly
10509   //  instantiated from the member definition associated with its class
10510   //  template.
10511   UnresolvedSet<8> TemplateMatches;
10512   FunctionDecl *NonTemplateMatch = nullptr;
10513   TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
10514   for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10515        P != PEnd; ++P) {
10516     NamedDecl *Prev = *P;
10517     if (!HasExplicitTemplateArgs) {
10518       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10519         QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10520                                                 /*AdjustExceptionSpec*/true);
10521         if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10522           if (Method->getPrimaryTemplate()) {
10523             TemplateMatches.addDecl(Method, P.getAccess());
10524           } else {
10525             // FIXME: Can this assert ever happen?  Needs a test.
10526             assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
10527             NonTemplateMatch = Method;
10528           }
10529         }
10530       }
10531     }
10532 
10533     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10534     if (!FunTmpl)
10535       continue;
10536 
10537     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10538     FunctionDecl *Specialization = nullptr;
10539     if (TemplateDeductionResult TDK
10540           = DeduceTemplateArguments(FunTmpl,
10541                                (HasExplicitTemplateArgs ? &TemplateArgs
10542                                                         : nullptr),
10543                                     R, Specialization, Info)) {
10544       // Keep track of almost-matches.
10545       FailedCandidates.addCandidate()
10546           .set(P.getPair(), FunTmpl->getTemplatedDecl(),
10547                MakeDeductionFailureInfo(Context, TDK, Info));
10548       (void)TDK;
10549       continue;
10550     }
10551 
10552     // Target attributes are part of the cuda function signature, so
10553     // the cuda target of the instantiated function must match that of its
10554     // template.  Given that C++ template deduction does not take
10555     // target attributes into account, we reject candidates here that
10556     // have a different target.
10557     if (LangOpts.CUDA &&
10558         IdentifyCUDATarget(Specialization,
10559                            /* IgnoreImplicitHDAttr = */ true) !=
10560             IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
10561       FailedCandidates.addCandidate().set(
10562           P.getPair(), FunTmpl->getTemplatedDecl(),
10563           MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
10564       continue;
10565     }
10566 
10567     TemplateMatches.addDecl(Specialization, P.getAccess());
10568   }
10569 
10570   FunctionDecl *Specialization = NonTemplateMatch;
10571   if (!Specialization) {
10572     // Find the most specialized function template specialization.
10573     UnresolvedSetIterator Result = getMostSpecialized(
10574         TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
10575         D.getIdentifierLoc(),
10576         PDiag(diag::err_explicit_instantiation_not_known) << Name,
10577         PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10578         PDiag(diag::note_explicit_instantiation_candidate));
10579 
10580     if (Result == TemplateMatches.end())
10581       return true;
10582 
10583     // Ignore access control bits, we don't need them for redeclaration checking.
10584     Specialization = cast<FunctionDecl>(*Result);
10585   }
10586 
10587   // C++11 [except.spec]p4
10588   // In an explicit instantiation an exception-specification may be specified,
10589   // but is not required.
10590   // If an exception-specification is specified in an explicit instantiation
10591   // directive, it shall be compatible with the exception-specifications of
10592   // other declarations of that function.
10593   if (auto *FPT = R->getAs<FunctionProtoType>())
10594     if (FPT->hasExceptionSpec()) {
10595       unsigned DiagID =
10596           diag::err_mismatched_exception_spec_explicit_instantiation;
10597       if (getLangOpts().MicrosoftExt)
10598         DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10599       bool Result = CheckEquivalentExceptionSpec(
10600           PDiag(DiagID) << Specialization->getType(),
10601           PDiag(diag::note_explicit_instantiation_here),
10602           Specialization->getType()->getAs<FunctionProtoType>(),
10603           Specialization->getLocation(), FPT, D.getBeginLoc());
10604       // In Microsoft mode, mismatching exception specifications just cause a
10605       // warning.
10606       if (!getLangOpts().MicrosoftExt && Result)
10607         return true;
10608     }
10609 
10610   if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10611     Diag(D.getIdentifierLoc(),
10612          diag::err_explicit_instantiation_member_function_not_instantiated)
10613       << Specialization
10614       << (Specialization->getTemplateSpecializationKind() ==
10615           TSK_ExplicitSpecialization);
10616     Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10617     return true;
10618   }
10619 
10620   FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10621   if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10622     PrevDecl = Specialization;
10623 
10624   if (PrevDecl) {
10625     bool HasNoEffect = false;
10626     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10627                                                PrevDecl,
10628                                      PrevDecl->getTemplateSpecializationKind(),
10629                                           PrevDecl->getPointOfInstantiation(),
10630                                                HasNoEffect))
10631       return true;
10632 
10633     // FIXME: We may still want to build some representation of this
10634     // explicit specialization.
10635     if (HasNoEffect)
10636       return (Decl*) nullptr;
10637   }
10638 
10639   // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10640   // functions
10641   //     valarray<size_t>::valarray(size_t) and
10642   //     valarray<size_t>::~valarray()
10643   // that it declared to have internal linkage with the internal_linkage
10644   // attribute. Ignore the explicit instantiation declaration in this case.
10645   if (Specialization->hasAttr<InternalLinkageAttr>() &&
10646       TSK == TSK_ExplicitInstantiationDeclaration) {
10647     if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10648       if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10649           RD->isInStdNamespace())
10650         return (Decl*) nullptr;
10651   }
10652 
10653   ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10654 
10655   // In MSVC mode, dllimported explicit instantiation definitions are treated as
10656   // instantiation declarations.
10657   if (TSK == TSK_ExplicitInstantiationDefinition &&
10658       Specialization->hasAttr<DLLImportAttr>() &&
10659       Context.getTargetInfo().getCXXABI().isMicrosoft())
10660     TSK = TSK_ExplicitInstantiationDeclaration;
10661 
10662   Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10663 
10664   if (Specialization->isDefined()) {
10665     // Let the ASTConsumer know that this function has been explicitly
10666     // instantiated now, and its linkage might have changed.
10667     Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
10668   } else if (TSK == TSK_ExplicitInstantiationDefinition)
10669     InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10670 
10671   // C++0x [temp.explicit]p2:
10672   //   If the explicit instantiation is for a member function, a member class
10673   //   or a static data member of a class template specialization, the name of
10674   //   the class template specialization in the qualified-id for the member
10675   //   name shall be a simple-template-id.
10676   //
10677   // C++98 has the same restriction, just worded differently.
10678   FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10679   if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10680       D.getCXXScopeSpec().isSet() &&
10681       !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10682     Diag(D.getIdentifierLoc(),
10683          diag::ext_explicit_instantiation_without_qualified_id)
10684     << Specialization << D.getCXXScopeSpec().getRange();
10685 
10686   CheckExplicitInstantiation(
10687       *this,
10688       FunTmpl ? (NamedDecl *)FunTmpl
10689               : Specialization->getInstantiatedFromMemberFunction(),
10690       D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10691 
10692   // FIXME: Create some kind of ExplicitInstantiationDecl here.
10693   return (Decl*) nullptr;
10694 }
10695 
10696 TypeResult
ActOnDependentTag(Scope * S,unsigned TagSpec,TagUseKind TUK,const CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation TagLoc,SourceLocation NameLoc)10697 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10698                         const CXXScopeSpec &SS, IdentifierInfo *Name,
10699                         SourceLocation TagLoc, SourceLocation NameLoc) {
10700   // This has to hold, because SS is expected to be defined.
10701   assert(Name && "Expected a name in a dependent tag");
10702 
10703   NestedNameSpecifier *NNS = SS.getScopeRep();
10704   if (!NNS)
10705     return true;
10706 
10707   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10708 
10709   if (TUK == TUK_Declaration || TUK == TUK_Definition) {
10710     Diag(NameLoc, diag::err_dependent_tag_decl)
10711       << (TUK == TUK_Definition) << Kind << SS.getRange();
10712     return true;
10713   }
10714 
10715   // Create the resulting type.
10716   ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10717   QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
10718 
10719   // Create type-source location information for this type.
10720   TypeLocBuilder TLB;
10721   DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
10722   TL.setElaboratedKeywordLoc(TagLoc);
10723   TL.setQualifierLoc(SS.getWithLocInContext(Context));
10724   TL.setNameLoc(NameLoc);
10725   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
10726 }
10727 
ActOnTypenameType(Scope * S,SourceLocation TypenameLoc,const CXXScopeSpec & SS,const IdentifierInfo & II,SourceLocation IdLoc,ImplicitTypenameContext IsImplicitTypename)10728 TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10729                                    const CXXScopeSpec &SS,
10730                                    const IdentifierInfo &II,
10731                                    SourceLocation IdLoc,
10732                                    ImplicitTypenameContext IsImplicitTypename) {
10733   if (SS.isInvalid())
10734     return true;
10735 
10736   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10737     Diag(TypenameLoc,
10738          getLangOpts().CPlusPlus11 ?
10739            diag::warn_cxx98_compat_typename_outside_of_template :
10740            diag::ext_typename_outside_of_template)
10741       << FixItHint::CreateRemoval(TypenameLoc);
10742 
10743   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10744   TypeSourceInfo *TSI = nullptr;
10745   QualType T =
10746       CheckTypenameType((TypenameLoc.isValid() ||
10747                          IsImplicitTypename == ImplicitTypenameContext::Yes)
10748                             ? ETK_Typename
10749                             : ETK_None,
10750                         TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
10751                         /*DeducedTSTContext=*/true);
10752   if (T.isNull())
10753     return true;
10754   return CreateParsedType(T, TSI);
10755 }
10756 
10757 TypeResult
ActOnTypenameType(Scope * S,SourceLocation TypenameLoc,const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,TemplateTy TemplateIn,IdentifierInfo * TemplateII,SourceLocation TemplateIILoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc)10758 Sema::ActOnTypenameType(Scope *S,
10759                         SourceLocation TypenameLoc,
10760                         const CXXScopeSpec &SS,
10761                         SourceLocation TemplateKWLoc,
10762                         TemplateTy TemplateIn,
10763                         IdentifierInfo *TemplateII,
10764                         SourceLocation TemplateIILoc,
10765                         SourceLocation LAngleLoc,
10766                         ASTTemplateArgsPtr TemplateArgsIn,
10767                         SourceLocation RAngleLoc) {
10768   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10769     Diag(TypenameLoc,
10770          getLangOpts().CPlusPlus11 ?
10771            diag::warn_cxx98_compat_typename_outside_of_template :
10772            diag::ext_typename_outside_of_template)
10773       << FixItHint::CreateRemoval(TypenameLoc);
10774 
10775   // Strangely, non-type results are not ignored by this lookup, so the
10776   // program is ill-formed if it finds an injected-class-name.
10777   if (TypenameLoc.isValid()) {
10778     auto *LookupRD =
10779         dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10780     if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10781       Diag(TemplateIILoc,
10782            diag::ext_out_of_line_qualified_id_type_names_constructor)
10783         << TemplateII << 0 /*injected-class-name used as template name*/
10784         << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10785     }
10786   }
10787 
10788   // Translate the parser's template argument list in our AST format.
10789   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10790   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10791 
10792   TemplateName Template = TemplateIn.get();
10793   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10794     // Construct a dependent template specialization type.
10795     assert(DTN && "dependent template has non-dependent name?");
10796     assert(DTN->getQualifier() == SS.getScopeRep());
10797     QualType T = Context.getDependentTemplateSpecializationType(
10798         ETK_Typename, DTN->getQualifier(), DTN->getIdentifier(),
10799         TemplateArgs.arguments());
10800 
10801     // Create source-location information for this type.
10802     TypeLocBuilder Builder;
10803     DependentTemplateSpecializationTypeLoc SpecTL
10804     = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
10805     SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10806     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
10807     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10808     SpecTL.setTemplateNameLoc(TemplateIILoc);
10809     SpecTL.setLAngleLoc(LAngleLoc);
10810     SpecTL.setRAngleLoc(RAngleLoc);
10811     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10812       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10813     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
10814   }
10815 
10816   QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
10817   if (T.isNull())
10818     return true;
10819 
10820   // Provide source-location information for the template specialization type.
10821   TypeLocBuilder Builder;
10822   TemplateSpecializationTypeLoc SpecTL
10823     = Builder.push<TemplateSpecializationTypeLoc>(T);
10824   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10825   SpecTL.setTemplateNameLoc(TemplateIILoc);
10826   SpecTL.setLAngleLoc(LAngleLoc);
10827   SpecTL.setRAngleLoc(RAngleLoc);
10828   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10829     SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10830 
10831   T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
10832   ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10833   TL.setElaboratedKeywordLoc(TypenameLoc);
10834   TL.setQualifierLoc(SS.getWithLocInContext(Context));
10835 
10836   TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10837   return CreateParsedType(T, TSI);
10838 }
10839 
10840 
10841 /// Determine whether this failed name lookup should be treated as being
10842 /// disabled by a usage of std::enable_if.
isEnableIf(NestedNameSpecifierLoc NNS,const IdentifierInfo & II,SourceRange & CondRange,Expr * & Cond)10843 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
10844                        SourceRange &CondRange, Expr *&Cond) {
10845   // We must be looking for a ::type...
10846   if (!II.isStr("type"))
10847     return false;
10848 
10849   // ... within an explicitly-written template specialization...
10850   if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10851     return false;
10852   TypeLoc EnableIfTy = NNS.getTypeLoc();
10853   TemplateSpecializationTypeLoc EnableIfTSTLoc =
10854       EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
10855   if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10856     return false;
10857   const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10858 
10859   // ... which names a complete class template declaration...
10860   const TemplateDecl *EnableIfDecl =
10861     EnableIfTST->getTemplateName().getAsTemplateDecl();
10862   if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10863     return false;
10864 
10865   // ... called "enable_if".
10866   const IdentifierInfo *EnableIfII =
10867     EnableIfDecl->getDeclName().getAsIdentifierInfo();
10868   if (!EnableIfII || !EnableIfII->isStr("enable_if"))
10869     return false;
10870 
10871   // Assume the first template argument is the condition.
10872   CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
10873 
10874   // Dig out the condition.
10875   Cond = nullptr;
10876   if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
10877         != TemplateArgument::Expression)
10878     return true;
10879 
10880   Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
10881 
10882   // Ignore Boolean literals; they add no value.
10883   if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
10884     Cond = nullptr;
10885 
10886   return true;
10887 }
10888 
10889 QualType
CheckTypenameType(ElaboratedTypeKeyword Keyword,SourceLocation KeywordLoc,NestedNameSpecifierLoc QualifierLoc,const IdentifierInfo & II,SourceLocation IILoc,TypeSourceInfo ** TSI,bool DeducedTSTContext)10890 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
10891                         SourceLocation KeywordLoc,
10892                         NestedNameSpecifierLoc QualifierLoc,
10893                         const IdentifierInfo &II,
10894                         SourceLocation IILoc,
10895                         TypeSourceInfo **TSI,
10896                         bool DeducedTSTContext) {
10897   QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
10898                                  DeducedTSTContext);
10899   if (T.isNull())
10900     return QualType();
10901 
10902   *TSI = Context.CreateTypeSourceInfo(T);
10903   if (isa<DependentNameType>(T)) {
10904     DependentNameTypeLoc TL =
10905         (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
10906     TL.setElaboratedKeywordLoc(KeywordLoc);
10907     TL.setQualifierLoc(QualifierLoc);
10908     TL.setNameLoc(IILoc);
10909   } else {
10910     ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
10911     TL.setElaboratedKeywordLoc(KeywordLoc);
10912     TL.setQualifierLoc(QualifierLoc);
10913     TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
10914   }
10915   return T;
10916 }
10917 
10918 /// Build the type that describes a C++ typename specifier,
10919 /// e.g., "typename T::type".
10920 QualType
CheckTypenameType(ElaboratedTypeKeyword Keyword,SourceLocation KeywordLoc,NestedNameSpecifierLoc QualifierLoc,const IdentifierInfo & II,SourceLocation IILoc,bool DeducedTSTContext)10921 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
10922                         SourceLocation KeywordLoc,
10923                         NestedNameSpecifierLoc QualifierLoc,
10924                         const IdentifierInfo &II,
10925                         SourceLocation IILoc, bool DeducedTSTContext) {
10926   CXXScopeSpec SS;
10927   SS.Adopt(QualifierLoc);
10928 
10929   DeclContext *Ctx = nullptr;
10930   if (QualifierLoc) {
10931     Ctx = computeDeclContext(SS);
10932     if (!Ctx) {
10933       // If the nested-name-specifier is dependent and couldn't be
10934       // resolved to a type, build a typename type.
10935       assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
10936       return Context.getDependentNameType(Keyword,
10937                                           QualifierLoc.getNestedNameSpecifier(),
10938                                           &II);
10939     }
10940 
10941     // If the nested-name-specifier refers to the current instantiation,
10942     // the "typename" keyword itself is superfluous. In C++03, the
10943     // program is actually ill-formed. However, DR 382 (in C++0x CD1)
10944     // allows such extraneous "typename" keywords, and we retroactively
10945     // apply this DR to C++03 code with only a warning. In any case we continue.
10946 
10947     if (RequireCompleteDeclContext(SS, Ctx))
10948       return QualType();
10949   }
10950 
10951   DeclarationName Name(&II);
10952   LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
10953   if (Ctx)
10954     LookupQualifiedName(Result, Ctx, SS);
10955   else
10956     LookupName(Result, CurScope);
10957   unsigned DiagID = 0;
10958   Decl *Referenced = nullptr;
10959   switch (Result.getResultKind()) {
10960   case LookupResult::NotFound: {
10961     // If we're looking up 'type' within a template named 'enable_if', produce
10962     // a more specific diagnostic.
10963     SourceRange CondRange;
10964     Expr *Cond = nullptr;
10965     if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10966       // If we have a condition, narrow it down to the specific failed
10967       // condition.
10968       if (Cond) {
10969         Expr *FailedCond;
10970         std::string FailedDescription;
10971         std::tie(FailedCond, FailedDescription) =
10972           findFailedBooleanCondition(Cond);
10973 
10974         Diag(FailedCond->getExprLoc(),
10975              diag::err_typename_nested_not_found_requirement)
10976           << FailedDescription
10977           << FailedCond->getSourceRange();
10978         return QualType();
10979       }
10980 
10981       Diag(CondRange.getBegin(),
10982            diag::err_typename_nested_not_found_enable_if)
10983           << Ctx << CondRange;
10984       return QualType();
10985     }
10986 
10987     DiagID = Ctx ? diag::err_typename_nested_not_found
10988                  : diag::err_unknown_typename;
10989     break;
10990   }
10991 
10992   case LookupResult::FoundUnresolvedValue: {
10993     // We found a using declaration that is a value. Most likely, the using
10994     // declaration itself is meant to have the 'typename' keyword.
10995     SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10996                           IILoc);
10997     Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10998       << Name << Ctx << FullRange;
10999     if (UnresolvedUsingValueDecl *Using
11000           = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11001       SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11002       Diag(Loc, diag::note_using_value_decl_missing_typename)
11003         << FixItHint::CreateInsertion(Loc, "typename ");
11004     }
11005   }
11006   // Fall through to create a dependent typename type, from which we can recover
11007   // better.
11008   [[fallthrough]];
11009 
11010   case LookupResult::NotFoundInCurrentInstantiation:
11011     // Okay, it's a member of an unknown instantiation.
11012     return Context.getDependentNameType(Keyword,
11013                                         QualifierLoc.getNestedNameSpecifier(),
11014                                         &II);
11015 
11016   case LookupResult::Found:
11017     if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11018       // C++ [class.qual]p2:
11019       //   In a lookup in which function names are not ignored and the
11020       //   nested-name-specifier nominates a class C, if the name specified
11021       //   after the nested-name-specifier, when looked up in C, is the
11022       //   injected-class-name of C [...] then the name is instead considered
11023       //   to name the constructor of class C.
11024       //
11025       // Unlike in an elaborated-type-specifier, function names are not ignored
11026       // in typename-specifier lookup. However, they are ignored in all the
11027       // contexts where we form a typename type with no keyword (that is, in
11028       // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11029       //
11030       // FIXME: That's not strictly true: mem-initializer-id lookup does not
11031       // ignore functions, but that appears to be an oversight.
11032       auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
11033       auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
11034       if (Keyword == ETK_Typename && LookupRD && FoundRD &&
11035           FoundRD->isInjectedClassName() &&
11036           declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
11037         Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
11038             << &II << 1 << 0 /*'typename' keyword used*/;
11039 
11040       // We found a type. Build an ElaboratedType, since the
11041       // typename-specifier was just sugar.
11042       MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
11043       return Context.getElaboratedType(Keyword,
11044                                        QualifierLoc.getNestedNameSpecifier(),
11045                                        Context.getTypeDeclType(Type));
11046     }
11047 
11048     // C++ [dcl.type.simple]p2:
11049     //   A type-specifier of the form
11050     //     typename[opt] nested-name-specifier[opt] template-name
11051     //   is a placeholder for a deduced class type [...].
11052     if (getLangOpts().CPlusPlus17) {
11053       if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11054         if (!DeducedTSTContext) {
11055           QualType T(QualifierLoc
11056                          ? QualifierLoc.getNestedNameSpecifier()->getAsType()
11057                          : nullptr, 0);
11058           if (!T.isNull())
11059             Diag(IILoc, diag::err_dependent_deduced_tst)
11060               << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T;
11061           else
11062             Diag(IILoc, diag::err_deduced_tst)
11063               << (int)getTemplateNameKindForDiagnostics(TemplateName(TD));
11064           Diag(TD->getLocation(), diag::note_template_decl_here);
11065           return QualType();
11066         }
11067         return Context.getElaboratedType(
11068             Keyword, QualifierLoc.getNestedNameSpecifier(),
11069             Context.getDeducedTemplateSpecializationType(TemplateName(TD),
11070                                                          QualType(), false));
11071       }
11072     }
11073 
11074     DiagID = Ctx ? diag::err_typename_nested_not_type
11075                  : diag::err_typename_not_type;
11076     Referenced = Result.getFoundDecl();
11077     break;
11078 
11079   case LookupResult::FoundOverloaded:
11080     DiagID = Ctx ? diag::err_typename_nested_not_type
11081                  : diag::err_typename_not_type;
11082     Referenced = *Result.begin();
11083     break;
11084 
11085   case LookupResult::Ambiguous:
11086     return QualType();
11087   }
11088 
11089   // If we get here, it's because name lookup did not find a
11090   // type. Emit an appropriate diagnostic and return an error.
11091   SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11092                         IILoc);
11093   if (Ctx)
11094     Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11095   else
11096     Diag(IILoc, DiagID) << FullRange << Name;
11097   if (Referenced)
11098     Diag(Referenced->getLocation(),
11099          Ctx ? diag::note_typename_member_refers_here
11100              : diag::note_typename_refers_here)
11101       << Name;
11102   return QualType();
11103 }
11104 
11105 namespace {
11106   // See Sema::RebuildTypeInCurrentInstantiation
11107   class CurrentInstantiationRebuilder
11108     : public TreeTransform<CurrentInstantiationRebuilder> {
11109     SourceLocation Loc;
11110     DeclarationName Entity;
11111 
11112   public:
11113     typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11114 
CurrentInstantiationRebuilder(Sema & SemaRef,SourceLocation Loc,DeclarationName Entity)11115     CurrentInstantiationRebuilder(Sema &SemaRef,
11116                                   SourceLocation Loc,
11117                                   DeclarationName Entity)
11118     : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11119       Loc(Loc), Entity(Entity) { }
11120 
11121     /// Determine whether the given type \p T has already been
11122     /// transformed.
11123     ///
11124     /// For the purposes of type reconstruction, a type has already been
11125     /// transformed if it is NULL or if it is not dependent.
AlreadyTransformed(QualType T)11126     bool AlreadyTransformed(QualType T) {
11127       return T.isNull() || !T->isInstantiationDependentType();
11128     }
11129 
11130     /// Returns the location of the entity whose type is being
11131     /// rebuilt.
getBaseLocation()11132     SourceLocation getBaseLocation() { return Loc; }
11133 
11134     /// Returns the name of the entity whose type is being rebuilt.
getBaseEntity()11135     DeclarationName getBaseEntity() { return Entity; }
11136 
11137     /// Sets the "base" location and entity when that
11138     /// information is known based on another transformation.
setBase(SourceLocation Loc,DeclarationName Entity)11139     void setBase(SourceLocation Loc, DeclarationName Entity) {
11140       this->Loc = Loc;
11141       this->Entity = Entity;
11142     }
11143 
TransformLambdaExpr(LambdaExpr * E)11144     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11145       // Lambdas never need to be transformed.
11146       return E;
11147     }
11148   };
11149 } // end anonymous namespace
11150 
11151 /// Rebuilds a type within the context of the current instantiation.
11152 ///
11153 /// The type \p T is part of the type of an out-of-line member definition of
11154 /// a class template (or class template partial specialization) that was parsed
11155 /// and constructed before we entered the scope of the class template (or
11156 /// partial specialization thereof). This routine will rebuild that type now
11157 /// that we have entered the declarator's scope, which may produce different
11158 /// canonical types, e.g.,
11159 ///
11160 /// \code
11161 /// template<typename T>
11162 /// struct X {
11163 ///   typedef T* pointer;
11164 ///   pointer data();
11165 /// };
11166 ///
11167 /// template<typename T>
11168 /// typename X<T>::pointer X<T>::data() { ... }
11169 /// \endcode
11170 ///
11171 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
11172 /// since we do not know that we can look into X<T> when we parsed the type.
11173 /// This function will rebuild the type, performing the lookup of "pointer"
11174 /// in X<T> and returning an ElaboratedType whose canonical type is the same
11175 /// as the canonical type of T*, allowing the return types of the out-of-line
11176 /// definition and the declaration to match.
RebuildTypeInCurrentInstantiation(TypeSourceInfo * T,SourceLocation Loc,DeclarationName Name)11177 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11178                                                         SourceLocation Loc,
11179                                                         DeclarationName Name) {
11180   if (!T || !T->getType()->isInstantiationDependentType())
11181     return T;
11182 
11183   CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11184   return Rebuilder.TransformType(T);
11185 }
11186 
RebuildExprInCurrentInstantiation(Expr * E)11187 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11188   CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11189                                           DeclarationName());
11190   return Rebuilder.TransformExpr(E);
11191 }
11192 
RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec & SS)11193 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11194   if (SS.isInvalid())
11195     return true;
11196 
11197   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11198   CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11199                                           DeclarationName());
11200   NestedNameSpecifierLoc Rebuilt
11201     = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11202   if (!Rebuilt)
11203     return true;
11204 
11205   SS.Adopt(Rebuilt);
11206   return false;
11207 }
11208 
11209 /// Rebuild the template parameters now that we know we're in a current
11210 /// instantiation.
RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList * Params)11211 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11212                                                TemplateParameterList *Params) {
11213   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11214     Decl *Param = Params->getParam(I);
11215 
11216     // There is nothing to rebuild in a type parameter.
11217     if (isa<TemplateTypeParmDecl>(Param))
11218       continue;
11219 
11220     // Rebuild the template parameter list of a template template parameter.
11221     if (TemplateTemplateParmDecl *TTP
11222         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11223       if (RebuildTemplateParamsInCurrentInstantiation(
11224             TTP->getTemplateParameters()))
11225         return true;
11226 
11227       continue;
11228     }
11229 
11230     // Rebuild the type of a non-type template parameter.
11231     NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
11232     TypeSourceInfo *NewTSI
11233       = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
11234                                           NTTP->getLocation(),
11235                                           NTTP->getDeclName());
11236     if (!NewTSI)
11237       return true;
11238 
11239     if (NewTSI->getType()->isUndeducedType()) {
11240       // C++17 [temp.dep.expr]p3:
11241       //   An id-expression is type-dependent if it contains
11242       //    - an identifier associated by name lookup with a non-type
11243       //      template-parameter declared with a type that contains a
11244       //      placeholder type (7.1.7.4),
11245       NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11246     }
11247 
11248     if (NewTSI != NTTP->getTypeSourceInfo()) {
11249       NTTP->setTypeSourceInfo(NewTSI);
11250       NTTP->setType(NewTSI->getType());
11251     }
11252   }
11253 
11254   return false;
11255 }
11256 
11257 /// Produces a formatted string that describes the binding of
11258 /// template parameters to template arguments.
11259 std::string
getTemplateArgumentBindingsText(const TemplateParameterList * Params,const TemplateArgumentList & Args)11260 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11261                                       const TemplateArgumentList &Args) {
11262   return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11263 }
11264 
11265 std::string
getTemplateArgumentBindingsText(const TemplateParameterList * Params,const TemplateArgument * Args,unsigned NumArgs)11266 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11267                                       const TemplateArgument *Args,
11268                                       unsigned NumArgs) {
11269   SmallString<128> Str;
11270   llvm::raw_svector_ostream Out(Str);
11271 
11272   if (!Params || Params->size() == 0 || NumArgs == 0)
11273     return std::string();
11274 
11275   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11276     if (I >= NumArgs)
11277       break;
11278 
11279     if (I == 0)
11280       Out << "[with ";
11281     else
11282       Out << ", ";
11283 
11284     if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11285       Out << Id->getName();
11286     } else {
11287       Out << '$' << I;
11288     }
11289 
11290     Out << " = ";
11291     Args[I].print(getPrintingPolicy(), Out,
11292                   TemplateParameterList::shouldIncludeTypeForArgument(
11293                       getPrintingPolicy(), Params, I));
11294   }
11295 
11296   Out << ']';
11297   return std::string(Out.str());
11298 }
11299 
MarkAsLateParsedTemplate(FunctionDecl * FD,Decl * FnD,CachedTokens & Toks)11300 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11301                                     CachedTokens &Toks) {
11302   if (!FD)
11303     return;
11304 
11305   auto LPT = std::make_unique<LateParsedTemplate>();
11306 
11307   // Take tokens to avoid allocations
11308   LPT->Toks.swap(Toks);
11309   LPT->D = FnD;
11310   LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11311 
11312   FD->setLateTemplateParsed(true);
11313 }
11314 
UnmarkAsLateParsedTemplate(FunctionDecl * FD)11315 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11316   if (!FD)
11317     return;
11318   FD->setLateTemplateParsed(false);
11319 }
11320 
IsInsideALocalClassWithinATemplateFunction()11321 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11322   DeclContext *DC = CurContext;
11323 
11324   while (DC) {
11325     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11326       const FunctionDecl *FD = RD->isLocalClass();
11327       return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11328     } else if (DC->isTranslationUnit() || DC->isNamespace())
11329       return false;
11330 
11331     DC = DC->getParent();
11332   }
11333   return false;
11334 }
11335 
11336 namespace {
11337 /// Walk the path from which a declaration was instantiated, and check
11338 /// that every explicit specialization along that path is visible. This enforces
11339 /// C++ [temp.expl.spec]/6:
11340 ///
11341 ///   If a template, a member template or a member of a class template is
11342 ///   explicitly specialized then that specialization shall be declared before
11343 ///   the first use of that specialization that would cause an implicit
11344 ///   instantiation to take place, in every translation unit in which such a
11345 ///   use occurs; no diagnostic is required.
11346 ///
11347 /// and also C++ [temp.class.spec]/1:
11348 ///
11349 ///   A partial specialization shall be declared before the first use of a
11350 ///   class template specialization that would make use of the partial
11351 ///   specialization as the result of an implicit or explicit instantiation
11352 ///   in every translation unit in which such a use occurs; no diagnostic is
11353 ///   required.
11354 class ExplicitSpecializationVisibilityChecker {
11355   Sema &S;
11356   SourceLocation Loc;
11357   llvm::SmallVector<Module *, 8> Modules;
11358   Sema::AcceptableKind Kind;
11359 
11360 public:
ExplicitSpecializationVisibilityChecker(Sema & S,SourceLocation Loc,Sema::AcceptableKind Kind)11361   ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11362                                           Sema::AcceptableKind Kind)
11363       : S(S), Loc(Loc), Kind(Kind) {}
11364 
check(NamedDecl * ND)11365   void check(NamedDecl *ND) {
11366     if (auto *FD = dyn_cast<FunctionDecl>(ND))
11367       return checkImpl(FD);
11368     if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11369       return checkImpl(RD);
11370     if (auto *VD = dyn_cast<VarDecl>(ND))
11371       return checkImpl(VD);
11372     if (auto *ED = dyn_cast<EnumDecl>(ND))
11373       return checkImpl(ED);
11374   }
11375 
11376 private:
diagnose(NamedDecl * D,bool IsPartialSpec)11377   void diagnose(NamedDecl *D, bool IsPartialSpec) {
11378     auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11379                               : Sema::MissingImportKind::ExplicitSpecialization;
11380     const bool Recover = true;
11381 
11382     // If we got a custom set of modules (because only a subset of the
11383     // declarations are interesting), use them, otherwise let
11384     // diagnoseMissingImport intelligently pick some.
11385     if (Modules.empty())
11386       S.diagnoseMissingImport(Loc, D, Kind, Recover);
11387     else
11388       S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11389   }
11390 
CheckMemberSpecialization(const NamedDecl * D)11391   bool CheckMemberSpecialization(const NamedDecl *D) {
11392     return Kind == Sema::AcceptableKind::Visible
11393                ? S.hasVisibleMemberSpecialization(D)
11394                : S.hasReachableMemberSpecialization(D);
11395   }
11396 
CheckExplicitSpecialization(const NamedDecl * D)11397   bool CheckExplicitSpecialization(const NamedDecl *D) {
11398     return Kind == Sema::AcceptableKind::Visible
11399                ? S.hasVisibleExplicitSpecialization(D)
11400                : S.hasReachableExplicitSpecialization(D);
11401   }
11402 
CheckDeclaration(const NamedDecl * D)11403   bool CheckDeclaration(const NamedDecl *D) {
11404     return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11405                                                  : S.hasReachableDeclaration(D);
11406   }
11407 
11408   // Check a specific declaration. There are three problematic cases:
11409   //
11410   //  1) The declaration is an explicit specialization of a template
11411   //     specialization.
11412   //  2) The declaration is an explicit specialization of a member of an
11413   //     templated class.
11414   //  3) The declaration is an instantiation of a template, and that template
11415   //     is an explicit specialization of a member of a templated class.
11416   //
11417   // We don't need to go any deeper than that, as the instantiation of the
11418   // surrounding class / etc is not triggered by whatever triggered this
11419   // instantiation, and thus should be checked elsewhere.
11420   template<typename SpecDecl>
checkImpl(SpecDecl * Spec)11421   void checkImpl(SpecDecl *Spec) {
11422     bool IsHiddenExplicitSpecialization = false;
11423     if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
11424       IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11425                                            ? !CheckMemberSpecialization(Spec)
11426                                            : !CheckExplicitSpecialization(Spec);
11427     } else {
11428       checkInstantiated(Spec);
11429     }
11430 
11431     if (IsHiddenExplicitSpecialization)
11432       diagnose(Spec->getMostRecentDecl(), false);
11433   }
11434 
checkInstantiated(FunctionDecl * FD)11435   void checkInstantiated(FunctionDecl *FD) {
11436     if (auto *TD = FD->getPrimaryTemplate())
11437       checkTemplate(TD);
11438   }
11439 
checkInstantiated(CXXRecordDecl * RD)11440   void checkInstantiated(CXXRecordDecl *RD) {
11441     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11442     if (!SD)
11443       return;
11444 
11445     auto From = SD->getSpecializedTemplateOrPartial();
11446     if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11447       checkTemplate(TD);
11448     else if (auto *TD =
11449                  From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11450       if (!CheckDeclaration(TD))
11451         diagnose(TD, true);
11452       checkTemplate(TD);
11453     }
11454   }
11455 
checkInstantiated(VarDecl * RD)11456   void checkInstantiated(VarDecl *RD) {
11457     auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11458     if (!SD)
11459       return;
11460 
11461     auto From = SD->getSpecializedTemplateOrPartial();
11462     if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11463       checkTemplate(TD);
11464     else if (auto *TD =
11465                  From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11466       if (!CheckDeclaration(TD))
11467         diagnose(TD, true);
11468       checkTemplate(TD);
11469     }
11470   }
11471 
checkInstantiated(EnumDecl * FD)11472   void checkInstantiated(EnumDecl *FD) {}
11473 
11474   template<typename TemplDecl>
checkTemplate(TemplDecl * TD)11475   void checkTemplate(TemplDecl *TD) {
11476     if (TD->isMemberSpecialization()) {
11477       if (!CheckMemberSpecialization(TD))
11478         diagnose(TD->getMostRecentDecl(), false);
11479     }
11480   }
11481 };
11482 } // end anonymous namespace
11483 
checkSpecializationVisibility(SourceLocation Loc,NamedDecl * Spec)11484 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11485   if (!getLangOpts().Modules)
11486     return;
11487 
11488   ExplicitSpecializationVisibilityChecker(*this, Loc,
11489                                           Sema::AcceptableKind::Visible)
11490       .check(Spec);
11491 }
11492 
checkSpecializationReachability(SourceLocation Loc,NamedDecl * Spec)11493 void Sema::checkSpecializationReachability(SourceLocation Loc,
11494                                            NamedDecl *Spec) {
11495   if (!getLangOpts().CPlusPlusModules)
11496     return checkSpecializationVisibility(Loc, Spec);
11497 
11498   ExplicitSpecializationVisibilityChecker(*this, Loc,
11499                                           Sema::AcceptableKind::Reachable)
11500       .check(Spec);
11501 }
11502