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