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