clang  20.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===//
7 //
8 // This file implements semantic analysis for C++ templates.
9 //===----------------------------------------------------------------------===//
10 
11 #include "TreeTransform.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclFriend.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/TemplateName.h"
21 #include "clang/AST/TypeVisitor.h"
22 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/Stack.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Sema/DeclSpec.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Overload.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/SemaCUDA.h"
38 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/BitVector.h"
41 #include "llvm/ADT/SmallBitVector.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/StringExtras.h"
44 
45 #include <iterator>
46 #include <optional>
47 using namespace clang;
48 using namespace sema;
49 
50 // Exported for use by Parser.
53  unsigned N) {
54  if (!N) return SourceRange();
55  return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
56 }
57 
58 unsigned Sema::getTemplateDepth(Scope *S) const {
59  unsigned Depth = 0;
60 
61  // Each template parameter scope represents one level of template parameter
62  // depth.
63  for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
64  TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
65  ++Depth;
66  }
67 
68  // Note that there are template parameters with the given depth.
69  auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
70 
71  // Look for parameters of an enclosing generic lambda. We don't create a
72  // template parameter scope for these.
73  for (FunctionScopeInfo *FSI : getFunctionScopes()) {
74  if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
75  if (!LSI->TemplateParams.empty()) {
76  ParamsAtDepth(LSI->AutoTemplateParameterDepth);
77  break;
78  }
79  if (LSI->GLTemplateParameterList) {
80  ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
81  break;
82  }
83  }
84  }
85 
86  // Look for parameters of an enclosing terse function template. We don't
87  // create a template parameter scope for these either.
88  for (const InventedTemplateParameterInfo &Info :
89  getInventedParameterInfos()) {
90  if (!Info.TemplateParams.empty()) {
91  ParamsAtDepth(Info.AutoTemplateParameterDepth);
92  break;
93  }
94  }
95 
96  return Depth;
97 }
98 
99 /// \brief Determine whether the declaration found is acceptable as the name
100 /// of a template and, if so, return that template declaration. Otherwise,
101 /// returns null.
102 ///
103 /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
104 /// is true. In all other cases it will return a TemplateDecl (or null).
106  bool AllowFunctionTemplates,
107  bool AllowDependent) {
108  D = D->getUnderlyingDecl();
109 
110  if (isa<TemplateDecl>(D)) {
111  if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
112  return nullptr;
113 
114  return D;
115  }
116 
117  if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
118  // C++ [temp.local]p1:
119  // Like normal (non-template) classes, class templates have an
120  // injected-class-name (Clause 9). The injected-class-name
121  // can be used with or without a template-argument-list. When
122  // it is used without a template-argument-list, it is
123  // equivalent to the injected-class-name followed by the
124  // template-parameters of the class template enclosed in
125  // <>. When it is used with a template-argument-list, it
126  // refers to the specified class template specialization,
127  // which could be the current specialization or another
128  // specialization.
129  if (Record->isInjectedClassName()) {
130  Record = cast<CXXRecordDecl>(Record->getDeclContext());
131  if (Record->getDescribedClassTemplate())
132  return Record->getDescribedClassTemplate();
133 
134  if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
135  return Spec->getSpecializedTemplate();
136  }
137 
138  return nullptr;
139  }
140 
141  // 'using Dependent::foo;' can resolve to a template name.
142  // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
143  // injected-class-name).
144  if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
145  return D;
146 
147  return nullptr;
148 }
149 
151  bool AllowFunctionTemplates,
152  bool AllowDependent) {
153  LookupResult::Filter filter = R.makeFilter();
154  while (filter.hasNext()) {
155  NamedDecl *Orig = filter.next();
156  if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
157  filter.erase();
158  }
159  filter.done();
160 }
161 
163  bool AllowFunctionTemplates,
164  bool AllowDependent,
165  bool AllowNonTemplateFunctions) {
166  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
167  if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
168  return true;
169  if (AllowNonTemplateFunctions &&
170  isa<FunctionDecl>((*I)->getUnderlyingDecl()))
171  return true;
172  }
173 
174  return false;
175 }
176 
178  CXXScopeSpec &SS,
179  bool hasTemplateKeyword,
180  const UnqualifiedId &Name,
181  ParsedType ObjectTypePtr,
182  bool EnteringContext,
183  TemplateTy &TemplateResult,
184  bool &MemberOfUnknownSpecialization,
185  bool Disambiguation) {
186  assert(getLangOpts().CPlusPlus && "No template names in C!");
187 
188  DeclarationName TName;
189  MemberOfUnknownSpecialization = false;
190 
191  switch (Name.getKind()) {
193  TName = DeclarationName(Name.Identifier);
194  break;
195 
197  TName = Context.DeclarationNames.getCXXOperatorName(
198  Name.OperatorFunctionId.Operator);
199  break;
200 
202  TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
203  break;
204 
205  default:
206  return TNK_Non_template;
207  }
208 
209  QualType ObjectType = ObjectTypePtr.get();
210 
211  AssumedTemplateKind AssumedTemplate;
212  LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
213  if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
214  /*RequiredTemplate=*/SourceLocation(),
215  &AssumedTemplate,
216  /*AllowTypoCorrection=*/!Disambiguation))
217  return TNK_Non_template;
218  MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
219 
220  if (AssumedTemplate != AssumedTemplateKind::None) {
221  TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
222  // Let the parser know whether we found nothing or found functions; if we
223  // found nothing, we want to more carefully check whether this is actually
224  // a function template name versus some other kind of undeclared identifier.
225  return AssumedTemplate == AssumedTemplateKind::FoundNothing
228  }
229 
230  if (R.empty())
231  return TNK_Non_template;
232 
233  NamedDecl *D = nullptr;
234  UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
235  if (R.isAmbiguous()) {
236  // If we got an ambiguity involving a non-function template, treat this
237  // as a template name, and pick an arbitrary template for error recovery.
238  bool AnyFunctionTemplates = false;
239  for (NamedDecl *FoundD : R) {
240  if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
241  if (isa<FunctionTemplateDecl>(FoundTemplate))
242  AnyFunctionTemplates = true;
243  else {
244  D = FoundTemplate;
245  FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
246  break;
247  }
248  }
249  }
250 
251  // If we didn't find any templates at all, this isn't a template name.
252  // Leave the ambiguity for a later lookup to diagnose.
253  if (!D && !AnyFunctionTemplates) {
254  R.suppressDiagnostics();
255  return TNK_Non_template;
256  }
257 
258  // If the only templates were function templates, filter out the rest.
259  // We'll diagnose the ambiguity later.
260  if (!D)
261  FilterAcceptableTemplateNames(R);
262  }
263 
264  // At this point, we have either picked a single template name declaration D
265  // or we have a non-empty set of results R containing either one template name
266  // declaration or a set of function templates.
267 
268  TemplateName Template;
269  TemplateNameKind TemplateKind;
270 
271  unsigned ResultCount = R.end() - R.begin();
272  if (!D && ResultCount > 1) {
273  // We assume that we'll preserve the qualifier from a function
274  // template name in other ways.
275  Template = Context.getOverloadedTemplateName(R.begin(), R.end());
276  TemplateKind = TNK_Function_template;
277 
278  // We'll do this lookup again later.
280  } else {
281  if (!D) {
282  D = getAsTemplateNameDecl(*R.begin());
283  assert(D && "unambiguous result is not a template name");
284  }
285 
286  if (isa<UnresolvedUsingValueDecl>(D)) {
287  // We don't yet know whether this is a template-name or not.
288  MemberOfUnknownSpecialization = true;
289  return TNK_Non_template;
290  }
291 
292  TemplateDecl *TD = cast<TemplateDecl>(D);
293  Template =
294  FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
295  assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
296  if (!SS.isInvalid()) {
297  NestedNameSpecifier *Qualifier = SS.getScopeRep();
298  Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
299  Template);
300  }
301 
302  if (isa<FunctionTemplateDecl>(TD)) {
303  TemplateKind = TNK_Function_template;
304 
305  // We'll do this lookup again later.
307  } else {
308  assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
309  isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
310  isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
311  TemplateKind =
312  isa<VarTemplateDecl>(TD) ? TNK_Var_template :
313  isa<ConceptDecl>(TD) ? TNK_Concept_template :
315  }
316  }
317 
318  TemplateResult = TemplateTy::make(Template);
319  return TemplateKind;
320 }
321 
323  SourceLocation NameLoc, CXXScopeSpec &SS,
324  ParsedTemplateTy *Template /*=nullptr*/) {
325  // We could use redeclaration lookup here, but we don't need to: the
326  // syntactic form of a deduction guide is enough to identify it even
327  // if we can't look up the template name at all.
328  LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
329  if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
330  /*EnteringContext*/ false))
331  return false;
332 
333  if (R.empty()) return false;
334  if (R.isAmbiguous()) {
335  // FIXME: Diagnose an ambiguity if we find at least one template.
337  return false;
338  }
339 
340  // We only treat template-names that name type templates as valid deduction
341  // guide names.
343  if (!TD || !getAsTypeTemplateDecl(TD))
344  return false;
345 
346  if (Template) {
347  TemplateName Name = Context.getQualifiedTemplateName(
348  SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
349  *Template = TemplateTy::make(Name);
350  }
351  return true;
352 }
353 
355  SourceLocation IILoc,
356  Scope *S,
357  const CXXScopeSpec *SS,
358  TemplateTy &SuggestedTemplate,
359  TemplateNameKind &SuggestedKind) {
360  // We can't recover unless there's a dependent scope specifier preceding the
361  // template name.
362  // FIXME: Typo correction?
363  if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
364  computeDeclContext(*SS))
365  return false;
366 
367  // The code is missing a 'template' keyword prior to the dependent template
368  // name.
370  Diag(IILoc, diag::err_template_kw_missing)
371  << Qualifier << II.getName()
372  << FixItHint::CreateInsertion(IILoc, "template ");
373  SuggestedTemplate
374  = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
375  SuggestedKind = TNK_Dependent_template_name;
376  return true;
377 }
378 
380  QualType ObjectType, bool EnteringContext,
381  RequiredTemplateKind RequiredTemplate,
382  AssumedTemplateKind *ATK,
383  bool AllowTypoCorrection) {
384  if (ATK)
386 
387  if (SS.isInvalid())
388  return true;
389 
390  Found.setTemplateNameLookup(true);
391 
392  // Determine where to perform name lookup
393  DeclContext *LookupCtx = nullptr;
394  bool IsDependent = false;
395  if (!ObjectType.isNull()) {
396  // This nested-name-specifier occurs in a member access expression, e.g.,
397  // x->B::f, and we are looking into the type of the object.
398  assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
399  LookupCtx = computeDeclContext(ObjectType);
400  IsDependent = !LookupCtx && ObjectType->isDependentType();
401  assert((IsDependent || !ObjectType->isIncompleteType() ||
402  !ObjectType->getAs<TagType>() ||
403  ObjectType->castAs<TagType>()->isBeingDefined()) &&
404  "Caller should have completed object type");
405 
406  // Template names cannot appear inside an Objective-C class or object type
407  // or a vector type.
408  //
409  // FIXME: This is wrong. For example:
410  //
411  // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
412  // Vec<int> vi;
413  // vi.Vec<int>::~Vec<int>();
414  //
415  // ... should be accepted but we will not treat 'Vec' as a template name
416  // here. The right thing to do would be to check if the name is a valid
417  // vector component name, and look up a template name if not. And similarly
418  // for lookups into Objective-C class and object types, where the same
419  // problem can arise.
420  if (ObjectType->isObjCObjectOrInterfaceType() ||
421  ObjectType->isVectorType()) {
422  Found.clear();
423  return false;
424  }
425  } else if (SS.isNotEmpty()) {
426  // This nested-name-specifier occurs after another nested-name-specifier,
427  // so long into the context associated with the prior nested-name-specifier.
428  LookupCtx = computeDeclContext(SS, EnteringContext);
429  IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
430 
431  // The declaration context must be complete.
432  if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
433  return true;
434  }
435 
436  bool ObjectTypeSearchedInScope = false;
437  bool AllowFunctionTemplatesInLookup = true;
438  if (LookupCtx) {
439  // Perform "qualified" name lookup into the declaration context we
440  // computed, which is either the type of the base of a member access
441  // expression or the declaration context associated with a prior
442  // nested-name-specifier.
443  LookupQualifiedName(Found, LookupCtx);
444 
445  // FIXME: The C++ standard does not clearly specify what happens in the
446  // case where the object type is dependent, and implementations vary. In
447  // Clang, we treat a name after a . or -> as a template-name if lookup
448  // finds a non-dependent member or member of the current instantiation that
449  // is a type template, or finds no such members and lookup in the context
450  // of the postfix-expression finds a type template. In the latter case, the
451  // name is nonetheless dependent, and we may resolve it to a member of an
452  // unknown specialization when we come to instantiate the template.
453  IsDependent |= Found.wasNotFoundInCurrentInstantiation();
454  }
455 
456  if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
457  // C++ [basic.lookup.classref]p1:
458  // In a class member access expression (5.2.5), if the . or -> token is
459  // immediately followed by an identifier followed by a <, the
460  // identifier must be looked up to determine whether the < is the
461  // beginning of a template argument list (14.2) or a less-than operator.
462  // The identifier is first looked up in the class of the object
463  // expression. If the identifier is not found, it is then looked up in
464  // the context of the entire postfix-expression and shall name a class
465  // template.
466  if (S)
467  LookupName(Found, S);
468 
469  if (!ObjectType.isNull()) {
470  // FIXME: We should filter out all non-type templates here, particularly
471  // variable templates and concepts. But the exclusion of alias templates
472  // and template template parameters is a wording defect.
473  AllowFunctionTemplatesInLookup = false;
474  ObjectTypeSearchedInScope = true;
475  }
476 
477  IsDependent |= Found.wasNotFoundInCurrentInstantiation();
478  }
479 
480  if (Found.isAmbiguous())
481  return false;
482 
483  if (ATK && SS.isEmpty() && ObjectType.isNull() &&
484  !RequiredTemplate.hasTemplateKeyword()) {
485  // C++2a [temp.names]p2:
486  // A name is also considered to refer to a template if it is an
487  // unqualified-id followed by a < and name lookup finds either one or more
488  // functions or finds nothing.
489  //
490  // To keep our behavior consistent, we apply the "finds nothing" part in
491  // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
492  // successfully form a call to an undeclared template-id.
493  bool AllFunctions =
494  getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
495  return isa<FunctionDecl>(ND->getUnderlyingDecl());
496  });
497  if (AllFunctions || (Found.empty() && !IsDependent)) {
498  // If lookup found any functions, or if this is a name that can only be
499  // used for a function, then strongly assume this is a function
500  // template-id.
501  *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
502  ? AssumedTemplateKind::FoundNothing
503  : AssumedTemplateKind::FoundFunctions;
504  Found.clear();
505  return false;
506  }
507  }
508 
509  if (Found.empty() && !IsDependent && AllowTypoCorrection) {
510  // If we did not find any names, and this is not a disambiguation, attempt
511  // to correct any typos.
512  DeclarationName Name = Found.getLookupName();
513  Found.clear();
514  // Simple filter callback that, for keywords, only accepts the C++ *_cast
515  DefaultFilterCCC FilterCCC{};
516  FilterCCC.WantTypeSpecifiers = false;
517  FilterCCC.WantExpressionKeywords = false;
518  FilterCCC.WantRemainingKeywords = false;
519  FilterCCC.WantCXXNamedCasts = true;
520  if (TypoCorrection Corrected =
521  CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
522  &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
523  if (auto *ND = Corrected.getFoundDecl())
524  Found.addDecl(ND);
525  FilterAcceptableTemplateNames(Found);
526  if (Found.isAmbiguous()) {
527  Found.clear();
528  } else if (!Found.empty()) {
529  Found.setLookupName(Corrected.getCorrection());
530  if (LookupCtx) {
531  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
532  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
533  Name.getAsString() == CorrectedStr;
534  diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
535  << Name << LookupCtx << DroppedSpecifier
536  << SS.getRange());
537  } else {
538  diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
539  }
540  }
541  }
542  }
543 
544  NamedDecl *ExampleLookupResult =
545  Found.empty() ? nullptr : Found.getRepresentativeDecl();
546  FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
547  if (Found.empty()) {
548  if (IsDependent) {
549  Found.setNotFoundInCurrentInstantiation();
550  return false;
551  }
552 
553  // If a 'template' keyword was used, a lookup that finds only non-template
554  // names is an error.
555  if (ExampleLookupResult && RequiredTemplate) {
556  Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
557  << Found.getLookupName() << SS.getRange()
558  << RequiredTemplate.hasTemplateKeyword()
559  << RequiredTemplate.getTemplateKeywordLoc();
560  Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
561  diag::note_template_kw_refers_to_non_template)
562  << Found.getLookupName();
563  return true;
564  }
565 
566  return false;
567  }
568 
569  if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
570  !getLangOpts().CPlusPlus11) {
571  // C++03 [basic.lookup.classref]p1:
572  // [...] If the lookup in the class of the object expression finds a
573  // template, the name is also looked up in the context of the entire
574  // postfix-expression and [...]
575  //
576  // Note: C++11 does not perform this second lookup.
577  LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
578  LookupOrdinaryName);
579  FoundOuter.setTemplateNameLookup(true);
580  LookupName(FoundOuter, S);
581  // FIXME: We silently accept an ambiguous lookup here, in violation of
582  // [basic.lookup]/1.
583  FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
584 
585  NamedDecl *OuterTemplate;
586  if (FoundOuter.empty()) {
587  // - if the name is not found, the name found in the class of the
588  // object expression is used, otherwise
589  } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
590  !(OuterTemplate =
591  getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
592  // - if the name is found in the context of the entire
593  // postfix-expression and does not name a class template, the name
594  // found in the class of the object expression is used, otherwise
595  FoundOuter.clear();
596  } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
597  // - if the name found is a class template, it must refer to the same
598  // entity as the one found in the class of the object expression,
599  // otherwise the program is ill-formed.
600  if (!Found.isSingleResult() ||
601  getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
602  OuterTemplate->getCanonicalDecl()) {
603  Diag(Found.getNameLoc(),
604  diag::ext_nested_name_member_ref_lookup_ambiguous)
605  << Found.getLookupName()
606  << ObjectType;
607  Diag(Found.getRepresentativeDecl()->getLocation(),
608  diag::note_ambig_member_ref_object_type)
609  << ObjectType;
610  Diag(FoundOuter.getFoundDecl()->getLocation(),
611  diag::note_ambig_member_ref_scope);
612 
613  // Recover by taking the template that we found in the object
614  // expression's type.
615  }
616  }
617  }
618 
619  return false;
620 }
621 
623  SourceLocation Less,
624  SourceLocation Greater) {
625  if (TemplateName.isInvalid())
626  return;
627 
628  DeclarationNameInfo NameInfo;
629  CXXScopeSpec SS;
630  LookupNameKind LookupKind;
631 
632  DeclContext *LookupCtx = nullptr;
633  NamedDecl *Found = nullptr;
634  bool MissingTemplateKeyword = false;
635 
636  // Figure out what name we looked up.
637  if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
638  NameInfo = DRE->getNameInfo();
639  SS.Adopt(DRE->getQualifierLoc());
640  LookupKind = LookupOrdinaryName;
641  Found = DRE->getFoundDecl();
642  } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
643  NameInfo = ME->getMemberNameInfo();
644  SS.Adopt(ME->getQualifierLoc());
645  LookupKind = LookupMemberName;
646  LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
647  Found = ME->getMemberDecl();
648  } else if (auto *DSDRE =
649  dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
650  NameInfo = DSDRE->getNameInfo();
651  SS.Adopt(DSDRE->getQualifierLoc());
652  MissingTemplateKeyword = true;
653  } else if (auto *DSME =
654  dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
655  NameInfo = DSME->getMemberNameInfo();
656  SS.Adopt(DSME->getQualifierLoc());
657  MissingTemplateKeyword = true;
658  } else {
659  llvm_unreachable("unexpected kind of potential template name");
660  }
661 
662  // If this is a dependent-scope lookup, diagnose that the 'template' keyword
663  // was missing.
664  if (MissingTemplateKeyword) {
665  Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
666  << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
667  return;
668  }
669 
670  // Try to correct the name by looking for templates and C++ named casts.
671  struct TemplateCandidateFilter : CorrectionCandidateCallback {
672  Sema &S;
673  TemplateCandidateFilter(Sema &S) : S(S) {
674  WantTypeSpecifiers = false;
675  WantExpressionKeywords = false;
676  WantRemainingKeywords = false;
677  WantCXXNamedCasts = true;
678  };
679  bool ValidateCandidate(const TypoCorrection &Candidate) override {
680  if (auto *ND = Candidate.getCorrectionDecl())
681  return S.getAsTemplateNameDecl(ND);
682  return Candidate.isKeyword();
683  }
684 
685  std::unique_ptr<CorrectionCandidateCallback> clone() override {
686  return std::make_unique<TemplateCandidateFilter>(*this);
687  }
688  };
689 
690  DeclarationName Name = NameInfo.getName();
691  TemplateCandidateFilter CCC(*this);
692  if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
693  CTK_ErrorRecovery, LookupCtx)) {
694  auto *ND = Corrected.getFoundDecl();
695  if (ND)
696  ND = getAsTemplateNameDecl(ND);
697  if (ND || Corrected.isKeyword()) {
698  if (LookupCtx) {
699  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
700  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
701  Name.getAsString() == CorrectedStr;
702  diagnoseTypo(Corrected,
703  PDiag(diag::err_non_template_in_member_template_id_suggest)
704  << Name << LookupCtx << DroppedSpecifier
705  << SS.getRange(), false);
706  } else {
707  diagnoseTypo(Corrected,
708  PDiag(diag::err_non_template_in_template_id_suggest)
709  << Name, false);
710  }
711  if (Found)
712  Diag(Found->getLocation(),
713  diag::note_non_template_in_template_id_found);
714  return;
715  }
716  }
717 
718  Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
719  << Name << SourceRange(Less, Greater);
720  if (Found)
721  Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
722 }
723 
726  SourceLocation TemplateKWLoc,
727  const DeclarationNameInfo &NameInfo,
728  bool isAddressOfOperand,
729  const TemplateArgumentListInfo *TemplateArgs) {
730  if (SS.isEmpty()) {
731  // FIXME: This codepath is only used by dependent unqualified names
732  // (e.g. a dependent conversion-function-id, or operator= once we support
733  // it). It doesn't quite do the right thing, and it will silently fail if
734  // getCurrentThisType() returns null.
735  QualType ThisType = getCurrentThisType();
736  if (ThisType.isNull())
737  return ExprError();
738 
740  Context, /*Base=*/nullptr, ThisType,
741  /*IsArrow=*/!Context.getLangOpts().HLSL,
742  /*OperatorLoc=*/SourceLocation(),
743  /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
744  /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
745  }
746  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
747 }
748 
751  SourceLocation TemplateKWLoc,
752  const DeclarationNameInfo &NameInfo,
753  const TemplateArgumentListInfo *TemplateArgs) {
754  // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
755  if (!SS.isValid())
756  return CreateRecoveryExpr(
757  SS.getBeginLoc(),
758  TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
759 
761  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
762  TemplateArgs);
763 }
764 
766  NamedDecl *Instantiation,
767  bool InstantiatedFromMember,
768  const NamedDecl *Pattern,
769  const NamedDecl *PatternDef,
771  bool Complain /*= true*/) {
772  assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
773  isa<VarDecl>(Instantiation));
774 
775  bool IsEntityBeingDefined = false;
776  if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
777  IsEntityBeingDefined = TD->isBeingDefined();
778 
779  if (PatternDef && !IsEntityBeingDefined) {
780  NamedDecl *SuggestedDef = nullptr;
781  if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
782  &SuggestedDef,
783  /*OnlyNeedComplete*/ false)) {
784  // If we're allowed to diagnose this and recover, do so.
785  bool Recover = Complain && !isSFINAEContext();
786  if (Complain)
787  diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
789  return !Recover;
790  }
791  return false;
792  }
793 
794  if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
795  return true;
796 
797  QualType InstantiationTy;
798  if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
799  InstantiationTy = Context.getTypeDeclType(TD);
800  if (PatternDef) {
801  Diag(PointOfInstantiation,
802  diag::err_template_instantiate_within_definition)
803  << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
804  << InstantiationTy;
805  // Not much point in noting the template declaration here, since
806  // we're lexically inside it.
807  Instantiation->setInvalidDecl();
808  } else if (InstantiatedFromMember) {
809  if (isa<FunctionDecl>(Instantiation)) {
810  Diag(PointOfInstantiation,
811  diag::err_explicit_instantiation_undefined_member)
812  << /*member function*/ 1 << Instantiation->getDeclName()
813  << Instantiation->getDeclContext();
814  Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
815  } else {
816  assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
817  Diag(PointOfInstantiation,
818  diag::err_implicit_instantiate_member_undefined)
819  << InstantiationTy;
820  Diag(Pattern->getLocation(), diag::note_member_declared_at);
821  }
822  } else {
823  if (isa<FunctionDecl>(Instantiation)) {
824  Diag(PointOfInstantiation,
825  diag::err_explicit_instantiation_undefined_func_template)
826  << Pattern;
827  Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
828  } else if (isa<TagDecl>(Instantiation)) {
829  Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
830  << (TSK != TSK_ImplicitInstantiation)
831  << InstantiationTy;
832  NoteTemplateLocation(*Pattern);
833  } else {
834  assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
835  if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
836  Diag(PointOfInstantiation,
837  diag::err_explicit_instantiation_undefined_var_template)
838  << Instantiation;
839  Instantiation->setInvalidDecl();
840  } else
841  Diag(PointOfInstantiation,
842  diag::err_explicit_instantiation_undefined_member)
843  << /*static data member*/ 2 << Instantiation->getDeclName()
844  << Instantiation->getDeclContext();
845  Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
846  }
847  }
848 
849  // In general, Instantiation isn't marked invalid to get more than one
850  // error for multiple undefined instantiations. But the code that does
851  // explicit declaration -> explicit definition conversion can't handle
852  // invalid declarations, so mark as invalid in that case.
854  Instantiation->setInvalidDecl();
855  return true;
856 }
857 
859  bool SupportedForCompatibility) {
860  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
861 
862  // C++23 [temp.local]p6:
863  // The name of a template-parameter shall not be bound to any following.
864  // declaration whose locus is contained by the scope to which the
865  // template-parameter belongs.
866  //
867  // When MSVC compatibility is enabled, the diagnostic is always a warning
868  // by default. Otherwise, it an error unless SupportedForCompatibility is
869  // true, in which case it is a default-to-error warning.
870  unsigned DiagId =
871  getLangOpts().MSVCCompat
872  ? diag::ext_template_param_shadow
873  : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
874  : diag::err_template_param_shadow);
875  const auto *ND = cast<NamedDecl>(PrevDecl);
876  Diag(Loc, DiagId) << ND->getDeclName();
877  NoteTemplateParameterLocation(*ND);
878 }
879 
881  if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
882  D = Temp->getTemplatedDecl();
883  return Temp;
884  }
885  return nullptr;
886 }
887 
889  SourceLocation EllipsisLoc) const {
890  assert(Kind == Template &&
891  "Only template template arguments can be pack expansions here");
892  assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
893  "Template template argument pack expansion without packs");
894  ParsedTemplateArgument Result(*this);
895  Result.EllipsisLoc = EllipsisLoc;
896  return Result;
897 }
898 
900  const ParsedTemplateArgument &Arg) {
901 
902  switch (Arg.getKind()) {
904  TypeSourceInfo *DI;
905  QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
906  if (!DI)
907  DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
909  }
910 
912  Expr *E = static_cast<Expr *>(Arg.getAsExpr());
914  }
915 
917  TemplateName Template = Arg.getAsTemplate().get();
918  TemplateArgument TArg;
919  if (Arg.getEllipsisLoc().isValid())
920  TArg = TemplateArgument(Template, std::optional<unsigned int>());
921  else
922  TArg = Template;
923  return TemplateArgumentLoc(
924  SemaRef.Context, TArg,
926  Arg.getLocation(), Arg.getEllipsisLoc());
927  }
928  }
929 
930  llvm_unreachable("Unhandled parsed template argument");
931 }
932 
934  TemplateArgumentListInfo &TemplateArgs) {
935  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
936  TemplateArgs.addArgument(translateTemplateArgument(*this,
937  TemplateArgsIn[I]));
938 }
939 
942  const IdentifierInfo *Name) {
943  NamedDecl *PrevDecl =
946  if (PrevDecl && PrevDecl->isTemplateParameter())
947  SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
948 }
949 
951  TypeSourceInfo *TInfo;
952  QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
953  if (T.isNull())
954  return ParsedTemplateArgument();
955  assert(TInfo && "template argument with no location");
956 
957  // If we might have formed a deduced template specialization type, convert
958  // it to a template template argument.
959  if (getLangOpts().CPlusPlus17) {
960  TypeLoc TL = TInfo->getTypeLoc();
961  SourceLocation EllipsisLoc;
962  if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
963  EllipsisLoc = PET.getEllipsisLoc();
964  TL = PET.getPatternLoc();
965  }
966 
967  CXXScopeSpec SS;
968  if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
969  SS.Adopt(ET.getQualifierLoc());
970  TL = ET.getNamedTypeLoc();
971  }
972 
973  if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
974  TemplateName Name = DTST.getTypePtr()->getTemplateName();
975  ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
976  DTST.getTemplateNameLoc());
977  if (EllipsisLoc.isValid())
978  Result = Result.getTemplatePackExpansion(EllipsisLoc);
979  return Result;
980  }
981  }
982 
983  // This is a normal type template argument. Note, if the type template
984  // argument is an injected-class-name for a template, it has a dual nature
985  // and can be used as either a type or a template. We handle that in
986  // convertTypeTemplateArgumentToTemplate.
989  TInfo->getTypeLoc().getBeginLoc());
990 }
991 
993  SourceLocation EllipsisLoc,
994  SourceLocation KeyLoc,
995  IdentifierInfo *ParamName,
996  SourceLocation ParamNameLoc,
997  unsigned Depth, unsigned Position,
998  SourceLocation EqualLoc,
999  ParsedType DefaultArg,
1000  bool HasTypeConstraint) {
1001  assert(S->isTemplateParamScope() &&
1002  "Template type parameter not in template parameter scope!");
1003 
1004  bool IsParameterPack = EllipsisLoc.isValid();
1005  TemplateTypeParmDecl *Param
1007  KeyLoc, ParamNameLoc, Depth, Position,
1008  ParamName, Typename, IsParameterPack,
1009  HasTypeConstraint);
1010  Param->setAccess(AS_public);
1011 
1012  if (Param->isParameterPack())
1013  if (auto *LSI = getEnclosingLambda())
1014  LSI->LocalPacks.push_back(Param);
1015 
1016  if (ParamName) {
1017  maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1018 
1019  // Add the template parameter into the current scope.
1020  S->AddDecl(Param);
1021  IdResolver.AddDecl(Param);
1022  }
1023 
1024  // C++0x [temp.param]p9:
1025  // A default template-argument may be specified for any kind of
1026  // template-parameter that is not a template parameter pack.
1027  if (DefaultArg && IsParameterPack) {
1028  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1029  DefaultArg = nullptr;
1030  }
1031 
1032  // Handle the default argument, if provided.
1033  if (DefaultArg) {
1034  TypeSourceInfo *DefaultTInfo;
1035  GetTypeFromParser(DefaultArg, &DefaultTInfo);
1036 
1037  assert(DefaultTInfo && "expected source information for type");
1038 
1039  // Check for unexpanded parameter packs.
1040  if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1041  UPPC_DefaultArgument))
1042  return Param;
1043 
1044  // Check the template argument itself.
1045  if (CheckTemplateArgument(DefaultTInfo)) {
1046  Param->setInvalidDecl();
1047  return Param;
1048  }
1049 
1050  Param->setDefaultArgument(
1051  Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1052  }
1053 
1054  return Param;
1055 }
1056 
1057 /// Convert the parser's template argument list representation into our form.
1060  TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1061  TemplateId.RAngleLoc);
1062  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1063  TemplateId.NumArgs);
1064  S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1065  return TemplateArgs;
1066 }
1067 
1069 
1070  TemplateName TN = TypeConstr->Template.get();
1071  ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1072 
1073  // C++2a [temp.param]p4:
1074  // [...] The concept designated by a type-constraint shall be a type
1075  // concept ([temp.concept]).
1076  if (!CD->isTypeConcept()) {
1077  Diag(TypeConstr->TemplateNameLoc,
1078  diag::err_type_constraint_non_type_concept);
1079  return true;
1080  }
1081 
1082  if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1083  return true;
1084 
1085  bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1086 
1087  if (!WereArgsSpecified &&
1089  Diag(TypeConstr->TemplateNameLoc,
1090  diag::err_type_constraint_missing_arguments)
1091  << CD;
1092  return true;
1093  }
1094  return false;
1095 }
1096 
1098  TemplateIdAnnotation *TypeConstr,
1099  TemplateTypeParmDecl *ConstrainedParameter,
1100  SourceLocation EllipsisLoc) {
1101  return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1102  false);
1103 }
1104 
1106  TemplateIdAnnotation *TypeConstr,
1107  TemplateTypeParmDecl *ConstrainedParameter,
1108  SourceLocation EllipsisLoc,
1109  bool AllowUnexpandedPack) {
1110 
1111  if (CheckTypeConstraint(TypeConstr))
1112  return true;
1113 
1114  TemplateName TN = TypeConstr->Template.get();
1115  ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1117 
1118  DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1119  TypeConstr->TemplateNameLoc);
1120 
1121  TemplateArgumentListInfo TemplateArgs;
1122  if (TypeConstr->LAngleLoc.isValid()) {
1123  TemplateArgs =
1124  makeTemplateArgumentListInfo(*this, *TypeConstr);
1125 
1126  if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1127  for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1128  if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint))
1129  return true;
1130  }
1131  }
1132  }
1133  return AttachTypeConstraint(
1134  SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1135  ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1136  TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1137  ConstrainedParameter, EllipsisLoc);
1138 }
1139 
1140 template <typename ArgumentLocAppender>
1143  ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1144  SourceLocation RAngleLoc, QualType ConstrainedType,
1145  SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1146  SourceLocation EllipsisLoc) {
1147 
1148  TemplateArgumentListInfo ConstraintArgs;
1149  ConstraintArgs.addArgument(
1151  /*NTTPType=*/QualType(), ParamNameLoc));
1152 
1153  ConstraintArgs.setRAngleLoc(RAngleLoc);
1154  ConstraintArgs.setLAngleLoc(LAngleLoc);
1155  Appender(ConstraintArgs);
1156 
1157  // C++2a [temp.param]p4:
1158  // [...] This constraint-expression E is called the immediately-declared
1159  // constraint of T. [...]
1160  CXXScopeSpec SS;
1161  SS.Adopt(NS);
1162  ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1163  SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1164  /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, NamedConcept,
1165  &ConstraintArgs);
1166  if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1167  return ImmediatelyDeclaredConstraint;
1168 
1169  // C++2a [temp.param]p4:
1170  // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1171  //
1172  // We have the following case:
1173  //
1174  // template<typename T> concept C1 = true;
1175  // template<C1... T> struct s1;
1176  //
1177  // The constraint: (C1<T> && ...)
1178  //
1179  // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1180  // any unqualified lookups for 'operator&&' here.
1181  return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1182  /*LParenLoc=*/SourceLocation(),
1183  ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1184  EllipsisLoc, /*RHS=*/nullptr,
1185  /*RParenLoc=*/SourceLocation(),
1186  /*NumExpansions=*/std::nullopt);
1187 }
1188 
1190  DeclarationNameInfo NameInfo,
1191  ConceptDecl *NamedConcept, NamedDecl *FoundDecl,
1192  const TemplateArgumentListInfo *TemplateArgs,
1193  TemplateTypeParmDecl *ConstrainedParameter,
1194  SourceLocation EllipsisLoc) {
1195  // C++2a [temp.param]p4:
1196  // [...] If Q is of the form C<A1, ..., An>, then let E' be
1197  // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1198  const ASTTemplateArgumentListInfo *ArgsAsWritten =
1199  TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1200  *TemplateArgs) : nullptr;
1201 
1202  QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1203 
1204  ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1205  *this, NS, NameInfo, NamedConcept, FoundDecl,
1206  TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1207  TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1208  ParamAsArgument, ConstrainedParameter->getLocation(),
1209  [&](TemplateArgumentListInfo &ConstraintArgs) {
1210  if (TemplateArgs)
1211  for (const auto &ArgLoc : TemplateArgs->arguments())
1212  ConstraintArgs.addArgument(ArgLoc);
1213  },
1214  EllipsisLoc);
1215  if (ImmediatelyDeclaredConstraint.isInvalid())
1216  return true;
1217 
1218  auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1219  /*TemplateKWLoc=*/SourceLocation{},
1220  /*ConceptNameInfo=*/NameInfo,
1221  /*FoundDecl=*/FoundDecl,
1222  /*NamedConcept=*/NamedConcept,
1223  /*ArgsWritten=*/ArgsAsWritten);
1224  ConstrainedParameter->setTypeConstraint(CL,
1225  ImmediatelyDeclaredConstraint.get());
1226  return false;
1227 }
1228 
1230  NonTypeTemplateParmDecl *NewConstrainedParm,
1231  NonTypeTemplateParmDecl *OrigConstrainedParm,
1232  SourceLocation EllipsisLoc) {
1233  if (NewConstrainedParm->getType() != TL.getType() ||
1235  Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1236  diag::err_unsupported_placeholder_constraint)
1237  << NewConstrainedParm->getTypeSourceInfo()
1238  ->getTypeLoc()
1239  .getSourceRange();
1240  return true;
1241  }
1242  // FIXME: Concepts: This should be the type of the placeholder, but this is
1243  // unclear in the wording right now.
1244  DeclRefExpr *Ref =
1245  BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1246  VK_PRValue, OrigConstrainedParm->getLocation());
1247  if (!Ref)
1248  return true;
1249  ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1251  TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1252  TL.getRAngleLoc(), BuildDecltypeType(Ref),
1253  OrigConstrainedParm->getLocation(),
1254  [&](TemplateArgumentListInfo &ConstraintArgs) {
1255  for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1256  ConstraintArgs.addArgument(TL.getArgLoc(I));
1257  },
1258  EllipsisLoc);
1259  if (ImmediatelyDeclaredConstraint.isInvalid() ||
1260  !ImmediatelyDeclaredConstraint.isUsable())
1261  return true;
1262 
1263  NewConstrainedParm->setPlaceholderTypeConstraint(
1264  ImmediatelyDeclaredConstraint.get());
1265  return false;
1266 }
1267 
1269  SourceLocation Loc) {
1270  if (TSI->getType()->isUndeducedType()) {
1271  // C++17 [temp.dep.expr]p3:
1272  // An id-expression is type-dependent if it contains
1273  // - an identifier associated by name lookup with a non-type
1274  // template-parameter declared with a type that contains a
1275  // placeholder type (7.1.7.4),
1276  TSI = SubstAutoTypeSourceInfoDependent(TSI);
1277  }
1278 
1279  return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1280 }
1281 
1283  if (T->isDependentType())
1284  return false;
1285 
1286  if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1287  return true;
1288 
1289  if (T->isStructuralType())
1290  return false;
1291 
1292  // Structural types are required to be object types or lvalue references.
1293  if (T->isRValueReferenceType()) {
1294  Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1295  return true;
1296  }
1297 
1298  // Don't mention structural types in our diagnostic prior to C++20. Also,
1299  // there's not much more we can say about non-scalar non-class types --
1300  // because we can't see functions or arrays here, those can only be language
1301  // extensions.
1302  if (!getLangOpts().CPlusPlus20 ||
1303  (!T->isScalarType() && !T->isRecordType())) {
1304  Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1305  return true;
1306  }
1307 
1308  // Structural types are required to be literal types.
1309  if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1310  return true;
1311 
1312  Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1313 
1314  // Drill down into the reason why the class is non-structural.
1315  while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1316  // All members are required to be public and non-mutable, and can't be of
1317  // rvalue reference type. Check these conditions first to prefer a "local"
1318  // reason over a more distant one.
1319  for (const FieldDecl *FD : RD->fields()) {
1320  if (FD->getAccess() != AS_public) {
1321  Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1322  return true;
1323  }
1324  if (FD->isMutable()) {
1325  Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1326  return true;
1327  }
1328  if (FD->getType()->isRValueReferenceType()) {
1329  Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1330  << T;
1331  return true;
1332  }
1333  }
1334 
1335  // All bases are required to be public.
1336  for (const auto &BaseSpec : RD->bases()) {
1337  if (BaseSpec.getAccessSpecifier() != AS_public) {
1338  Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1339  << T << 1;
1340  return true;
1341  }
1342  }
1343 
1344  // All subobjects are required to be of structural types.
1345  SourceLocation SubLoc;
1346  QualType SubType;
1347  int Kind = -1;
1348 
1349  for (const FieldDecl *FD : RD->fields()) {
1350  QualType T = Context.getBaseElementType(FD->getType());
1351  if (!T->isStructuralType()) {
1352  SubLoc = FD->getLocation();
1353  SubType = T;
1354  Kind = 0;
1355  break;
1356  }
1357  }
1358 
1359  if (Kind == -1) {
1360  for (const auto &BaseSpec : RD->bases()) {
1361  QualType T = BaseSpec.getType();
1362  if (!T->isStructuralType()) {
1363  SubLoc = BaseSpec.getBaseTypeLoc();
1364  SubType = T;
1365  Kind = 1;
1366  break;
1367  }
1368  }
1369  }
1370 
1371  assert(Kind != -1 && "couldn't find reason why type is not structural");
1372  Diag(SubLoc, diag::note_not_structural_subobject)
1373  << T << Kind << SubType;
1374  T = SubType;
1375  RD = T->getAsCXXRecordDecl();
1376  }
1377 
1378  return true;
1379 }
1380 
1382  SourceLocation Loc) {
1383  // We don't allow variably-modified types as the type of non-type template
1384  // parameters.
1385  if (T->isVariablyModifiedType()) {
1386  Diag(Loc, diag::err_variably_modified_nontype_template_param)
1387  << T;
1388  return QualType();
1389  }
1390 
1391  // C++ [temp.param]p4:
1392  //
1393  // A non-type template-parameter shall have one of the following
1394  // (optionally cv-qualified) types:
1395  //
1396  // -- integral or enumeration type,
1397  if (T->isIntegralOrEnumerationType() ||
1398  // -- pointer to object or pointer to function,
1399  T->isPointerType() ||
1400  // -- lvalue reference to object or lvalue reference to function,
1401  T->isLValueReferenceType() ||
1402  // -- pointer to member,
1403  T->isMemberPointerType() ||
1404  // -- std::nullptr_t, or
1405  T->isNullPtrType() ||
1406  // -- a type that contains a placeholder type.
1407  T->isUndeducedType()) {
1408  // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1409  // are ignored when determining its type.
1410  return T.getUnqualifiedType();
1411  }
1412 
1413  // C++ [temp.param]p8:
1414  //
1415  // A non-type template-parameter of type "array of T" or
1416  // "function returning T" is adjusted to be of type "pointer to
1417  // T" or "pointer to function returning T", respectively.
1418  if (T->isArrayType() || T->isFunctionType())
1419  return Context.getDecayedType(T);
1420 
1421  // If T is a dependent type, we can't do the check now, so we
1422  // assume that it is well-formed. Note that stripping off the
1423  // qualifiers here is not really correct if T turns out to be
1424  // an array type, but we'll recompute the type everywhere it's
1425  // used during instantiation, so that should be OK. (Using the
1426  // qualified type is equally wrong.)
1427  if (T->isDependentType())
1428  return T.getUnqualifiedType();
1429 
1430  // C++20 [temp.param]p6:
1431  // -- a structural type
1432  if (RequireStructuralType(T, Loc))
1433  return QualType();
1434 
1435  if (!getLangOpts().CPlusPlus20) {
1436  // FIXME: Consider allowing structural types as an extension in C++17. (In
1437  // earlier language modes, the template argument evaluation rules are too
1438  // inflexible.)
1439  Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1440  return QualType();
1441  }
1442 
1443  Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1444  return T.getUnqualifiedType();
1445 }
1446 
1448  unsigned Depth,
1449  unsigned Position,
1450  SourceLocation EqualLoc,
1451  Expr *Default) {
1452  TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1453 
1454  // Check that we have valid decl-specifiers specified.
1455  auto CheckValidDeclSpecifiers = [this, &D] {
1456  // C++ [temp.param]
1457  // p1
1458  // template-parameter:
1459  // ...
1460  // parameter-declaration
1461  // p2
1462  // ... A storage class shall not be specified in a template-parameter
1463  // declaration.
1464  // [dcl.typedef]p1:
1465  // The typedef specifier [...] shall not be used in the decl-specifier-seq
1466  // of a parameter-declaration
1467  const DeclSpec &DS = D.getDeclSpec();
1468  auto EmitDiag = [this](SourceLocation Loc) {
1469  Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1471  };
1473  EmitDiag(DS.getStorageClassSpecLoc());
1474 
1476  EmitDiag(DS.getThreadStorageClassSpecLoc());
1477 
1478  // [dcl.inline]p1:
1479  // The inline specifier can be applied only to the declaration or
1480  // definition of a variable or function.
1481 
1482  if (DS.isInlineSpecified())
1483  EmitDiag(DS.getInlineSpecLoc());
1484 
1485  // [dcl.constexpr]p1:
1486  // The constexpr specifier shall be applied only to the definition of a
1487  // variable or variable template or the declaration of a function or
1488  // function template.
1489 
1490  if (DS.hasConstexprSpecifier())
1491  EmitDiag(DS.getConstexprSpecLoc());
1492 
1493  // [dcl.fct.spec]p1:
1494  // Function-specifiers can be used only in function declarations.
1495 
1496  if (DS.isVirtualSpecified())
1497  EmitDiag(DS.getVirtualSpecLoc());
1498 
1499  if (DS.hasExplicitSpecifier())
1500  EmitDiag(DS.getExplicitSpecLoc());
1501 
1502  if (DS.isNoreturnSpecified())
1503  EmitDiag(DS.getNoreturnSpecLoc());
1504  };
1505 
1506  CheckValidDeclSpecifiers();
1507 
1508  if (const auto *T = TInfo->getType()->getContainedDeducedType())
1509  if (isa<AutoType>(T))
1510  Diag(D.getIdentifierLoc(),
1511  diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1512  << QualType(TInfo->getType()->getContainedAutoType(), 0);
1513 
1514  assert(S->isTemplateParamScope() &&
1515  "Non-type template parameter not in template parameter scope!");
1516  bool Invalid = false;
1517 
1518  QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1519  if (T.isNull()) {
1520  T = Context.IntTy; // Recover with an 'int' type.
1521  Invalid = true;
1522  }
1523 
1524  CheckFunctionOrTemplateParamDeclarator(S, D);
1525 
1526  const IdentifierInfo *ParamName = D.getIdentifier();
1527  bool IsParameterPack = D.hasEllipsis();
1529  Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1530  D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1531  TInfo);
1532  Param->setAccess(AS_public);
1533 
1534  if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1535  if (TL.isConstrained())
1536  if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1537  Invalid = true;
1538 
1539  if (Invalid)
1540  Param->setInvalidDecl();
1541 
1542  if (Param->isParameterPack())
1543  if (auto *LSI = getEnclosingLambda())
1544  LSI->LocalPacks.push_back(Param);
1545 
1546  if (ParamName) {
1547  maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1548  ParamName);
1549 
1550  // Add the template parameter into the current scope.
1551  S->AddDecl(Param);
1552  IdResolver.AddDecl(Param);
1553  }
1554 
1555  // C++0x [temp.param]p9:
1556  // A default template-argument may be specified for any kind of
1557  // template-parameter that is not a template parameter pack.
1558  if (Default && IsParameterPack) {
1559  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1560  Default = nullptr;
1561  }
1562 
1563  // Check the well-formedness of the default template argument, if provided.
1564  if (Default) {
1565  // Check for unexpanded parameter packs.
1566  if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1567  return Param;
1568 
1569  Param->setDefaultArgument(
1570  Context, getTrivialTemplateArgumentLoc(TemplateArgument(Default),
1571  QualType(), SourceLocation()));
1572  }
1573 
1574  return Param;
1575 }
1576 
1578  Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
1579  bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *Name,
1580  SourceLocation NameLoc, unsigned Depth, unsigned Position,
1581  SourceLocation EqualLoc, ParsedTemplateArgument Default) {
1582  assert(S->isTemplateParamScope() &&
1583  "Template template parameter not in template parameter scope!");
1584 
1585  // Construct the parameter object.
1586  bool IsParameterPack = EllipsisLoc.isValid();
1588  Context, Context.getTranslationUnitDecl(),
1589  NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1590  Name, Typename, Params);
1591  Param->setAccess(AS_public);
1592 
1593  if (Param->isParameterPack())
1594  if (auto *LSI = getEnclosingLambda())
1595  LSI->LocalPacks.push_back(Param);
1596 
1597  // If the template template parameter has a name, then link the identifier
1598  // into the scope and lookup mechanisms.
1599  if (Name) {
1600  maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1601 
1602  S->AddDecl(Param);
1603  IdResolver.AddDecl(Param);
1604  }
1605 
1606  if (Params->size() == 0) {
1607  Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1608  << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1609  Param->setInvalidDecl();
1610  }
1611 
1612  // C++0x [temp.param]p9:
1613  // A default template-argument may be specified for any kind of
1614  // template-parameter that is not a template parameter pack.
1615  if (IsParameterPack && !Default.isInvalid()) {
1616  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1618  }
1619 
1620  if (!Default.isInvalid()) {
1621  // Check only that we have a template template argument. We don't want to
1622  // try to check well-formedness now, because our template template parameter
1623  // might have dependent types in its template parameters, which we wouldn't
1624  // be able to match now.
1625  //
1626  // If none of the template template parameter's template arguments mention
1627  // other template parameters, we could actually perform more checking here.
1628  // However, it isn't worth doing.
1630  if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1631  Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1632  << DefaultArg.getSourceRange();
1633  return Param;
1634  }
1635 
1636  // Check for unexpanded parameter packs.
1637  if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1638  DefaultArg.getArgument().getAsTemplate(),
1639  UPPC_DefaultArgument))
1640  return Param;
1641 
1642  Param->setDefaultArgument(Context, DefaultArg);
1643  }
1644 
1645  return Param;
1646 }
1647 
1648 namespace {
1649 class ConstraintRefersToContainingTemplateChecker
1650  : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1651  bool Result = false;
1652  const FunctionDecl *Friend = nullptr;
1653  unsigned TemplateDepth = 0;
1654 
1655  // Check a record-decl that we've seen to see if it is a lexical parent of the
1656  // Friend, likely because it was referred to without its template arguments.
1657  void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1658  CheckingRD = CheckingRD->getMostRecentDecl();
1659  if (!CheckingRD->isTemplated())
1660  return;
1661 
1662  for (const DeclContext *DC = Friend->getLexicalDeclContext();
1663  DC && !DC->isFileContext(); DC = DC->getParent())
1664  if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1665  if (CheckingRD == RD->getMostRecentDecl())
1666  Result = true;
1667  }
1668 
1669  void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1670  assert(D->getDepth() <= TemplateDepth &&
1671  "Nothing should reference a value below the actual template depth, "
1672  "depth is likely wrong");
1673  if (D->getDepth() != TemplateDepth)
1674  Result = true;
1675 
1676  // Necessary because the type of the NTTP might be what refers to the parent
1677  // constriant.
1678  TransformType(D->getType());
1679  }
1680 
1681 public:
1683 
1684  ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1685  const FunctionDecl *Friend,
1686  unsigned TemplateDepth)
1687  : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1688  bool getResult() const { return Result; }
1689 
1690  // This should be the only template parm type that we have to deal with.
1691  // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1692  // FunctionParmPackExpr are all partially substituted, which cannot happen
1693  // with concepts at this point in translation.
1694  using inherited::TransformTemplateTypeParmType;
1695  QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1696  TemplateTypeParmTypeLoc TL, bool) {
1697  assert(TL.getDecl()->getDepth() <= TemplateDepth &&
1698  "Nothing should reference a value below the actual template depth, "
1699  "depth is likely wrong");
1700  if (TL.getDecl()->getDepth() != TemplateDepth)
1701  Result = true;
1702  return inherited::TransformTemplateTypeParmType(
1703  TLB, TL,
1704  /*SuppressObjCLifetime=*/false);
1705  }
1706 
1707  Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1708  if (!D)
1709  return D;
1710  // FIXME : This is possibly an incomplete list, but it is unclear what other
1711  // Decl kinds could be used to refer to the template parameters. This is a
1712  // best guess so far based on examples currently available, but the
1713  // unreachable should catch future instances/cases.
1714  if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1715  TransformType(TD->getUnderlyingType());
1716  else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1717  CheckNonTypeTemplateParmDecl(NTTPD);
1718  else if (auto *VD = dyn_cast<ValueDecl>(D))
1719  TransformType(VD->getType());
1720  else if (auto *TD = dyn_cast<TemplateDecl>(D))
1721  TransformTemplateParameterList(TD->getTemplateParameters());
1722  else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1723  CheckIfContainingRecord(RD);
1724  else if (isa<NamedDecl>(D)) {
1725  // No direct types to visit here I believe.
1726  } else
1727  llvm_unreachable("Don't know how to handle this declaration type yet");
1728  return D;
1729  }
1730 };
1731 } // namespace
1732 
1734  const FunctionDecl *Friend, unsigned TemplateDepth,
1735  const Expr *Constraint) {
1736  assert(Friend->getFriendObjectKind() && "Only works on a friend");
1737  ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1738  TemplateDepth);
1739  Checker.TransformExpr(const_cast<Expr *>(Constraint));
1740  return Checker.getResult();
1741 }
1742 
1745  SourceLocation ExportLoc,
1746  SourceLocation TemplateLoc,
1747  SourceLocation LAngleLoc,
1748  ArrayRef<NamedDecl *> Params,
1749  SourceLocation RAngleLoc,
1750  Expr *RequiresClause) {
1751  if (ExportLoc.isValid())
1752  Diag(ExportLoc, diag::warn_template_export_unsupported);
1753 
1754  for (NamedDecl *P : Params)
1755  warnOnReservedIdentifier(P);
1756 
1758  Context, TemplateLoc, LAngleLoc,
1759  llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1760 }
1761 
1763  const CXXScopeSpec &SS) {
1764  if (SS.isSet())
1765  T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1766 }
1767 
1768 // Returns the template parameter list with all default template argument
1769 // information.
1771  // Make sure we get the template parameter list from the most
1772  // recent declaration, since that is the only one that is guaranteed to
1773  // have all the default template argument information.
1774  Decl *D = TD->getMostRecentDecl();
1775  // C++11 N3337 [temp.param]p12:
1776  // A default template argument shall not be specified in a friend class
1777  // template declaration.
1778  //
1779  // Skip past friend *declarations* because they are not supposed to contain
1780  // default template arguments. Moreover, these declarations may introduce
1781  // template parameters living in different template depths than the
1782  // corresponding template parameters in TD, causing unmatched constraint
1783  // substitution.
1784  //
1785  // FIXME: Diagnose such cases within a class template:
1786  // template <class T>
1787  // struct S {
1788  // template <class = void> friend struct C;
1789  // };
1790  // template struct S<int>;
1791  while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1792  D->getPreviousDecl())
1793  D = D->getPreviousDecl();
1794  return cast<TemplateDecl>(D)->getTemplateParameters();
1795 }
1796 
1798  Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1799  CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1800  const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1801  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1802  SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1803  TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1804  assert(TemplateParams && TemplateParams->size() > 0 &&
1805  "No template parameters");
1806  assert(TUK != TagUseKind::Reference &&
1807  "Can only declare or define class templates");
1808  bool Invalid = false;
1809 
1810  // Check that we can declare a template here.
1811  if (CheckTemplateDeclScope(S, TemplateParams))
1812  return true;
1813 
1815  assert(Kind != TagTypeKind::Enum &&
1816  "can't build template of enumerated type");
1817 
1818  // There is no such thing as an unnamed class template.
1819  if (!Name) {
1820  Diag(KWLoc, diag::err_template_unnamed_class);
1821  return true;
1822  }
1823 
1824  // Find any previous declaration with this name. For a friend with no
1825  // scope explicitly specified, we only look for tag declarations (per
1826  // C++11 [basic.lookup.elab]p2).
1827  DeclContext *SemanticContext;
1828  LookupResult Previous(*this, Name, NameLoc,
1829  (SS.isEmpty() && TUK == TagUseKind::Friend)
1830  ? LookupTagName
1831  : LookupOrdinaryName,
1832  forRedeclarationInCurContext());
1833  if (SS.isNotEmpty() && !SS.isInvalid()) {
1834  SemanticContext = computeDeclContext(SS, true);
1835  if (!SemanticContext) {
1836  // FIXME: Horrible, horrible hack! We can't currently represent this
1837  // in the AST, and historically we have just ignored such friend
1838  // class templates, so don't complain here.
1839  Diag(NameLoc, TUK == TagUseKind::Friend
1840  ? diag::warn_template_qualified_friend_ignored
1841  : diag::err_template_qualified_declarator_no_match)
1842  << SS.getScopeRep() << SS.getRange();
1843  return TUK != TagUseKind::Friend;
1844  }
1845 
1846  if (RequireCompleteDeclContext(SS, SemanticContext))
1847  return true;
1848 
1849  // If we're adding a template to a dependent context, we may need to
1850  // rebuilding some of the types used within the template parameter list,
1851  // now that we know what the current instantiation is.
1852  if (SemanticContext->isDependentContext()) {
1853  ContextRAII SavedContext(*this, SemanticContext);
1854  if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1855  Invalid = true;
1856  }
1857 
1858  if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1859  diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1860  /*TemplateId-*/ nullptr,
1861  /*IsMemberSpecialization*/ false);
1862 
1863  LookupQualifiedName(Previous, SemanticContext);
1864  } else {
1865  SemanticContext = CurContext;
1866 
1867  // C++14 [class.mem]p14:
1868  // If T is the name of a class, then each of the following shall have a
1869  // name different from T:
1870  // -- every member template of class T
1871  if (TUK != TagUseKind::Friend &&
1872  DiagnoseClassNameShadow(SemanticContext,
1873  DeclarationNameInfo(Name, NameLoc)))
1874  return true;
1875 
1876  LookupName(Previous, S);
1877  }
1878 
1879  if (Previous.isAmbiguous())
1880  return true;
1881 
1882  NamedDecl *PrevDecl = nullptr;
1883  if (Previous.begin() != Previous.end())
1884  PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1885 
1886  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1887  // Maybe we will complain about the shadowed template parameter.
1888  DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1889  // Just pretend that we didn't see the previous declaration.
1890  PrevDecl = nullptr;
1891  }
1892 
1893  // If there is a previous declaration with the same name, check
1894  // whether this is a valid redeclaration.
1895  ClassTemplateDecl *PrevClassTemplate =
1896  dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1897 
1898  // We may have found the injected-class-name of a class template,
1899  // class template partial specialization, or class template specialization.
1900  // In these cases, grab the template that is being defined or specialized.
1901  if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
1902  cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1903  PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1904  PrevClassTemplate
1905  = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1906  if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1907  PrevClassTemplate
1908  = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1909  ->getSpecializedTemplate();
1910  }
1911  }
1912 
1913  if (TUK == TagUseKind::Friend) {
1914  // C++ [namespace.memdef]p3:
1915  // [...] When looking for a prior declaration of a class or a function
1916  // declared as a friend, and when the name of the friend class or
1917  // function is neither a qualified name nor a template-id, scopes outside
1918  // the innermost enclosing namespace scope are not considered.
1919  if (!SS.isSet()) {
1920  DeclContext *OutermostContext = CurContext;
1921  while (!OutermostContext->isFileContext())
1922  OutermostContext = OutermostContext->getLookupParent();
1923 
1924  if (PrevDecl &&
1925  (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1926  OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1927  SemanticContext = PrevDecl->getDeclContext();
1928  } else {
1929  // Declarations in outer scopes don't matter. However, the outermost
1930  // context we computed is the semantic context for our new
1931  // declaration.
1932  PrevDecl = PrevClassTemplate = nullptr;
1933  SemanticContext = OutermostContext;
1934 
1935  // Check that the chosen semantic context doesn't already contain a
1936  // declaration of this name as a non-tag type.
1937  Previous.clear(LookupOrdinaryName);
1938  DeclContext *LookupContext = SemanticContext;
1939  while (LookupContext->isTransparentContext())
1940  LookupContext = LookupContext->getLookupParent();
1941  LookupQualifiedName(Previous, LookupContext);
1942 
1943  if (Previous.isAmbiguous())
1944  return true;
1945 
1946  if (Previous.begin() != Previous.end())
1947  PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1948  }
1949  }
1950  } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
1951  SemanticContext, S, SS.isValid()))
1952  PrevDecl = PrevClassTemplate = nullptr;
1953 
1954  if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1955  PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1956  if (SS.isEmpty() &&
1957  !(PrevClassTemplate &&
1958  PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1959  SemanticContext->getRedeclContext()))) {
1960  Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1961  Diag(Shadow->getTargetDecl()->getLocation(),
1962  diag::note_using_decl_target);
1963  Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1964  // Recover by ignoring the old declaration.
1965  PrevDecl = PrevClassTemplate = nullptr;
1966  }
1967  }
1968 
1969  if (PrevClassTemplate) {
1970  // Ensure that the template parameter lists are compatible. Skip this check
1971  // for a friend in a dependent context: the template parameter list itself
1972  // could be dependent.
1973  if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
1974  !TemplateParameterListsAreEqual(
1975  TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
1976  : CurContext,
1977  CurContext, KWLoc),
1978  TemplateParams, PrevClassTemplate,
1979  PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
1980  TPL_TemplateMatch))
1981  return true;
1982 
1983  // C++ [temp.class]p4:
1984  // In a redeclaration, partial specialization, explicit
1985  // specialization or explicit instantiation of a class template,
1986  // the class-key shall agree in kind with the original class
1987  // template declaration (7.1.5.3).
1988  RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1989  if (!isAcceptableTagRedeclaration(
1990  PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
1991  Diag(KWLoc, diag::err_use_with_wrong_tag)
1992  << Name
1993  << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1994  Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1995  Kind = PrevRecordDecl->getTagKind();
1996  }
1997 
1998  // Check for redefinition of this class template.
1999  if (TUK == TagUseKind::Definition) {
2000  if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2001  // If we have a prior definition that is not visible, treat this as
2002  // simply making that previous definition visible.
2003  NamedDecl *Hidden = nullptr;
2004  if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2005  SkipBody->ShouldSkip = true;
2006  SkipBody->Previous = Def;
2007  auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2008  assert(Tmpl && "original definition of a class template is not a "
2009  "class template?");
2010  makeMergedDefinitionVisible(Hidden);
2011  makeMergedDefinitionVisible(Tmpl);
2012  } else {
2013  Diag(NameLoc, diag::err_redefinition) << Name;
2014  Diag(Def->getLocation(), diag::note_previous_definition);
2015  // FIXME: Would it make sense to try to "forget" the previous
2016  // definition, as part of error recovery?
2017  return true;
2018  }
2019  }
2020  }
2021  } else if (PrevDecl) {
2022  // C++ [temp]p5:
2023  // A class template shall not have the same name as any other
2024  // template, class, function, object, enumeration, enumerator,
2025  // namespace, or type in the same scope (3.3), except as specified
2026  // in (14.5.4).
2027  Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2028  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2029  return true;
2030  }
2031 
2032  // Check the template parameter list of this declaration, possibly
2033  // merging in the template parameter list from the previous class
2034  // template declaration. Skip this check for a friend in a dependent
2035  // context, because the template parameter list might be dependent.
2036  if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2037  CheckTemplateParameterList(
2038  TemplateParams,
2039  PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2040  : nullptr,
2041  (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2042  SemanticContext->isDependentContext())
2043  ? TPC_ClassTemplateMember
2044  : TUK == TagUseKind::Friend ? TPC_FriendClassTemplate
2045  : TPC_ClassTemplate,
2046  SkipBody))
2047  Invalid = true;
2048 
2049  if (SS.isSet()) {
2050  // If the name of the template was qualified, we must be defining the
2051  // template out-of-line.
2052  if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2053  Diag(NameLoc, TUK == TagUseKind::Friend
2054  ? diag::err_friend_decl_does_not_match
2055  : diag::err_member_decl_does_not_match)
2056  << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2057  Invalid = true;
2058  }
2059  }
2060 
2061  // If this is a templated friend in a dependent context we should not put it
2062  // on the redecl chain. In some cases, the templated friend can be the most
2063  // recent declaration tricking the template instantiator to make substitutions
2064  // there.
2065  // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2066  bool ShouldAddRedecl =
2067  !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2068 
2069  CXXRecordDecl *NewClass =
2070  CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2071  PrevClassTemplate && ShouldAddRedecl ?
2072  PrevClassTemplate->getTemplatedDecl() : nullptr,
2073  /*DelayTypeCreation=*/true);
2074  SetNestedNameSpecifier(*this, NewClass, SS);
2075  if (NumOuterTemplateParamLists > 0)
2077  Context,
2078  llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2079 
2080  // Add alignment attributes if necessary; these attributes are checked when
2081  // the ASTContext lays out the structure.
2082  if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2083  AddAlignmentAttributesForRecord(NewClass);
2084  AddMsStructLayoutForRecord(NewClass);
2085  }
2086 
2087  ClassTemplateDecl *NewTemplate
2088  = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2089  DeclarationName(Name), TemplateParams,
2090  NewClass);
2091 
2092  if (ShouldAddRedecl)
2093  NewTemplate->setPreviousDecl(PrevClassTemplate);
2094 
2095  NewClass->setDescribedClassTemplate(NewTemplate);
2096 
2097  if (ModulePrivateLoc.isValid())
2098  NewTemplate->setModulePrivate();
2099 
2100  // Build the type for the class template declaration now.
2102  T = Context.getInjectedClassNameType(NewClass, T);
2103  assert(T->isDependentType() && "Class template type is not dependent?");
2104  (void)T;
2105 
2106  // If we are providing an explicit specialization of a member that is a
2107  // class template, make a note of that.
2108  if (PrevClassTemplate &&
2109  PrevClassTemplate->getInstantiatedFromMemberTemplate())
2110  PrevClassTemplate->setMemberSpecialization();
2111 
2112  // Set the access specifier.
2113  if (!Invalid && TUK != TagUseKind::Friend &&
2114  NewTemplate->getDeclContext()->isRecord())
2115  SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2116 
2117  // Set the lexical context of these templates
2118  NewClass->setLexicalDeclContext(CurContext);
2119  NewTemplate->setLexicalDeclContext(CurContext);
2120 
2121  if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2122  NewClass->startDefinition();
2123 
2124  ProcessDeclAttributeList(S, NewClass, Attr);
2125  ProcessAPINotes(NewClass);
2126 
2127  if (PrevClassTemplate)
2128  mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2129 
2130  AddPushedVisibilityAttribute(NewClass);
2131  inferGslOwnerPointerAttribute(NewClass);
2132  inferNullableClassAttribute(NewClass);
2133 
2134  if (TUK != TagUseKind::Friend) {
2135  // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2136  Scope *Outer = S;
2137  while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2138  Outer = Outer->getParent();
2139  PushOnScopeChains(NewTemplate, Outer);
2140  } else {
2141  if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2142  NewTemplate->setAccess(PrevClassTemplate->getAccess());
2143  NewClass->setAccess(PrevClassTemplate->getAccess());
2144  }
2145 
2146  NewTemplate->setObjectOfFriendDecl();
2147 
2148  // Friend templates are visible in fairly strange ways.
2149  if (!CurContext->isDependentContext()) {
2150  DeclContext *DC = SemanticContext->getRedeclContext();
2151  DC->makeDeclVisibleInContext(NewTemplate);
2152  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2153  PushOnScopeChains(NewTemplate, EnclosingScope,
2154  /* AddToContext = */ false);
2155  }
2156 
2158  Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2159  Friend->setAccess(AS_public);
2160  CurContext->addDecl(Friend);
2161  }
2162 
2163  if (PrevClassTemplate)
2164  CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2165 
2166  if (Invalid) {
2167  NewTemplate->setInvalidDecl();
2168  NewClass->setInvalidDecl();
2169  }
2170 
2171  ActOnDocumentableDecl(NewTemplate);
2172 
2173  if (SkipBody && SkipBody->ShouldSkip)
2174  return SkipBody->Previous;
2175 
2176  return NewTemplate;
2177 }
2178 
2179 /// Diagnose the presence of a default template argument on a
2180 /// template parameter, which is ill-formed in certain contexts.
2181 ///
2182 /// \returns true if the default template argument should be dropped.
2185  SourceLocation ParamLoc,
2186  SourceRange DefArgRange) {
2187  switch (TPC) {
2189  case Sema::TPC_VarTemplate:
2191  return false;
2192 
2195  // C++ [temp.param]p9:
2196  // A default template-argument shall not be specified in a
2197  // function template declaration or a function template
2198  // definition [...]
2199  // If a friend function template declaration specifies a default
2200  // template-argument, that declaration shall be a definition and shall be
2201  // the only declaration of the function template in the translation unit.
2202  // (C++98/03 doesn't have this wording; see DR226).
2203  S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2204  diag::warn_cxx98_compat_template_parameter_default_in_function_template
2205  : diag::ext_template_parameter_default_in_function_template)
2206  << DefArgRange;
2207  return false;
2208 
2210  // C++0x [temp.param]p9:
2211  // A default template-argument shall not be specified in the
2212  // template-parameter-lists of the definition of a member of a
2213  // class template that appears outside of the member's class.
2214  S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2215  << DefArgRange;
2216  return true;
2217 
2220  // C++ [temp.param]p9:
2221  // A default template-argument shall not be specified in a
2222  // friend template declaration.
2223  S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2224  << DefArgRange;
2225  return true;
2226 
2227  // FIXME: C++0x [temp.param]p9 allows default template-arguments
2228  // for friend function templates if there is only a single
2229  // declaration (and it is a definition). Strange!
2230  }
2231 
2232  llvm_unreachable("Invalid TemplateParamListContext!");
2233 }
2234 
2235 /// Check for unexpanded parameter packs within the template parameters
2236 /// of a template template parameter, recursively.
2238  TemplateTemplateParmDecl *TTP) {
2239  // A template template parameter which is a parameter pack is also a pack
2240  // expansion.
2241  if (TTP->isParameterPack())
2242  return false;
2243 
2245  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2246  NamedDecl *P = Params->getParam(I);
2247  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2248  if (!TTP->isParameterPack())
2249  if (const TypeConstraint *TC = TTP->getTypeConstraint())
2250  if (TC->hasExplicitTemplateArgs())
2251  for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2252  if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2254  return true;
2255  continue;
2256  }
2257 
2258  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2259  if (!NTTP->isParameterPack() &&
2260  S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2261  NTTP->getTypeSourceInfo(),
2263  return true;
2264 
2265  continue;
2266  }
2267 
2268  if (TemplateTemplateParmDecl *InnerTTP
2269  = dyn_cast<TemplateTemplateParmDecl>(P))
2270  if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2271  return true;
2272  }
2273 
2274  return false;
2275 }
2276 
2278  TemplateParameterList *OldParams,
2280  SkipBodyInfo *SkipBody) {
2281  bool Invalid = false;
2282 
2283  // C++ [temp.param]p10:
2284  // The set of default template-arguments available for use with a
2285  // template declaration or definition is obtained by merging the
2286  // default arguments from the definition (if in scope) and all
2287  // declarations in scope in the same way default function
2288  // arguments are (8.3.6).
2289  bool SawDefaultArgument = false;
2290  SourceLocation PreviousDefaultArgLoc;
2291 
2292  // Dummy initialization to avoid warnings.
2293  TemplateParameterList::iterator OldParam = NewParams->end();
2294  if (OldParams)
2295  OldParam = OldParams->begin();
2296 
2297  bool RemoveDefaultArguments = false;
2298  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2299  NewParamEnd = NewParams->end();
2300  NewParam != NewParamEnd; ++NewParam) {
2301  // Whether we've seen a duplicate default argument in the same translation
2302  // unit.
2303  bool RedundantDefaultArg = false;
2304  // Whether we've found inconsis inconsitent default arguments in different
2305  // translation unit.
2306  bool InconsistentDefaultArg = false;
2307  // The name of the module which contains the inconsistent default argument.
2308  std::string PrevModuleName;
2309 
2310  SourceLocation OldDefaultLoc;
2311  SourceLocation NewDefaultLoc;
2312 
2313  // Variable used to diagnose missing default arguments
2314  bool MissingDefaultArg = false;
2315 
2316  // Variable used to diagnose non-final parameter packs
2317  bool SawParameterPack = false;
2318 
2319  if (TemplateTypeParmDecl *NewTypeParm
2320  = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2321  // Check the presence of a default argument here.
2322  if (NewTypeParm->hasDefaultArgument() &&
2324  *this, TPC, NewTypeParm->getLocation(),
2325  NewTypeParm->getDefaultArgument().getSourceRange()))
2326  NewTypeParm->removeDefaultArgument();
2327 
2328  // Merge default arguments for template type parameters.
2329  TemplateTypeParmDecl *OldTypeParm
2330  = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2331  if (NewTypeParm->isParameterPack()) {
2332  assert(!NewTypeParm->hasDefaultArgument() &&
2333  "Parameter packs can't have a default argument!");
2334  SawParameterPack = true;
2335  } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2336  NewTypeParm->hasDefaultArgument() &&
2337  (!SkipBody || !SkipBody->ShouldSkip)) {
2338  OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2339  NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2340  SawDefaultArgument = true;
2341 
2342  if (!OldTypeParm->getOwningModule())
2343  RedundantDefaultArg = true;
2344  else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2345  NewTypeParm)) {
2346  InconsistentDefaultArg = true;
2347  PrevModuleName =
2348  OldTypeParm->getImportedOwningModule()->getFullModuleName();
2349  }
2350  PreviousDefaultArgLoc = NewDefaultLoc;
2351  } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2352  // Merge the default argument from the old declaration to the
2353  // new declaration.
2354  NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2355  PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2356  } else if (NewTypeParm->hasDefaultArgument()) {
2357  SawDefaultArgument = true;
2358  PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2359  } else if (SawDefaultArgument)
2360  MissingDefaultArg = true;
2361  } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2362  = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2363  // Check for unexpanded parameter packs.
2364  if (!NewNonTypeParm->isParameterPack() &&
2365  DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2366  NewNonTypeParm->getTypeSourceInfo(),
2367  UPPC_NonTypeTemplateParameterType)) {
2368  Invalid = true;
2369  continue;
2370  }
2371 
2372  // Check the presence of a default argument here.
2373  if (NewNonTypeParm->hasDefaultArgument() &&
2375  *this, TPC, NewNonTypeParm->getLocation(),
2376  NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2377  NewNonTypeParm->removeDefaultArgument();
2378  }
2379 
2380  // Merge default arguments for non-type template parameters
2381  NonTypeTemplateParmDecl *OldNonTypeParm
2382  = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2383  if (NewNonTypeParm->isParameterPack()) {
2384  assert(!NewNonTypeParm->hasDefaultArgument() &&
2385  "Parameter packs can't have a default argument!");
2386  if (!NewNonTypeParm->isPackExpansion())
2387  SawParameterPack = true;
2388  } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2389  NewNonTypeParm->hasDefaultArgument() &&
2390  (!SkipBody || !SkipBody->ShouldSkip)) {
2391  OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2392  NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2393  SawDefaultArgument = true;
2394  if (!OldNonTypeParm->getOwningModule())
2395  RedundantDefaultArg = true;
2396  else if (!getASTContext().isSameDefaultTemplateArgument(
2397  OldNonTypeParm, NewNonTypeParm)) {
2398  InconsistentDefaultArg = true;
2399  PrevModuleName =
2400  OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2401  }
2402  PreviousDefaultArgLoc = NewDefaultLoc;
2403  } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2404  // Merge the default argument from the old declaration to the
2405  // new declaration.
2406  NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2407  PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2408  } else if (NewNonTypeParm->hasDefaultArgument()) {
2409  SawDefaultArgument = true;
2410  PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2411  } else if (SawDefaultArgument)
2412  MissingDefaultArg = true;
2413  } else {
2414  TemplateTemplateParmDecl *NewTemplateParm
2415  = cast<TemplateTemplateParmDecl>(*NewParam);
2416 
2417  // Check for unexpanded parameter packs, recursively.
2418  if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2419  Invalid = true;
2420  continue;
2421  }
2422 
2423  // Check the presence of a default argument here.
2424  if (NewTemplateParm->hasDefaultArgument() &&
2426  NewTemplateParm->getLocation(),
2427  NewTemplateParm->getDefaultArgument().getSourceRange()))
2428  NewTemplateParm->removeDefaultArgument();
2429 
2430  // Merge default arguments for template template parameters
2431  TemplateTemplateParmDecl *OldTemplateParm
2432  = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2433  if (NewTemplateParm->isParameterPack()) {
2434  assert(!NewTemplateParm->hasDefaultArgument() &&
2435  "Parameter packs can't have a default argument!");
2436  if (!NewTemplateParm->isPackExpansion())
2437  SawParameterPack = true;
2438  } else if (OldTemplateParm &&
2439  hasVisibleDefaultArgument(OldTemplateParm) &&
2440  NewTemplateParm->hasDefaultArgument() &&
2441  (!SkipBody || !SkipBody->ShouldSkip)) {
2442  OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2443  NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2444  SawDefaultArgument = true;
2445  if (!OldTemplateParm->getOwningModule())
2446  RedundantDefaultArg = true;
2447  else if (!getASTContext().isSameDefaultTemplateArgument(
2448  OldTemplateParm, NewTemplateParm)) {
2449  InconsistentDefaultArg = true;
2450  PrevModuleName =
2451  OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2452  }
2453  PreviousDefaultArgLoc = NewDefaultLoc;
2454  } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2455  // Merge the default argument from the old declaration to the
2456  // new declaration.
2457  NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2458  PreviousDefaultArgLoc
2459  = OldTemplateParm->getDefaultArgument().getLocation();
2460  } else if (NewTemplateParm->hasDefaultArgument()) {
2461  SawDefaultArgument = true;
2462  PreviousDefaultArgLoc
2463  = NewTemplateParm->getDefaultArgument().getLocation();
2464  } else if (SawDefaultArgument)
2465  MissingDefaultArg = true;
2466  }
2467 
2468  // C++11 [temp.param]p11:
2469  // If a template parameter of a primary class template or alias template
2470  // is a template parameter pack, it shall be the last template parameter.
2471  if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2472  (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2473  TPC == TPC_TypeAliasTemplate)) {
2474  Diag((*NewParam)->getLocation(),
2475  diag::err_template_param_pack_must_be_last_template_parameter);
2476  Invalid = true;
2477  }
2478 
2479  // [basic.def.odr]/13:
2480  // There can be more than one definition of a
2481  // ...
2482  // default template argument
2483  // ...
2484  // in a program provided that each definition appears in a different
2485  // translation unit and the definitions satisfy the [same-meaning
2486  // criteria of the ODR].
2487  //
2488  // Simply, the design of modules allows the definition of template default
2489  // argument to be repeated across translation unit. Note that the ODR is
2490  // checked elsewhere. But it is still not allowed to repeat template default
2491  // argument in the same translation unit.
2492  if (RedundantDefaultArg) {
2493  Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2494  Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2495  Invalid = true;
2496  } else if (InconsistentDefaultArg) {
2497  // We could only diagnose about the case that the OldParam is imported.
2498  // The case NewParam is imported should be handled in ASTReader.
2499  Diag(NewDefaultLoc,
2500  diag::err_template_param_default_arg_inconsistent_redefinition);
2501  Diag(OldDefaultLoc,
2502  diag::note_template_param_prev_default_arg_in_other_module)
2503  << PrevModuleName;
2504  Invalid = true;
2505  } else if (MissingDefaultArg &&
2506  (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
2507  TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
2508  // C++ 23[temp.param]p14:
2509  // If a template-parameter of a class template, variable template, or
2510  // alias template has a default template argument, each subsequent
2511  // template-parameter shall either have a default template argument
2512  // supplied or be a template parameter pack.
2513  Diag((*NewParam)->getLocation(),
2514  diag::err_template_param_default_arg_missing);
2515  Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2516  Invalid = true;
2517  RemoveDefaultArguments = true;
2518  }
2519 
2520  // If we have an old template parameter list that we're merging
2521  // in, move on to the next parameter.
2522  if (OldParams)
2523  ++OldParam;
2524  }
2525 
2526  // We were missing some default arguments at the end of the list, so remove
2527  // all of the default arguments.
2528  if (RemoveDefaultArguments) {
2529  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2530  NewParamEnd = NewParams->end();
2531  NewParam != NewParamEnd; ++NewParam) {
2532  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2533  TTP->removeDefaultArgument();
2534  else if (NonTypeTemplateParmDecl *NTTP
2535  = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2536  NTTP->removeDefaultArgument();
2537  else
2538  cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2539  }
2540  }
2541 
2542  return Invalid;
2543 }
2544 
2545 namespace {
2546 
2547 /// A class which looks for a use of a certain level of template
2548 /// parameter.
2549 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2551 
2552  unsigned Depth;
2553 
2554  // Whether we're looking for a use of a template parameter that makes the
2555  // overall construct type-dependent / a dependent type. This is strictly
2556  // best-effort for now; we may fail to match at all for a dependent type
2557  // in some cases if this is set.
2558  bool IgnoreNonTypeDependent;
2559 
2560  bool Match;
2561  SourceLocation MatchLoc;
2562 
2563  DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2564  : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2565  Match(false) {}
2566 
2567  DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2568  : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2569  NamedDecl *ND = Params->getParam(0);
2570  if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2571  Depth = PD->getDepth();
2572  } else if (NonTypeTemplateParmDecl *PD =
2573  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2574  Depth = PD->getDepth();
2575  } else {
2576  Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2577  }
2578  }
2579 
2580  bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2581  if (ParmDepth >= Depth) {
2582  Match = true;
2583  MatchLoc = Loc;
2584  return true;
2585  }
2586  return false;
2587  }
2588 
2589  bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2590  // Prune out non-type-dependent expressions if requested. This can
2591  // sometimes result in us failing to find a template parameter reference
2592  // (if a value-dependent expression creates a dependent type), but this
2593  // mode is best-effort only.
2594  if (auto *E = dyn_cast_or_null<Expr>(S))
2595  if (IgnoreNonTypeDependent && !E->isTypeDependent())
2596  return true;
2597  return super::TraverseStmt(S, Q);
2598  }
2599 
2600  bool TraverseTypeLoc(TypeLoc TL) {
2601  if (IgnoreNonTypeDependent && !TL.isNull() &&
2602  !TL.getType()->isDependentType())
2603  return true;
2604  return super::TraverseTypeLoc(TL);
2605  }
2606 
2607  bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2608  return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2609  }
2610 
2611  bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2612  // For a best-effort search, keep looking until we find a location.
2613  return IgnoreNonTypeDependent || !Matches(T->getDepth());
2614  }
2615 
2616  bool TraverseTemplateName(TemplateName N) {
2617  if (TemplateTemplateParmDecl *PD =
2618  dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2619  if (Matches(PD->getDepth()))
2620  return false;
2621  return super::TraverseTemplateName(N);
2622  }
2623 
2624  bool VisitDeclRefExpr(DeclRefExpr *E) {
2625  if (NonTypeTemplateParmDecl *PD =
2626  dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2627  if (Matches(PD->getDepth(), E->getExprLoc()))
2628  return false;
2629  return super::VisitDeclRefExpr(E);
2630  }
2631 
2632  bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2633  return TraverseType(T->getReplacementType());
2634  }
2635 
2636  bool
2637  VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2638  return TraverseTemplateArgument(T->getArgumentPack());
2639  }
2640 
2641  bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2642  return TraverseType(T->getInjectedSpecializationType());
2643  }
2644 };
2645 } // end anonymous namespace
2646 
2647 /// Determines whether a given type depends on the given parameter
2648 /// list.
2649 static bool
2651  if (!Params->size())
2652  return false;
2653 
2654  DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2655  Checker.TraverseType(T);
2656  return Checker.Match;
2657 }
2658 
2659 // Find the source range corresponding to the named type in the given
2660 // nested-name-specifier, if any.
2662  QualType T,
2663  const CXXScopeSpec &SS) {
2665  while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2666  if (const Type *CurType = NNS->getAsType()) {
2667  if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2668  return NNSLoc.getTypeLoc().getSourceRange();
2669  } else
2670  break;
2671 
2672  NNSLoc = NNSLoc.getPrefix();
2673  }
2674 
2675  return SourceRange();
2676 }
2677 
2679  SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2680  TemplateIdAnnotation *TemplateId,
2681  ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2682  bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2683  IsMemberSpecialization = false;
2684  Invalid = false;
2685 
2686  // The sequence of nested types to which we will match up the template
2687  // parameter lists. We first build this list by starting with the type named
2688  // by the nested-name-specifier and walking out until we run out of types.
2689  SmallVector<QualType, 4> NestedTypes;
2690  QualType T;
2691  if (SS.getScopeRep()) {
2692  if (CXXRecordDecl *Record
2693  = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2694  T = Context.getTypeDeclType(Record);
2695  else
2696  T = QualType(SS.getScopeRep()->getAsType(), 0);
2697  }
2698 
2699  // If we found an explicit specialization that prevents us from needing
2700  // 'template<>' headers, this will be set to the location of that
2701  // explicit specialization.
2702  SourceLocation ExplicitSpecLoc;
2703 
2704  while (!T.isNull()) {
2705  NestedTypes.push_back(T);
2706 
2707  // Retrieve the parent of a record type.
2709  // If this type is an explicit specialization, we're done.
2711  = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2712  if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2713  Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2714  ExplicitSpecLoc = Spec->getLocation();
2715  break;
2716  }
2717  } else if (Record->getTemplateSpecializationKind()
2719  ExplicitSpecLoc = Record->getLocation();
2720  break;
2721  }
2722 
2723  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2724  T = Context.getTypeDeclType(Parent);
2725  else
2726  T = QualType();
2727  continue;
2728  }
2729 
2730  if (const TemplateSpecializationType *TST
2732  if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2733  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2734  T = Context.getTypeDeclType(Parent);
2735  else
2736  T = QualType();
2737  continue;
2738  }
2739  }
2740 
2741  // Look one step prior in a dependent template specialization type.
2742  if (const DependentTemplateSpecializationType *DependentTST
2744  if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2745  T = QualType(NNS->getAsType(), 0);
2746  else
2747  T = QualType();
2748  continue;
2749  }
2750 
2751  // Look one step prior in a dependent name type.
2752  if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2753  if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2754  T = QualType(NNS->getAsType(), 0);
2755  else
2756  T = QualType();
2757  continue;
2758  }
2759 
2760  // Retrieve the parent of an enumeration type.
2761  if (const EnumType *EnumT = T->getAs<EnumType>()) {
2762  // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2763  // check here.
2764  EnumDecl *Enum = EnumT->getDecl();
2765 
2766  // Get to the parent type.
2767  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2768  T = Context.getTypeDeclType(Parent);
2769  else
2770  T = QualType();
2771  continue;
2772  }
2773 
2774  T = QualType();
2775  }
2776  // Reverse the nested types list, since we want to traverse from the outermost
2777  // to the innermost while checking template-parameter-lists.
2778  std::reverse(NestedTypes.begin(), NestedTypes.end());
2779 
2780  // C++0x [temp.expl.spec]p17:
2781  // A member or a member template may be nested within many
2782  // enclosing class templates. In an explicit specialization for
2783  // such a member, the member declaration shall be preceded by a
2784  // template<> for each enclosing class template that is
2785  // explicitly specialized.
2786  bool SawNonEmptyTemplateParameterList = false;
2787 
2788  auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2789  if (SawNonEmptyTemplateParameterList) {
2790  if (!SuppressDiagnostic)
2791  Diag(DeclLoc, diag::err_specialize_member_of_template)
2792  << !Recovery << Range;
2793  Invalid = true;
2794  IsMemberSpecialization = false;
2795  return true;
2796  }
2797 
2798  return false;
2799  };
2800 
2801  auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2802  // Check that we can have an explicit specialization here.
2803  if (CheckExplicitSpecialization(Range, true))
2804  return true;
2805 
2806  // We don't have a template header, but we should.
2807  SourceLocation ExpectedTemplateLoc;
2808  if (!ParamLists.empty())
2809  ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2810  else
2811  ExpectedTemplateLoc = DeclStartLoc;
2812 
2813  if (!SuppressDiagnostic)
2814  Diag(DeclLoc, diag::err_template_spec_needs_header)
2815  << Range
2816  << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2817  return false;
2818  };
2819 
2820  unsigned ParamIdx = 0;
2821  for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2822  ++TypeIdx) {
2823  T = NestedTypes[TypeIdx];
2824 
2825  // Whether we expect a 'template<>' header.
2826  bool NeedEmptyTemplateHeader = false;
2827 
2828  // Whether we expect a template header with parameters.
2829  bool NeedNonemptyTemplateHeader = false;
2830 
2831  // For a dependent type, the set of template parameters that we
2832  // expect to see.
2833  TemplateParameterList *ExpectedTemplateParams = nullptr;
2834 
2835  // C++0x [temp.expl.spec]p15:
2836  // A member or a member template may be nested within many enclosing
2837  // class templates. In an explicit specialization for such a member, the
2838  // member declaration shall be preceded by a template<> for each
2839  // enclosing class template that is explicitly specialized.
2842  = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2843  ExpectedTemplateParams = Partial->getTemplateParameters();
2844  NeedNonemptyTemplateHeader = true;
2845  } else if (Record->isDependentType()) {
2846  if (Record->getDescribedClassTemplate()) {
2847  ExpectedTemplateParams = Record->getDescribedClassTemplate()
2848  ->getTemplateParameters();
2849  NeedNonemptyTemplateHeader = true;
2850  }
2851  } else if (ClassTemplateSpecializationDecl *Spec
2852  = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2853  // C++0x [temp.expl.spec]p4:
2854  // Members of an explicitly specialized class template are defined
2855  // in the same manner as members of normal classes, and not using
2856  // the template<> syntax.
2857  if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2858  NeedEmptyTemplateHeader = true;
2859  else
2860  continue;
2861  } else if (Record->getTemplateSpecializationKind()) {
2862  if (Record->getTemplateSpecializationKind()
2864  TypeIdx == NumTypes - 1)
2865  IsMemberSpecialization = true;
2866 
2867  continue;
2868  }
2869  } else if (const TemplateSpecializationType *TST
2871  if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2872  ExpectedTemplateParams = Template->getTemplateParameters();
2873  NeedNonemptyTemplateHeader = true;
2874  }
2875  } else if (T->getAs<DependentTemplateSpecializationType>()) {
2876  // FIXME: We actually could/should check the template arguments here
2877  // against the corresponding template parameter list.
2878  NeedNonemptyTemplateHeader = false;
2879  }
2880 
2881  // C++ [temp.expl.spec]p16:
2882  // In an explicit specialization declaration for a member of a class
2883  // template or a member template that appears in namespace scope, the
2884  // member template and some of its enclosing class templates may remain
2885  // unspecialized, except that the declaration shall not explicitly
2886  // specialize a class member template if its enclosing class templates
2887  // are not explicitly specialized as well.
2888  if (ParamIdx < ParamLists.size()) {
2889  if (ParamLists[ParamIdx]->size() == 0) {
2890  if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2891  false))
2892  return nullptr;
2893  } else
2894  SawNonEmptyTemplateParameterList = true;
2895  }
2896 
2897  if (NeedEmptyTemplateHeader) {
2898  // If we're on the last of the types, and we need a 'template<>' header
2899  // here, then it's a member specialization.
2900  if (TypeIdx == NumTypes - 1)
2901  IsMemberSpecialization = true;
2902 
2903  if (ParamIdx < ParamLists.size()) {
2904  if (ParamLists[ParamIdx]->size() > 0) {
2905  // The header has template parameters when it shouldn't. Complain.
2906  if (!SuppressDiagnostic)
2907  Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2908  diag::err_template_param_list_matches_nontemplate)
2909  << T
2910  << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2911  ParamLists[ParamIdx]->getRAngleLoc())
2912  << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2913  Invalid = true;
2914  return nullptr;
2915  }
2916 
2917  // Consume this template header.
2918  ++ParamIdx;
2919  continue;
2920  }
2921 
2922  if (!IsFriend)
2923  if (DiagnoseMissingExplicitSpecialization(
2924  getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2925  return nullptr;
2926 
2927  continue;
2928  }
2929 
2930  if (NeedNonemptyTemplateHeader) {
2931  // In friend declarations we can have template-ids which don't
2932  // depend on the corresponding template parameter lists. But
2933  // assume that empty parameter lists are supposed to match this
2934  // template-id.
2935  if (IsFriend && T->isDependentType()) {
2936  if (ParamIdx < ParamLists.size() &&
2937  DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2938  ExpectedTemplateParams = nullptr;
2939  else
2940  continue;
2941  }
2942 
2943  if (ParamIdx < ParamLists.size()) {
2944  // Check the template parameter list, if we can.
2945  if (ExpectedTemplateParams &&
2946  !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2947  ExpectedTemplateParams,
2948  !SuppressDiagnostic, TPL_TemplateMatch))
2949  Invalid = true;
2950 
2951  if (!Invalid &&
2952  CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2953  TPC_ClassTemplateMember))
2954  Invalid = true;
2955 
2956  ++ParamIdx;
2957  continue;
2958  }
2959 
2960  if (!SuppressDiagnostic)
2961  Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2962  << T
2963  << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2964  Invalid = true;
2965  continue;
2966  }
2967  }
2968 
2969  // If there were at least as many template-ids as there were template
2970  // parameter lists, then there are no template parameter lists remaining for
2971  // the declaration itself.
2972  if (ParamIdx >= ParamLists.size()) {
2973  if (TemplateId && !IsFriend) {
2974  // We don't have a template header for the declaration itself, but we
2975  // should.
2976  DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2977  TemplateId->RAngleLoc));
2978 
2979  // Fabricate an empty template parameter list for the invented header.
2981  SourceLocation(), std::nullopt,
2982  SourceLocation(), nullptr);
2983  }
2984 
2985  return nullptr;
2986  }
2987 
2988  // If there were too many template parameter lists, complain about that now.
2989  if (ParamIdx < ParamLists.size() - 1) {
2990  bool HasAnyExplicitSpecHeader = false;
2991  bool AllExplicitSpecHeaders = true;
2992  for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2993  if (ParamLists[I]->size() == 0)
2994  HasAnyExplicitSpecHeader = true;
2995  else
2996  AllExplicitSpecHeaders = false;
2997  }
2998 
2999  if (!SuppressDiagnostic)
3000  Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3001  AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3002  : diag::err_template_spec_extra_headers)
3003  << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3004  ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3005 
3006  // If there was a specialization somewhere, such that 'template<>' is
3007  // not required, and there were any 'template<>' headers, note where the
3008  // specialization occurred.
3009  if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3010  !SuppressDiagnostic)
3011  Diag(ExplicitSpecLoc,
3012  diag::note_explicit_template_spec_does_not_need_header)
3013  << NestedTypes.back();
3014 
3015  // We have a template parameter list with no corresponding scope, which
3016  // means that the resulting template declaration can't be instantiated
3017  // properly (we'll end up with dependent nodes when we shouldn't).
3018  if (!AllExplicitSpecHeaders)
3019  Invalid = true;
3020  }
3021 
3022  // C++ [temp.expl.spec]p16:
3023  // In an explicit specialization declaration for a member of a class
3024  // template or a member template that ap- pears in namespace scope, the
3025  // member template and some of its enclosing class templates may remain
3026  // unspecialized, except that the declaration shall not explicitly
3027  // specialize a class member template if its en- closing class templates
3028  // are not explicitly specialized as well.
3029  if (ParamLists.back()->size() == 0 &&
3030  CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3031  false))
3032  return nullptr;
3033 
3034  // Return the last template parameter list, which corresponds to the
3035  // entity being declared.
3036  return ParamLists.back();
3037 }
3038 
3040  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3041  Diag(Template->getLocation(), diag::note_template_declared_here)
3042  << (isa<FunctionTemplateDecl>(Template)
3043  ? 0
3044  : isa<ClassTemplateDecl>(Template)
3045  ? 1
3046  : isa<VarTemplateDecl>(Template)
3047  ? 2
3048  : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3049  << Template->getDeclName();
3050  return;
3051  }
3052 
3053  if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3054  for (OverloadedTemplateStorage::iterator I = OST->begin(),
3055  IEnd = OST->end();
3056  I != IEnd; ++I)
3057  Diag((*I)->getLocation(), diag::note_template_declared_here)
3058  << 0 << (*I)->getDeclName();
3059 
3060  return;
3061  }
3062 }
3063 
3064 static QualType
3066  ArrayRef<TemplateArgument> Converted,
3067  SourceLocation TemplateLoc,
3068  TemplateArgumentListInfo &TemplateArgs) {
3069  ASTContext &Context = SemaRef.getASTContext();
3070 
3071  switch (BTD->getBuiltinTemplateKind()) {
3072  case BTK__make_integer_seq: {
3073  // Specializations of __make_integer_seq<S, T, N> are treated like
3074  // S<T, 0, ..., N-1>.
3075 
3076  QualType OrigType = Converted[1].getAsType();
3077  // C++14 [inteseq.intseq]p1:
3078  // T shall be an integer type.
3079  if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3080  SemaRef.Diag(TemplateArgs[1].getLocation(),
3081  diag::err_integer_sequence_integral_element_type);
3082  return QualType();
3083  }
3084 
3085  TemplateArgument NumArgsArg = Converted[2];
3086  if (NumArgsArg.isDependent())
3088  Converted);
3089 
3090  TemplateArgumentListInfo SyntheticTemplateArgs;
3091  // The type argument, wrapped in substitution sugar, gets reused as the
3092  // first template argument in the synthetic template argument list.
3093  SyntheticTemplateArgs.addArgument(
3096  OrigType, TemplateArgs[1].getLocation())));
3097 
3098  if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3099  // Expand N into 0 ... N-1.
3100  for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3101  I < NumArgs; ++I) {
3102  TemplateArgument TA(Context, I, OrigType);
3103  SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3104  TA, OrigType, TemplateArgs[2].getLocation()));
3105  }
3106  } else {
3107  // C++14 [inteseq.make]p1:
3108  // If N is negative the program is ill-formed.
3109  SemaRef.Diag(TemplateArgs[2].getLocation(),
3110  diag::err_integer_sequence_negative_length);
3111  return QualType();
3112  }
3113 
3114  // The first template argument will be reused as the template decl that
3115  // our synthetic template arguments will be applied to.
3116  return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3117  TemplateLoc, SyntheticTemplateArgs);
3118  }
3119 
3121  // Specializations of
3122  // __type_pack_element<Index, T_1, ..., T_N>
3123  // are treated like T_Index.
3124  assert(Converted.size() == 2 &&
3125  "__type_pack_element should be given an index and a parameter pack");
3126 
3127  TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3128  if (IndexArg.isDependent() || Ts.isDependent())
3130  Converted);
3131 
3132  llvm::APSInt Index = IndexArg.getAsIntegral();
3133  assert(Index >= 0 && "the index used with __type_pack_element should be of "
3134  "type std::size_t, and hence be non-negative");
3135  // If the Index is out of bounds, the program is ill-formed.
3136  if (Index >= Ts.pack_size()) {
3137  SemaRef.Diag(TemplateArgs[0].getLocation(),
3138  diag::err_type_pack_element_out_of_bounds);
3139  return QualType();
3140  }
3141 
3142  // We simply return the type at index `Index`.
3143  int64_t N = Index.getExtValue();
3144  return Ts.getPackAsArray()[N].getAsType();
3145  }
3146  llvm_unreachable("unexpected BuiltinTemplateDecl!");
3147 }
3148 
3149 /// Determine whether this alias template is "enable_if_t".
3150 /// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3151 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3152  return AliasTemplate->getName() == "enable_if_t" ||
3153  AliasTemplate->getName() == "__enable_if_t";
3154 }
3155 
3156 /// Collect all of the separable terms in the given condition, which
3157 /// might be a conjunction.
3158 ///
3159 /// FIXME: The right answer is to convert the logical expression into
3160 /// disjunctive normal form, so we can find the first failed term
3161 /// within each possible clause.
3162 static void collectConjunctionTerms(Expr *Clause,
3163  SmallVectorImpl<Expr *> &Terms) {
3164  if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3165  if (BinOp->getOpcode() == BO_LAnd) {
3166  collectConjunctionTerms(BinOp->getLHS(), Terms);
3167  collectConjunctionTerms(BinOp->getRHS(), Terms);
3168  return;
3169  }
3170  }
3171 
3172  Terms.push_back(Clause);
3173 }
3174 
3175 // The ranges-v3 library uses an odd pattern of a top-level "||" with
3176 // a left-hand side that is value-dependent but never true. Identify
3177 // the idiom and ignore that term.
3179  // Top-level '||'.
3180  auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3181  if (!BinOp) return Cond;
3182 
3183  if (BinOp->getOpcode() != BO_LOr) return Cond;
3184 
3185  // With an inner '==' that has a literal on the right-hand side.
3186  Expr *LHS = BinOp->getLHS();
3187  auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3188  if (!InnerBinOp) return Cond;
3189 
3190  if (InnerBinOp->getOpcode() != BO_EQ ||
3191  !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3192  return Cond;
3193 
3194  // If the inner binary operation came from a macro expansion named
3195  // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3196  // of the '||', which is the real, user-provided condition.
3197  SourceLocation Loc = InnerBinOp->getExprLoc();
3198  if (!Loc.isMacroID()) return Cond;
3199 
3200  StringRef MacroName = PP.getImmediateMacroName(Loc);
3201  if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3202  return BinOp->getRHS();
3203 
3204  return Cond;
3205 }
3206 
3207 namespace {
3208 
3209 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3210 // within failing boolean expression, such as substituting template parameters
3211 // for actual types.
3212 class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3213 public:
3214  explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3215  : Policy(P) {}
3216 
3217  bool handledStmt(Stmt *E, raw_ostream &OS) override {
3218  const auto *DR = dyn_cast<DeclRefExpr>(E);
3219  if (DR && DR->getQualifier()) {
3220  // If this is a qualified name, expand the template arguments in nested
3221  // qualifiers.
3222  DR->getQualifier()->print(OS, Policy, true);
3223  // Then print the decl itself.
3224  const ValueDecl *VD = DR->getDecl();
3225  OS << VD->getName();
3226  if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3227  // This is a template variable, print the expanded template arguments.
3229  OS, IV->getTemplateArgs().asArray(), Policy,
3230  IV->getSpecializedTemplate()->getTemplateParameters());
3231  }
3232  return true;
3233  }
3234  return false;
3235  }
3236 
3237 private:
3238  const PrintingPolicy Policy;
3239 };
3240 
3241 } // end anonymous namespace
3242 
3243 std::pair<Expr *, std::string>
3245  Cond = lookThroughRangesV3Condition(PP, Cond);
3246 
3247  // Separate out all of the terms in a conjunction.
3248  SmallVector<Expr *, 4> Terms;
3249  collectConjunctionTerms(Cond, Terms);
3250 
3251  // Determine which term failed.
3252  Expr *FailedCond = nullptr;
3253  for (Expr *Term : Terms) {
3254  Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3255 
3256  // Literals are uninteresting.
3257  if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3258  isa<IntegerLiteral>(TermAsWritten))
3259  continue;
3260 
3261  // The initialization of the parameter from the argument is
3262  // a constant-evaluated context.
3263  EnterExpressionEvaluationContext ConstantEvaluated(
3265 
3266  bool Succeeded;
3267  if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3268  !Succeeded) {
3269  FailedCond = TermAsWritten;
3270  break;
3271  }
3272  }
3273  if (!FailedCond)
3274  FailedCond = Cond->IgnoreParenImpCasts();
3275 
3276  std::string Description;
3277  {
3278  llvm::raw_string_ostream Out(Description);
3279  PrintingPolicy Policy = getPrintingPolicy();
3280  Policy.PrintCanonicalTypes = true;
3281  FailedBooleanConditionPrinterHelper Helper(Policy);
3282  FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3283  }
3284  return { FailedCond, Description };
3285 }
3286 
3288  SourceLocation TemplateLoc,
3289  TemplateArgumentListInfo &TemplateArgs) {
3291  = Name.getUnderlying().getAsDependentTemplateName();
3292  if (DTN && DTN->isIdentifier())
3293  // When building a template-id where the template-name is dependent,
3294  // assume the template is a type template. Either our assumption is
3295  // correct, or the code is ill-formed and will be diagnosed when the
3296  // dependent name is substituted.
3299  TemplateArgs.arguments());
3300 
3301  if (Name.getAsAssumedTemplateName() &&
3302  resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
3303  return QualType();
3304 
3305  TemplateDecl *Template = Name.getAsTemplateDecl();
3306  if (!Template || isa<FunctionTemplateDecl>(Template) ||
3307  isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3308  // We might have a substituted template template parameter pack. If so,
3309  // build a template specialization type for it.
3310  if (Name.getAsSubstTemplateTemplateParmPack())
3311  return Context.getTemplateSpecializationType(Name,
3312  TemplateArgs.arguments());
3313 
3314  Diag(TemplateLoc, diag::err_template_id_not_a_type)
3315  << Name;
3316  NoteAllFoundTemplates(Name);
3317  return QualType();
3318  }
3319 
3320  // Check that the template argument list is well-formed for this
3321  // template.
3322  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3323  if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false,
3324  SugaredConverted, CanonicalConverted,
3325  /*UpdateArgsWithConversions=*/true))
3326  return QualType();
3327 
3328  QualType CanonType;
3329 
3331  dyn_cast<TypeAliasTemplateDecl>(Template)) {
3332 
3333  // Find the canonical type for this type alias template specialization.
3334  TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3335  if (Pattern->isInvalidDecl())
3336  return QualType();
3337 
3338  // Only substitute for the innermost template argument list. NOTE: Some
3339  // external resugarers rely on leaving a Subst* node here. Make the
3340  // substitution non-final in that case. Note that these external resugarers
3341  // will still miss some information in this representation, because we don't
3342  // provide enough context in the Subst* nodes in order to tell different
3343  // template type alias specializations apart.
3344  MultiLevelTemplateArgumentList TemplateArgLists;
3345  TemplateArgLists.addOuterTemplateArguments(
3346  Template, SugaredConverted,
3347  /*Final=*/!getLangOpts().RetainSubstTemplateTypeParmTypeAstNodes);
3348  TemplateArgLists.addOuterRetainedLevels(
3349  AliasTemplate->getTemplateParameters()->getDepth());
3350 
3352  InstantiatingTemplate Inst(
3353  *this, /*PointOfInstantiation=*/TemplateLoc,
3354  /*Entity=*/AliasTemplate,
3355  /*TemplateArgs=*/TemplateArgLists.getInnermost());
3356 
3357  // Diagnose uses of this alias.
3358  (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3359 
3360  if (Inst.isInvalid())
3361  return QualType();
3362 
3363  std::optional<ContextRAII> SavedContext;
3364  if (!AliasTemplate->getDeclContext()->isFileContext())
3365  SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3366 
3367  CanonType =
3368  SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3369  AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3370  if (CanonType.isNull()) {
3371  // If this was enable_if and we failed to find the nested type
3372  // within enable_if in a SFINAE context, dig out the specific
3373  // enable_if condition that failed and present that instead.
3375  if (auto DeductionInfo = isSFINAEContext()) {
3376  if (*DeductionInfo &&
3377  (*DeductionInfo)->hasSFINAEDiagnostic() &&
3378  (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3379  diag::err_typename_nested_not_found_enable_if &&
3380  TemplateArgs[0].getArgument().getKind()
3382  Expr *FailedCond;
3383  std::string FailedDescription;
3384  std::tie(FailedCond, FailedDescription) =
3385  findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3386 
3387  // Remove the old SFINAE diagnostic.
3388  PartialDiagnosticAt OldDiag =
3390  (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3391 
3392  // Add a new SFINAE diagnostic specifying which condition
3393  // failed.
3394  (*DeductionInfo)->addSFINAEDiagnostic(
3395  OldDiag.first,
3396  PDiag(diag::err_typename_nested_not_found_requirement)
3397  << FailedDescription
3398  << FailedCond->getSourceRange());
3399  }
3400  }
3401  }
3402 
3403  return QualType();
3404  }
3405  } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3406  CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
3407  TemplateLoc, TemplateArgs);
3408  } else if (Name.isDependent() ||
3410  TemplateArgs, CanonicalConverted)) {
3411  // This class template specialization is a dependent
3412  // type. Therefore, its canonical type is another class template
3413  // specialization type that contains all of the converted
3414  // arguments in canonical form. This ensures that, e.g., A<T> and
3415  // A<T, T> have identical types when A is declared as:
3416  //
3417  // template<typename T, typename U = T> struct A;
3418  CanonType = Context.getCanonicalTemplateSpecializationType(
3419  Name, CanonicalConverted);
3420 
3421  // This might work out to be a current instantiation, in which
3422  // case the canonical type needs to be the InjectedClassNameType.
3423  //
3424  // TODO: in theory this could be a simple hashtable lookup; most
3425  // changes to CurContext don't change the set of current
3426  // instantiations.
3427  if (isa<ClassTemplateDecl>(Template)) {
3428  for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3429  // If we get out to a namespace, we're done.
3430  if (Ctx->isFileContext()) break;
3431 
3432  // If this isn't a record, keep looking.
3433  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3434  if (!Record) continue;
3435 
3436  // Look for one of the two cases with InjectedClassNameTypes
3437  // and check whether it's the same template.
3438  if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3439  !Record->getDescribedClassTemplate())
3440  continue;
3441 
3442  // Fetch the injected class name type and check whether its
3443  // injected type is equal to the type we just built.
3444  QualType ICNT = Context.getTypeDeclType(Record);
3445  QualType Injected = cast<InjectedClassNameType>(ICNT)
3446  ->getInjectedSpecializationType();
3447 
3448  if (CanonType != Injected->getCanonicalTypeInternal())
3449  continue;
3450 
3451  // If so, the canonical type of this TST is the injected
3452  // class name type of the record we just found.
3453  assert(ICNT.isCanonical());
3454  CanonType = ICNT;
3455  break;
3456  }
3457  }
3458  } else if (ClassTemplateDecl *ClassTemplate =
3459  dyn_cast<ClassTemplateDecl>(Template)) {
3460  // Find the class template specialization declaration that
3461  // corresponds to these arguments.
3462  void *InsertPos = nullptr;
3464  ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3465  if (!Decl) {
3466  // This is the first time we have referenced this class template
3467  // specialization. Create the canonical declaration and add it to
3468  // the set of specializations.
3470  Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3471  ClassTemplate->getDeclContext(),
3472  ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3473  ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
3474  nullptr);
3475  ClassTemplate->AddSpecialization(Decl, InsertPos);
3476  if (ClassTemplate->isOutOfLine())
3477  Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3478  }
3479 
3480  if (Decl->getSpecializationKind() == TSK_Undeclared &&
3481  ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3482  InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3483  if (!Inst.isInvalid()) {
3484  MultiLevelTemplateArgumentList TemplateArgLists(Template,
3485  CanonicalConverted,
3486  /*Final=*/false);
3487  InstantiateAttrsForDecl(TemplateArgLists,
3488  ClassTemplate->getTemplatedDecl(), Decl);
3489  }
3490  }
3491 
3492  // Diagnose uses of this specialization.
3493  (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3494 
3495  CanonType = Context.getTypeDeclType(Decl);
3496  assert(isa<RecordType>(CanonType) &&
3497  "type of non-dependent specialization is not a RecordType");
3498  } else {
3499  llvm_unreachable("Unhandled template kind");
3500  }
3501 
3502  // Build the fully-sugared type for this class template
3503  // specialization, which refers back to the class template
3504  // specialization we created or found.
3505  return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
3506  CanonType);
3507 }
3508 
3510  TemplateNameKind &TNK,
3511  SourceLocation NameLoc,
3512  IdentifierInfo *&II) {
3513  assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3514 
3515  TemplateName Name = ParsedName.get();
3516  auto *ATN = Name.getAsAssumedTemplateName();
3517  assert(ATN && "not an assumed template name");
3518  II = ATN->getDeclName().getAsIdentifierInfo();
3519 
3520  if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3521  // Resolved to a type template name.
3522  ParsedName = TemplateTy::make(Name);
3523  TNK = TNK_Type_template;
3524  }
3525 }
3526 
3528  SourceLocation NameLoc,
3529  bool Diagnose) {
3530  // We assumed this undeclared identifier to be an (ADL-only) function
3531  // template name, but it was used in a context where a type was required.
3532  // Try to typo-correct it now.
3533  AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3534  assert(ATN && "not an assumed template name");
3535 
3536  LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3537  struct CandidateCallback : CorrectionCandidateCallback {
3538  bool ValidateCandidate(const TypoCorrection &TC) override {
3539  return TC.getCorrectionDecl() &&
3541  }
3542  std::unique_ptr<CorrectionCandidateCallback> clone() override {
3543  return std::make_unique<CandidateCallback>(*this);
3544  }
3545  } FilterCCC;
3546 
3547  TypoCorrection Corrected =
3548  CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3549  FilterCCC, CTK_ErrorRecovery);
3550  if (Corrected && Corrected.getFoundDecl()) {
3551  diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3552  << ATN->getDeclName());
3553  Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3554  return false;
3555  }
3556 
3557  if (Diagnose)
3558  Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3559  return true;
3560 }
3561 
3563  Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3564  TemplateTy TemplateD, const IdentifierInfo *TemplateII,
3565  SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3566  ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3567  bool IsCtorOrDtorName, bool IsClassName,
3568  ImplicitTypenameContext AllowImplicitTypename) {
3569  if (SS.isInvalid())
3570  return true;
3571 
3572  if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3573  DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3574 
3575  // C++ [temp.res]p3:
3576  // A qualified-id that refers to a type and in which the
3577  // nested-name-specifier depends on a template-parameter (14.6.2)
3578  // shall be prefixed by the keyword typename to indicate that the
3579  // qualified-id denotes a type, forming an
3580  // elaborated-type-specifier (7.1.5.3).
3581  if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3582  // C++2a relaxes some of those restrictions in [temp.res]p5.
3583  if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3584  if (getLangOpts().CPlusPlus20)
3585  Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
3586  else
3587  Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
3588  << SS.getScopeRep() << TemplateII->getName()
3589  << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
3590  } else
3591  Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3592  << SS.getScopeRep() << TemplateII->getName();
3593 
3594  // FIXME: This is not quite correct recovery as we don't transform SS
3595  // into the corresponding dependent form (and we don't diagnose missing
3596  // 'template' keywords within SS as a result).
3597  return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3598  TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3599  TemplateArgsIn, RAngleLoc);
3600  }
3601 
3602  // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3603  // it's not actually allowed to be used as a type in most cases. Because
3604  // we annotate it before we know whether it's valid, we have to check for
3605  // this case here.
3606  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3607  if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3608  Diag(TemplateIILoc,
3609  TemplateKWLoc.isInvalid()
3610  ? diag::err_out_of_line_qualified_id_type_names_constructor
3611  : diag::ext_out_of_line_qualified_id_type_names_constructor)
3612  << TemplateII << 0 /*injected-class-name used as template name*/
3613  << 1 /*if any keyword was present, it was 'template'*/;
3614  }
3615  }
3616 
3617  TemplateName Template = TemplateD.get();
3618  if (Template.getAsAssumedTemplateName() &&
3619  resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3620  return true;
3621 
3622  // Translate the parser's template argument list in our AST format.
3623  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3624  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3625 
3626  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3627  assert(SS.getScopeRep() == DTN->getQualifier());
3629  ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3630  TemplateArgs.arguments());
3631  // Build type-source information.
3632  TypeLocBuilder TLB;
3636  SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3637  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3638  SpecTL.setTemplateNameLoc(TemplateIILoc);
3639  SpecTL.setLAngleLoc(LAngleLoc);
3640  SpecTL.setRAngleLoc(RAngleLoc);
3641  for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3642  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3643  return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3644  }
3645 
3646  QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3647  if (SpecTy.isNull())
3648  return true;
3649 
3650  // Build type-source information.
3651  TypeLocBuilder TLB;
3653  TLB.push<TemplateSpecializationTypeLoc>(SpecTy);
3654  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3655  SpecTL.setTemplateNameLoc(TemplateIILoc);
3656  SpecTL.setLAngleLoc(LAngleLoc);
3657  SpecTL.setRAngleLoc(RAngleLoc);
3658  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3659  SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3660 
3661  // Create an elaborated-type-specifier containing the nested-name-specifier.
3662  QualType ElTy =
3663  getElaboratedType(ElaboratedTypeKeyword::None,
3664  !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
3665  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
3667  if (!ElabTL.isEmpty())
3668  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3669  return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
3670 }
3671 
3673  TypeSpecifierType TagSpec,
3674  SourceLocation TagLoc,
3675  CXXScopeSpec &SS,
3676  SourceLocation TemplateKWLoc,
3677  TemplateTy TemplateD,
3678  SourceLocation TemplateLoc,
3679  SourceLocation LAngleLoc,
3680  ASTTemplateArgsPtr TemplateArgsIn,
3681  SourceLocation RAngleLoc) {
3682  if (SS.isInvalid())
3683  return TypeResult(true);
3684 
3685  TemplateName Template = TemplateD.get();
3686 
3687  // Translate the parser's template argument list in our AST format.
3688  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3689  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3690 
3691  // Determine the tag kind
3693  ElaboratedTypeKeyword Keyword
3695 
3696  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3697  assert(SS.getScopeRep() == DTN->getQualifier());
3699  Keyword, DTN->getQualifier(), DTN->getIdentifier(),
3700  TemplateArgs.arguments());
3701 
3702  // Build type-source information.
3703  TypeLocBuilder TLB;
3706  SpecTL.setElaboratedKeywordLoc(TagLoc);
3707  SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3708  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3709  SpecTL.setTemplateNameLoc(TemplateLoc);
3710  SpecTL.setLAngleLoc(LAngleLoc);
3711  SpecTL.setRAngleLoc(RAngleLoc);
3712  for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3713  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3714  return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3715  }
3716 
3717  if (TypeAliasTemplateDecl *TAT =
3718  dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3719  // C++0x [dcl.type.elab]p2:
3720  // If the identifier resolves to a typedef-name or the simple-template-id
3721  // resolves to an alias template specialization, the
3722  // elaborated-type-specifier is ill-formed.
3723  Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3724  << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
3725  Diag(TAT->getLocation(), diag::note_declared_at);
3726  }
3727 
3728  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3729  if (Result.isNull())
3730  return TypeResult(true);
3731 
3732  // Check the tag kind
3733  if (const RecordType *RT = Result->getAs<RecordType>()) {
3734  RecordDecl *D = RT->getDecl();
3735 
3736  IdentifierInfo *Id = D->getIdentifier();
3737  assert(Id && "templated class must have an identifier");
3738 
3739  if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TagUseKind::Definition,
3740  TagLoc, Id)) {
3741  Diag(TagLoc, diag::err_use_with_wrong_tag)
3742  << Result
3743  << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3744  Diag(D->getLocation(), diag::note_previous_use);
3745  }
3746  }
3747 
3748  // Provide source-location information for the template specialization.
3749  TypeLocBuilder TLB;
3751  = TLB.push<TemplateSpecializationTypeLoc>(Result);
3752  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3753  SpecTL.setTemplateNameLoc(TemplateLoc);
3754  SpecTL.setLAngleLoc(LAngleLoc);
3755  SpecTL.setRAngleLoc(RAngleLoc);
3756  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3757  SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3758 
3759  // Construct an elaborated type containing the nested-name-specifier (if any)
3760  // and tag keyword.
3761  Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3762  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3763  ElabTL.setElaboratedKeywordLoc(TagLoc);
3764  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3765  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3766 }
3767 
3768 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3769  NamedDecl *PrevDecl,
3772 
3774 
3776  const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3777  switch (Arg.getKind()) {
3785  return false;
3786 
3787  case TemplateArgument::Type: {
3788  QualType Type = Arg.getAsType();
3789  const TemplateTypeParmType *TPT =
3791  return TPT && !Type.hasQualifiers() &&
3792  TPT->getDepth() == Depth && TPT->getIndex() == Index;
3793  }
3794 
3796  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3797  if (!DRE || !DRE->getDecl())
3798  return false;
3799  const NonTypeTemplateParmDecl *NTTP =
3800  dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3801  return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3802  }
3803 
3805  const TemplateTemplateParmDecl *TTP =
3806  dyn_cast_or_null<TemplateTemplateParmDecl>(
3808  return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3809  }
3810  llvm_unreachable("unexpected kind of template argument");
3811 }
3812 
3815  if (Params->size() != Args.size())
3816  return false;
3817 
3818  unsigned Depth = Params->getDepth();
3819 
3820  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3821  TemplateArgument Arg = Args[I];
3822 
3823  // If the parameter is a pack expansion, the argument must be a pack
3824  // whose only element is a pack expansion.
3825  if (Params->getParam(I)->isParameterPack()) {
3826  if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3827  !Arg.pack_begin()->isPackExpansion())
3828  return false;
3829  Arg = Arg.pack_begin()->getPackExpansionPattern();
3830  }
3831 
3833  return false;
3834  }
3835 
3836  return true;
3837 }
3838 
3839 template<typename PartialSpecDecl>
3840 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3841  if (Partial->getDeclContext()->isDependentContext())
3842  return;
3843 
3844  // FIXME: Get the TDK from deduction in order to provide better diagnostics
3845  // for non-substitution-failure issues?
3846  TemplateDeductionInfo Info(Partial->getLocation());
3847  if (S.isMoreSpecializedThanPrimary(Partial, Info))
3848  return;
3849 
3850  auto *Template = Partial->getSpecializedTemplate();
3851  S.Diag(Partial->getLocation(),
3852  diag::ext_partial_spec_not_more_specialized_than_primary)
3853  << isa<VarTemplateDecl>(Template);
3854 
3855  if (Info.hasSFINAEDiagnostic()) {
3858  Info.takeSFINAEDiagnostic(Diag);
3859  SmallString<128> SFINAEArgString;
3860  Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3861  S.Diag(Diag.first,
3862  diag::note_partial_spec_not_more_specialized_than_primary)
3863  << SFINAEArgString;
3864  }
3865 
3866  S.NoteTemplateLocation(*Template);
3867  SmallVector<const Expr *, 3> PartialAC, TemplateAC;
3868  Template->getAssociatedConstraints(TemplateAC);
3869  Partial->getAssociatedConstraints(PartialAC);
3870  S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
3871  TemplateAC);
3872 }
3873 
3874 static void
3876  const llvm::SmallBitVector &DeducibleParams) {
3877  for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3878  if (!DeducibleParams[I]) {
3879  NamedDecl *Param = TemplateParams->getParam(I);
3880  if (Param->getDeclName())
3881  S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3882  << Param->getDeclName();
3883  else
3884  S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3885  << "(anonymous)";
3886  }
3887  }
3888 }
3889 
3890 
3891 template<typename PartialSpecDecl>
3893  PartialSpecDecl *Partial) {
3894  // C++1z [temp.class.spec]p8: (DR1495)
3895  // - The specialization shall be more specialized than the primary
3896  // template (14.5.5.2).
3897  checkMoreSpecializedThanPrimary(S, Partial);
3898 
3899  // C++ [temp.class.spec]p8: (DR1315)
3900  // - Each template-parameter shall appear at least once in the
3901  // template-id outside a non-deduced context.
3902  // C++1z [temp.class.spec.match]p3 (P0127R2)
3903  // If the template arguments of a partial specialization cannot be
3904  // deduced because of the structure of its template-parameter-list
3905  // and the template-id, the program is ill-formed.
3906  auto *TemplateParams = Partial->getTemplateParameters();
3907  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3908  S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3909  TemplateParams->getDepth(), DeducibleParams);
3910 
3911  if (!DeducibleParams.all()) {
3912  unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3913  S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3914  << isa<VarTemplatePartialSpecializationDecl>(Partial)
3915  << (NumNonDeducible > 1)
3916  << SourceRange(Partial->getLocation(),
3917  Partial->getTemplateArgsAsWritten()->RAngleLoc);
3918  noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3919  }
3920 }
3921 
3924  checkTemplatePartialSpecialization(*this, Partial);
3925 }
3926 
3929  checkTemplatePartialSpecialization(*this, Partial);
3930 }
3931 
3933  // C++1z [temp.param]p11:
3934  // A template parameter of a deduction guide template that does not have a
3935  // default-argument shall be deducible from the parameter-type-list of the
3936  // deduction guide template.
3937  auto *TemplateParams = TD->getTemplateParameters();
3938  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3939  MarkDeducedTemplateParameters(TD, DeducibleParams);
3940  for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3941  // A parameter pack is deducible (to an empty pack).
3942  auto *Param = TemplateParams->getParam(I);
3943  if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3944  DeducibleParams[I] = true;
3945  }
3946 
3947  if (!DeducibleParams.all()) {
3948  unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3949  Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3950  << (NumNonDeducible > 1);
3951  noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3952  }
3953 }
3954 
3957  SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
3959  // D must be variable template id.
3960  assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
3961  "Variable template specialization is declared with a template id.");
3962 
3963  TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3964  TemplateArgumentListInfo TemplateArgs =
3965  makeTemplateArgumentListInfo(*this, *TemplateId);
3966  SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3967  SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3968  SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3969 
3970  TemplateName Name = TemplateId->Template.get();
3971 
3972  // The template-id must name a variable template.
3973  VarTemplateDecl *VarTemplate =
3974  dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3975  if (!VarTemplate) {
3976  NamedDecl *FnTemplate;
3977  if (auto *OTS = Name.getAsOverloadedTemplate())
3978  FnTemplate = *OTS->begin();
3979  else
3980  FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3981  if (FnTemplate)
3982  return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3983  << FnTemplate->getDeclName();
3984  return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3986  }
3987 
3988  // Check for unexpanded parameter packs in any of the template arguments.
3989  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3990  if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3992  ? UPPC_PartialSpecialization
3993  : UPPC_ExplicitSpecialization))
3994  return true;
3995 
3996  // Check that the template argument list is well-formed for this
3997  // template.
3998  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3999  if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4000  false, SugaredConverted, CanonicalConverted,
4001  /*UpdateArgsWithConversions=*/true))
4002  return true;
4003 
4004  // Find the variable template (partial) specialization declaration that
4005  // corresponds to these arguments.
4007  if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4008  TemplateArgs.size(),
4009  CanonicalConverted))
4010  return true;
4011 
4012  // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4013  // also do them during instantiation.
4014  if (!Name.isDependent() &&
4016  TemplateArgs, CanonicalConverted)) {
4017  Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4018  << VarTemplate->getDeclName();
4019  IsPartialSpecialization = false;
4020  }
4021 
4023  CanonicalConverted) &&
4024  (!Context.getLangOpts().CPlusPlus20 ||
4025  !TemplateParams->hasAssociatedConstraints())) {
4026  // C++ [temp.class.spec]p9b3:
4027  //
4028  // -- The argument list of the specialization shall not be identical
4029  // to the implicit argument list of the primary template.
4030  Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4031  << /*variable template*/ 1
4032  << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4033  << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4034  // FIXME: Recover from this by treating the declaration as a redeclaration
4035  // of the primary template.
4036  return true;
4037  }
4038  }
4039 
4040  void *InsertPos = nullptr;
4041  VarTemplateSpecializationDecl *PrevDecl = nullptr;
4042 
4044  PrevDecl = VarTemplate->findPartialSpecialization(
4045  CanonicalConverted, TemplateParams, InsertPos);
4046  else
4047  PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4048 
4050 
4051  // Check whether we can declare a variable template specialization in
4052  // the current scope.
4053  if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4054  TemplateNameLoc,
4056  return true;
4057 
4058  if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4059  // Since the only prior variable template specialization with these
4060  // arguments was referenced but not declared, reuse that
4061  // declaration node as our own, updating its source location and
4062  // the list of outer template parameters to reflect our new declaration.
4063  Specialization = PrevDecl;
4064  Specialization->setLocation(TemplateNameLoc);
4065  PrevDecl = nullptr;
4066  } else if (IsPartialSpecialization) {
4067  // Create a new class template partial specialization declaration node.
4069  cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4072  Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4073  TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4074  CanonicalConverted);
4075  Partial->setTemplateArgsAsWritten(TemplateArgs);
4076 
4077  if (!PrevPartial)
4078  VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4079  Specialization = Partial;
4080 
4081  // If we are providing an explicit specialization of a member variable
4082  // template specialization, make a note of that.
4083  if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4084  PrevPartial->setMemberSpecialization();
4085 
4086  CheckTemplatePartialSpecialization(Partial);
4087  } else {
4088  // Create a new class template specialization declaration node for
4089  // this explicit specialization or friend declaration.
4091  Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4092  VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4093  Specialization->setTemplateArgsAsWritten(TemplateArgs);
4094 
4095  if (!PrevDecl)
4096  VarTemplate->AddSpecialization(Specialization, InsertPos);
4097  }
4098 
4099  // C++ [temp.expl.spec]p6:
4100  // If a template, a member template or the member of a class template is
4101  // explicitly specialized then that specialization shall be declared
4102  // before the first use of that specialization that would cause an implicit
4103  // instantiation to take place, in every translation unit in which such a
4104  // use occurs; no diagnostic is required.
4105  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4106  bool Okay = false;
4107  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4108  // Is there any previous explicit specialization declaration?
4110  Okay = true;
4111  break;
4112  }
4113  }
4114 
4115  if (!Okay) {
4116  SourceRange Range(TemplateNameLoc, RAngleLoc);
4117  Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4118  << Name << Range;
4119 
4120  Diag(PrevDecl->getPointOfInstantiation(),
4121  diag::note_instantiation_required_here)
4122  << (PrevDecl->getTemplateSpecializationKind() !=
4124  return true;
4125  }
4126  }
4127 
4128  Specialization->setLexicalDeclContext(CurContext);
4129 
4130  // Add the specialization into its lexical context, so that it can
4131  // be seen when iterating through the list of declarations in that
4132  // context. However, specializations are not found by name lookup.
4133  CurContext->addDecl(Specialization);
4134 
4135  // Note that this is an explicit specialization.
4136  Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4137 
4138  Previous.clear();
4139  if (PrevDecl)
4140  Previous.addDecl(PrevDecl);
4141  else if (Specialization->isStaticDataMember() &&
4142  Specialization->isOutOfLine())
4143  Specialization->setAccess(VarTemplate->getAccess());
4144 
4145  return Specialization;
4146 }
4147 
4148 namespace {
4149 /// A partial specialization whose template arguments have matched
4150 /// a given template-id.
4151 struct PartialSpecMatchResult {
4153  TemplateArgumentList *Args;
4154 };
4155 } // end anonymous namespace
4156 
4157 DeclResult
4159  SourceLocation TemplateNameLoc,
4160  const TemplateArgumentListInfo &TemplateArgs) {
4161  assert(Template && "A variable template id without template?");
4162 
4163  // Check that the template argument list is well-formed for this template.
4164  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4165  if (CheckTemplateArgumentList(
4166  Template, TemplateNameLoc,
4167  const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4168  SugaredConverted, CanonicalConverted,
4169  /*UpdateArgsWithConversions=*/true))
4170  return true;
4171 
4172  // Produce a placeholder value if the specialization is dependent.
4173  if (Template->getDeclContext()->isDependentContext() ||
4175  TemplateArgs, CanonicalConverted))
4176  return DeclResult();
4177 
4178  // Find the variable template specialization declaration that
4179  // corresponds to these arguments.
4180  void *InsertPos = nullptr;
4181  if (VarTemplateSpecializationDecl *Spec =
4182  Template->findSpecialization(CanonicalConverted, InsertPos)) {
4183  checkSpecializationReachability(TemplateNameLoc, Spec);
4184  // If we already have a variable template specialization, return it.
4185  return Spec;
4186  }
4187 
4188  // This is the first time we have referenced this variable template
4189  // specialization. Create the canonical declaration and add it to
4190  // the set of specializations, based on the closest partial specialization
4191  // that it represents. That is,
4192  VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4193  const TemplateArgumentList *PartialSpecArgs = nullptr;
4194  bool AmbiguousPartialSpec = false;
4195  typedef PartialSpecMatchResult MatchResult;
4197  SourceLocation PointOfInstantiation = TemplateNameLoc;
4198  TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4199  /*ForTakingAddress=*/false);
4200 
4201  // 1. Attempt to find the closest partial specialization that this
4202  // specializes, if any.
4203  // TODO: Unify with InstantiateClassTemplateSpecialization()?
4204  // Perhaps better after unification of DeduceTemplateArguments() and
4205  // getMoreSpecializedPartialSpecialization().
4207  Template->getPartialSpecializations(PartialSpecs);
4208 
4209  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4210  VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4211  TemplateDeductionInfo Info(FailedCandidates.getLocation());
4212 
4213  if (TemplateDeductionResult Result =
4214  DeduceTemplateArguments(Partial, SugaredConverted, Info);
4216  // Store the failed-deduction information for use in diagnostics, later.
4217  // TODO: Actually use the failed-deduction info?
4218  FailedCandidates.addCandidate().set(
4219  DeclAccessPair::make(Template, AS_public), Partial,
4220  MakeDeductionFailureInfo(Context, Result, Info));
4221  (void)Result;
4222  } else {
4223  Matched.push_back(PartialSpecMatchResult());
4224  Matched.back().Partial = Partial;
4225  Matched.back().Args = Info.takeSugared();
4226  }
4227  }
4228 
4229  if (Matched.size() >= 1) {
4230  SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4231  if (Matched.size() == 1) {
4232  // -- If exactly one matching specialization is found, the
4233  // instantiation is generated from that specialization.
4234  // We don't need to do anything for this.
4235  } else {
4236  // -- If more than one matching specialization is found, the
4237  // partial order rules (14.5.4.2) are used to determine
4238  // whether one of the specializations is more specialized
4239  // than the others. If none of the specializations is more
4240  // specialized than all of the other matching
4241  // specializations, then the use of the variable template is
4242  // ambiguous and the program is ill-formed.
4243  for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4244  PEnd = Matched.end();
4245  P != PEnd; ++P) {
4246  if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4247  PointOfInstantiation) ==
4248  P->Partial)
4249  Best = P;
4250  }
4251 
4252  // Determine if the best partial specialization is more specialized than
4253  // the others.
4254  for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4255  PEnd = Matched.end();
4256  P != PEnd; ++P) {
4257  if (P != Best && getMoreSpecializedPartialSpecialization(
4258  P->Partial, Best->Partial,
4259  PointOfInstantiation) != Best->Partial) {
4260  AmbiguousPartialSpec = true;
4261  break;
4262  }
4263  }
4264  }
4265 
4266  // Instantiate using the best variable template partial specialization.
4267  InstantiationPattern = Best->Partial;
4268  PartialSpecArgs = Best->Args;
4269  } else {
4270  // -- If no match is found, the instantiation is generated
4271  // from the primary template.
4272  // InstantiationPattern = Template->getTemplatedDecl();
4273  }
4274 
4275  // 2. Create the canonical declaration.
4276  // Note that we do not instantiate a definition until we see an odr-use
4277  // in DoMarkVarDeclReferenced().
4278  // FIXME: LateAttrs et al.?
4279  VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4280  Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
4281  CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4282  if (!Decl)
4283  return true;
4284 
4285  if (AmbiguousPartialSpec) {
4286  // Partial ordering did not produce a clear winner. Complain.
4287  Decl->setInvalidDecl();
4288  Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4289  << Decl;
4290 
4291  // Print the matching partial specializations.
4292  for (MatchResult P : Matched)
4293  Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4294  << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4295  *P.Args);
4296  return true;
4297  }
4298 
4300  dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4301  Decl->setInstantiationOf(D, PartialSpecArgs);
4302 
4303  checkSpecializationReachability(TemplateNameLoc, Decl);
4304 
4305  assert(Decl && "No variable template specialization?");
4306  return Decl;
4307 }
4308 
4310  const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4311  VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4312  const TemplateArgumentListInfo *TemplateArgs) {
4313 
4314  DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4315  *TemplateArgs);
4316  if (Decl.isInvalid())
4317  return ExprError();
4318 
4319  if (!Decl.get())
4320  return ExprResult();
4321 
4322  VarDecl *Var = cast<VarDecl>(Decl.get());
4323  if (!Var->getTemplateSpecializationKind())
4325  NameInfo.getLoc());
4326 
4327  // Build an ordinary singleton decl ref.
4328  return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4329 }
4330 
4332  SourceLocation Loc) {
4333  Diag(Loc, diag::err_template_missing_args)
4334  << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4335  if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4336  NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4337  }
4338 }
4339 
4341  bool TemplateKeyword,
4342  TemplateDecl *TD,
4343  SourceLocation Loc) {
4344  TemplateName Name = Context.getQualifiedTemplateName(
4345  SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4346  diagnoseMissingTemplateArguments(Name, Loc);
4347 }
4348 
4349 ExprResult
4351  SourceLocation TemplateKWLoc,
4352  const DeclarationNameInfo &ConceptNameInfo,
4353  NamedDecl *FoundDecl,
4354  ConceptDecl *NamedConcept,
4355  const TemplateArgumentListInfo *TemplateArgs) {
4356  assert(NamedConcept && "A concept template id without a template?");
4357 
4358  llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4359  if (CheckTemplateArgumentList(
4360  NamedConcept, ConceptNameInfo.getLoc(),
4361  const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4362  /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
4363  /*UpdateArgsWithConversions=*/false))
4364  return ExprError();
4365 
4366  DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4367 
4369  Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4370  CanonicalConverted);
4371  ConstraintSatisfaction Satisfaction;
4372  bool AreArgsDependent =
4374  *TemplateArgs, CanonicalConverted);
4375  MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
4376  /*Final=*/false);
4378 
4380  *this, ExpressionEvaluationContext::Unevaluated, CSD};
4381 
4382  if (!AreArgsDependent &&
4384  NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
4385  SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4386  TemplateArgs->getRAngleLoc()),
4387  Satisfaction))
4388  return ExprError();
4389  auto *CL = ConceptReference::Create(
4390  Context,
4391  SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4392  TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4393  ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs));
4395  Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4396 }
4397 
4399  SourceLocation TemplateKWLoc,
4400  LookupResult &R,
4401  bool RequiresADL,
4402  const TemplateArgumentListInfo *TemplateArgs) {
4403  // FIXME: Can we do any checking at this point? I guess we could check the
4404  // template arguments that we have against the template name, if the template
4405  // name refers to a single template. That's not a terribly common case,
4406  // though.
4407  // foo<int> could identify a single function unambiguously
4408  // This approach does NOT work, since f<int>(1);
4409  // gets resolved prior to resorting to overload resolution
4410  // i.e., template<class T> void f(double);
4411  // vs template<class T, class U> void f(U);
4412 
4413  // These should be filtered out by our callers.
4414  assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4415 
4416  // Non-function templates require a template argument list.
4417  if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4418  if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4419  diagnoseMissingTemplateArguments(
4420  SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4421  return ExprError();
4422  }
4423  }
4424  bool KnownDependent = false;
4425  // In C++1y, check variable template ids.
4426  if (R.getAsSingle<VarTemplateDecl>()) {
4427  ExprResult Res = CheckVarTemplateId(
4429  R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4430  if (Res.isInvalid() || Res.isUsable())
4431  return Res;
4432  // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4433  KnownDependent = true;
4434  }
4435 
4436  if (R.getAsSingle<ConceptDecl>()) {
4437  return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4439  R.getAsSingle<ConceptDecl>(), TemplateArgs);
4440  }
4441 
4442  // We don't want lookup warnings at this point.
4443  R.suppressDiagnostics();
4444 
4446  Context, R.getNamingClass(), SS.getWithLocInContext(Context),
4447  TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4448  R.begin(), R.end(), KnownDependent,
4449  /*KnownInstantiationDependent=*/false);
4450 
4451  // Model the templates with UnresolvedTemplateTy. The expression should then
4452  // either be transformed in an instantiation or be diagnosed in
4453  // CheckPlaceholderExpr.
4454  if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4455  !R.getFoundDecl()->getAsFunction())
4456  ULE->setType(Context.UnresolvedTemplateTy);
4457 
4458  return ULE;
4459 }
4460 
4462  CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4463  const DeclarationNameInfo &NameInfo,
4464  const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4465  assert(TemplateArgs || TemplateKWLoc.isValid());
4466 
4467  LookupResult R(*this, NameInfo, LookupOrdinaryName);
4468  if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4469  /*EnteringContext=*/false, TemplateKWLoc))
4470  return ExprError();
4471 
4472  if (R.isAmbiguous())
4473  return ExprError();
4474 
4476  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4477 
4478  if (R.empty()) {
4479  DeclContext *DC = computeDeclContext(SS);
4480  Diag(NameInfo.getLoc(), diag::err_no_member)
4481  << NameInfo.getName() << DC << SS.getRange();
4482  return ExprError();
4483  }
4484 
4485  // If necessary, build an implicit class member access.
4486  if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
4487  return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
4488  /*S=*/nullptr);
4489 
4490  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
4491 }
4492 
4494  CXXScopeSpec &SS,
4495  SourceLocation TemplateKWLoc,
4496  const UnqualifiedId &Name,
4497  ParsedType ObjectType,
4498  bool EnteringContext,
4499  TemplateTy &Result,
4500  bool AllowInjectedClassName) {
4501  if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4502  Diag(TemplateKWLoc,
4503  getLangOpts().CPlusPlus11 ?
4504  diag::warn_cxx98_compat_template_outside_of_template :
4505  diag::ext_template_outside_of_template)
4506  << FixItHint::CreateRemoval(TemplateKWLoc);
4507 
4508  if (SS.isInvalid())
4509  return TNK_Non_template;
4510 
4511  // Figure out where isTemplateName is going to look.
4512  DeclContext *LookupCtx = nullptr;
4513  if (SS.isNotEmpty())
4514  LookupCtx = computeDeclContext(SS, EnteringContext);
4515  else if (ObjectType)
4516  LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
4517 
4518  // C++0x [temp.names]p5:
4519  // If a name prefixed by the keyword template is not the name of
4520  // a template, the program is ill-formed. [Note: the keyword
4521  // template may not be applied to non-template members of class
4522  // templates. -end note ] [ Note: as is the case with the
4523  // typename prefix, the template prefix is allowed in cases
4524  // where it is not strictly necessary; i.e., when the
4525  // nested-name-specifier or the expression on the left of the ->
4526  // or . is not dependent on a template-parameter, or the use
4527  // does not appear in the scope of a template. -end note]
4528  //
4529  // Note: C++03 was more strict here, because it banned the use of
4530  // the "template" keyword prior to a template-name that was not a
4531  // dependent name. C++ DR468 relaxed this requirement (the
4532  // "template" keyword is now permitted). We follow the C++0x
4533  // rules, even in C++03 mode with a warning, retroactively applying the DR.
4534  bool MemberOfUnknownSpecialization;
4535  TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4536  ObjectType, EnteringContext, Result,
4537  MemberOfUnknownSpecialization);
4538  if (TNK != TNK_Non_template) {
4539  // We resolved this to a (non-dependent) template name. Return it.
4540  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4541  if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
4542  Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4543  Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4544  // C++14 [class.qual]p2:
4545  // In a lookup in which function names are not ignored and the
4546  // nested-name-specifier nominates a class C, if the name specified
4547  // [...] is the injected-class-name of C, [...] the name is instead
4548  // considered to name the constructor
4549  //
4550  // We don't get here if naming the constructor would be valid, so we
4551  // just reject immediately and recover by treating the
4552  // injected-class-name as naming the template.
4553  Diag(Name.getBeginLoc(),
4554  diag::ext_out_of_line_qualified_id_type_names_constructor)
4555  << Name.Identifier
4556  << 0 /*injected-class-name used as template name*/
4557  << TemplateKWLoc.isValid();
4558  }
4559  return TNK;
4560  }
4561 
4562  if (!MemberOfUnknownSpecialization) {
4563  // Didn't find a template name, and the lookup wasn't dependent.
4564  // Do the lookup again to determine if this is a "nothing found" case or
4565  // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4566  // need to do this.
4567  DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4568  LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4569  LookupOrdinaryName);
4570  // Tell LookupTemplateName that we require a template so that it diagnoses
4571  // cases where it finds a non-template.
4572  RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4573  ? RequiredTemplateKind(TemplateKWLoc)
4574  : TemplateNameIsRequired;
4575  if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
4576  /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
4577  !R.isAmbiguous()) {
4578  if (LookupCtx)
4579  Diag(Name.getBeginLoc(), diag::err_no_member)
4580  << DNI.getName() << LookupCtx << SS.getRange();
4581  else
4582  Diag(Name.getBeginLoc(), diag::err_undeclared_use)
4583  << DNI.getName() << SS.getRange();
4584  }
4585  return TNK_Non_template;
4586  }
4587 
4588  NestedNameSpecifier *Qualifier = SS.getScopeRep();
4589 
4590  switch (Name.getKind()) {
4592  Result = TemplateTy::make(
4593  Context.getDependentTemplateName(Qualifier, Name.Identifier));
4595 
4597  Result = TemplateTy::make(Context.getDependentTemplateName(
4598  Qualifier, Name.OperatorFunctionId.Operator));
4599  return TNK_Function_template;
4600 
4602  // This is a kind of template name, but can never occur in a dependent
4603  // scope (literal operators can only be declared at namespace scope).
4604  break;
4605 
4606  default:
4607  break;
4608  }
4609 
4610  // This name cannot possibly name a dependent template. Diagnose this now
4611  // rather than building a dependent template name that can never be valid.
4612  Diag(Name.getBeginLoc(),
4613  diag::err_template_kw_refers_to_dependent_non_template)
4614  << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4615  << TemplateKWLoc.isValid() << TemplateKWLoc;
4616  return TNK_Non_template;
4617 }
4618 
4621  SmallVectorImpl<TemplateArgument> &SugaredConverted,
4622  SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
4623  const TemplateArgument &Arg = AL.getArgument();
4624  QualType ArgType;
4625  TypeSourceInfo *TSI = nullptr;
4626 
4627  // Check template type parameter.
4628  switch(Arg.getKind()) {
4630  // C++ [temp.arg.type]p1:
4631  // A template-argument for a template-parameter which is a
4632  // type shall be a type-id.
4633  ArgType = Arg.getAsType();
4634  TSI = AL.getTypeSourceInfo();
4635  break;
4638  // We have a template type parameter but the template argument
4639  // is a template without any arguments.
4640  SourceRange SR = AL.getSourceRange();
4642  diagnoseMissingTemplateArguments(Name, SR.getEnd());
4643  return true;
4644  }
4646  // We have a template type parameter but the template argument is an
4647  // expression; see if maybe it is missing the "typename" keyword.
4648  CXXScopeSpec SS;
4649  DeclarationNameInfo NameInfo;
4650 
4651  if (DependentScopeDeclRefExpr *ArgExpr =
4652  dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4653  SS.Adopt(ArgExpr->getQualifierLoc());
4654  NameInfo = ArgExpr->getNameInfo();
4655  } else if (CXXDependentScopeMemberExpr *ArgExpr =
4656  dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4657  if (ArgExpr->isImplicitAccess()) {
4658  SS.Adopt(ArgExpr->getQualifierLoc());
4659  NameInfo = ArgExpr->getMemberNameInfo();
4660  }
4661  }
4662 
4663  if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4664  LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4665  LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
4666 
4667  if (Result.getAsSingle<TypeDecl>() ||
4668  Result.wasNotFoundInCurrentInstantiation()) {
4669  assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
4670  // Suggest that the user add 'typename' before the NNS.
4672  Diag(Loc, getLangOpts().MSVCCompat
4673  ? diag::ext_ms_template_type_arg_missing_typename
4674  : diag::err_template_arg_must_be_type_suggest)
4675  << FixItHint::CreateInsertion(Loc, "typename ");
4676  NoteTemplateParameterLocation(*Param);
4677 
4678  // Recover by synthesizing a type using the location information that we
4679  // already have.
4681  SS.getScopeRep(), II);
4682  TypeLocBuilder TLB;
4683  DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4684  TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4685  TL.setQualifierLoc(SS.getWithLocInContext(Context));
4686  TL.setNameLoc(NameInfo.getLoc());
4687  TSI = TLB.getTypeSourceInfo(Context, ArgType);
4688 
4689  // Overwrite our input TemplateArgumentLoc so that we can recover
4690  // properly.
4691  AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4693 
4694  break;
4695  }
4696  }
4697  // fallthrough
4698  [[fallthrough]];
4699  }
4700  default: {
4701  // We allow instantiateing a template with template argument packs when
4702  // building deduction guides.
4703  if (Arg.getKind() == TemplateArgument::Pack &&
4704  CodeSynthesisContexts.back().Kind ==
4706  SugaredConverted.push_back(Arg);
4707  CanonicalConverted.push_back(Arg);
4708  return false;
4709  }
4710  // We have a template type parameter but the template argument
4711  // is not a type.
4712  SourceRange SR = AL.getSourceRange();
4713  Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4714  NoteTemplateParameterLocation(*Param);
4715 
4716  return true;
4717  }
4718  }
4719 
4720  if (CheckTemplateArgument(TSI))
4721  return true;
4722 
4723  // Objective-C ARC:
4724  // If an explicitly-specified template argument type is a lifetime type
4725  // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4726  if (getLangOpts().ObjCAutoRefCount &&
4727  ArgType->isObjCLifetimeType() &&
4728  !ArgType.getObjCLifetime()) {
4729  Qualifiers Qs;
4731  ArgType = Context.getQualifiedType(ArgType, Qs);
4732  }
4733 
4734  SugaredConverted.push_back(TemplateArgument(ArgType));
4735  CanonicalConverted.push_back(
4736  TemplateArgument(Context.getCanonicalType(ArgType)));
4737  return false;
4738 }
4739 
4740 /// Substitute template arguments into the default template argument for
4741 /// the given template type parameter.
4742 ///
4743 /// \param SemaRef the semantic analysis object for which we are performing
4744 /// the substitution.
4745 ///
4746 /// \param Template the template that we are synthesizing template arguments
4747 /// for.
4748 ///
4749 /// \param TemplateLoc the location of the template name that started the
4750 /// template-id we are checking.
4751 ///
4752 /// \param RAngleLoc the location of the right angle bracket ('>') that
4753 /// terminates the template-id.
4754 ///
4755 /// \param Param the template template parameter whose default we are
4756 /// substituting into.
4757 ///
4758 /// \param Converted the list of template arguments provided for template
4759 /// parameters that precede \p Param in the template parameter list.
4760 ///
4761 /// \param Output the resulting substituted template argument.
4762 ///
4763 /// \returns true if an error occurred.
4765  Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4766  SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
4767  ArrayRef<TemplateArgument> SugaredConverted,
4768  ArrayRef<TemplateArgument> CanonicalConverted,
4769  TemplateArgumentLoc &Output) {
4770  Output = Param->getDefaultArgument();
4771 
4772  // If the argument type is dependent, instantiate it now based
4773  // on the previously-computed template arguments.
4774  if (Output.getArgument().isInstantiationDependent()) {
4775  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
4776  SugaredConverted,
4777  SourceRange(TemplateLoc, RAngleLoc));
4778  if (Inst.isInvalid())
4779  return true;
4780 
4781  // Only substitute for the innermost template argument list.
4782  MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4783  /*Final=*/true);
4784  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4785  TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4786 
4787  bool ForLambdaCallOperator = false;
4788  if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
4789  ForLambdaCallOperator = Rec->isLambda();
4790  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
4791  !ForLambdaCallOperator);
4792 
4793  if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
4794  Param->getDefaultArgumentLoc(),
4795  Param->getDeclName()))
4796  return true;
4797  }
4798 
4799  return false;
4800 }
4801 
4802 /// Substitute template arguments into the default template argument for
4803 /// the given non-type template parameter.
4804 ///
4805 /// \param SemaRef the semantic analysis object for which we are performing
4806 /// the substitution.
4807 ///
4808 /// \param Template the template that we are synthesizing template arguments
4809 /// for.
4810 ///
4811 /// \param TemplateLoc the location of the template name that started the
4812 /// template-id we are checking.
4813 ///
4814 /// \param RAngleLoc the location of the right angle bracket ('>') that
4815 /// terminates the template-id.
4816 ///
4817 /// \param Param the non-type template parameter whose default we are
4818 /// substituting into.
4819 ///
4820 /// \param Converted the list of template arguments provided for template
4821 /// parameters that precede \p Param in the template parameter list.
4822 ///
4823 /// \returns the substituted template argument, or NULL if an error occurred.
4825  Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4826  SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
4827  ArrayRef<TemplateArgument> SugaredConverted,
4828  ArrayRef<TemplateArgument> CanonicalConverted,
4829  TemplateArgumentLoc &Output) {
4830  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
4831  SugaredConverted,
4832  SourceRange(TemplateLoc, RAngleLoc));
4833  if (Inst.isInvalid())
4834  return true;
4835 
4836  // Only substitute for the innermost template argument list.
4837  MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4838  /*Final=*/true);
4839  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4840  TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4841 
4842  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4843  EnterExpressionEvaluationContext ConstantEvaluated(
4845  return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
4846  TemplateArgLists, Output);
4847 }
4848 
4849 /// Substitute template arguments into the default template argument for
4850 /// the given template template parameter.
4851 ///
4852 /// \param SemaRef the semantic analysis object for which we are performing
4853 /// the substitution.
4854 ///
4855 /// \param Template the template that we are synthesizing template arguments
4856 /// for.
4857 ///
4858 /// \param TemplateLoc the location of the template name that started the
4859 /// template-id we are checking.
4860 ///
4861 /// \param RAngleLoc the location of the right angle bracket ('>') that
4862 /// terminates the template-id.
4863 ///
4864 /// \param Param the template template parameter whose default we are
4865 /// substituting into.
4866 ///
4867 /// \param Converted the list of template arguments provided for template
4868 /// parameters that precede \p Param in the template parameter list.
4869 ///
4870 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4871 /// source-location information) that precedes the template name.
4872 ///
4873 /// \returns the substituted template argument, or NULL if an error occurred.
4875  Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4876  SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
4877  ArrayRef<TemplateArgument> SugaredConverted,
4878  ArrayRef<TemplateArgument> CanonicalConverted,
4879  NestedNameSpecifierLoc &QualifierLoc) {
4881  SemaRef, TemplateLoc, TemplateParameter(Param), Template,
4882  SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
4883  if (Inst.isInvalid())
4884  return TemplateName();
4885 
4886  // Only substitute for the innermost template argument list.
4887  MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4888  /*Final=*/true);
4889  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4890  TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4891 
4892  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4893  // Substitute into the nested-name-specifier first,
4894  QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4895  if (QualifierLoc) {
4896  QualifierLoc =
4897  SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4898  if (!QualifierLoc)
4899  return TemplateName();
4900  }
4901 
4902  return SemaRef.SubstTemplateName(
4903  QualifierLoc,
4906  TemplateArgLists);
4907 }
4908 
4910  TemplateDecl *Template, SourceLocation TemplateLoc,
4911  SourceLocation RAngleLoc, Decl *Param,
4912  ArrayRef<TemplateArgument> SugaredConverted,
4913  ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
4914  HasDefaultArg = false;
4915 
4916  if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4917  if (!hasReachableDefaultArgument(TypeParm))
4918  return TemplateArgumentLoc();
4919 
4920  HasDefaultArg = true;
4921  TemplateArgumentLoc Output;
4922  if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
4923  TypeParm, SugaredConverted,
4924  CanonicalConverted, Output))
4925  return TemplateArgumentLoc();
4926  return Output;
4927  }
4928 
4929  if (NonTypeTemplateParmDecl *NonTypeParm
4930  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4931  if (!hasReachableDefaultArgument(NonTypeParm))
4932  return TemplateArgumentLoc();
4933 
4934  HasDefaultArg = true;
4935  TemplateArgumentLoc Output;
4936  if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
4937  NonTypeParm, SugaredConverted,
4938  CanonicalConverted, Output))
4939  return TemplateArgumentLoc();
4940  return Output;
4941  }
4942 
4943  TemplateTemplateParmDecl *TempTempParm
4944  = cast<TemplateTemplateParmDecl>(Param);
4945  if (!hasReachableDefaultArgument(TempTempParm))
4946  return TemplateArgumentLoc();
4947 
4948  HasDefaultArg = true;
4949  NestedNameSpecifierLoc QualifierLoc;
4951  *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
4952  CanonicalConverted, QualifierLoc);
4953  if (TName.isNull())
4954  return TemplateArgumentLoc();
4955 
4956  return TemplateArgumentLoc(
4957  Context, TemplateArgument(TName),
4958  TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4959  TempTempParm->getDefaultArgument().getTemplateNameLoc());
4960 }
4961 
4962 /// Convert a template-argument that we parsed as a type into a template, if
4963 /// possible. C++ permits injected-class-names to perform dual service as
4964 /// template template arguments and as template type arguments.
4965 static TemplateArgumentLoc
4967  // Extract and step over any surrounding nested-name-specifier.
4968  NestedNameSpecifierLoc QualLoc;
4969  if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4970  if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
4971  return TemplateArgumentLoc();
4972 
4973  QualLoc = ETLoc.getQualifierLoc();
4974  TLoc = ETLoc.getNamedTypeLoc();
4975  }
4976  // If this type was written as an injected-class-name, it can be used as a
4977  // template template argument.
4978  if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4979  return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
4980  QualLoc, InjLoc.getNameLoc());
4981 
4982  // If this type was written as an injected-class-name, it may have been
4983  // converted to a RecordType during instantiation. If the RecordType is
4984  // *not* wrapped in a TemplateSpecializationType and denotes a class
4985  // template specialization, it must have come from an injected-class-name.
4986  if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4987  if (auto *CTSD =
4988  dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4989  return TemplateArgumentLoc(Context,
4990  TemplateName(CTSD->getSpecializedTemplate()),
4991  QualLoc, RecLoc.getNameLoc());
4992 
4993  return TemplateArgumentLoc();
4994 }
4995 
4997  NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
4998  SourceLocation TemplateLoc, SourceLocation RAngleLoc,
4999  unsigned ArgumentPackIndex,
5000  SmallVectorImpl<TemplateArgument> &SugaredConverted,
5001  SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5003  // Check template type parameters.
5004  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5005  return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
5006  CanonicalConverted);
5007 
5008  // Check non-type template parameters.
5009  if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5010  // Do substitution on the type of the non-type template parameter
5011  // with the template arguments we've seen thus far. But if the
5012  // template has a dependent context then we cannot substitute yet.
5013  QualType NTTPType = NTTP->getType();
5014  if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5015  NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5016 
5017  if (NTTPType->isInstantiationDependentType() &&
5018  !isa<TemplateTemplateParmDecl>(Template) &&
5019  !Template->getDeclContext()->isDependentContext()) {
5020  // Do substitution on the type of the non-type template parameter.
5021  InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5022  SugaredConverted,
5023  SourceRange(TemplateLoc, RAngleLoc));
5024  if (Inst.isInvalid())
5025  return true;
5026 
5027  MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
5028  /*Final=*/true);
5029  // If the parameter is a pack expansion, expand this slice of the pack.
5030  if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5031  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
5032  ArgumentPackIndex);
5033  NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5034  NTTP->getDeclName());
5035  } else {
5036  NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5037  NTTP->getDeclName());
5038  }
5039 
5040  // If that worked, check the non-type template parameter type
5041  // for validity.
5042  if (!NTTPType.isNull())
5043  NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5044  NTTP->getLocation());
5045  if (NTTPType.isNull())
5046  return true;
5047  }
5048 
5049  switch (Arg.getArgument().getKind()) {
5051  llvm_unreachable("Should never see a NULL template argument here");
5052 
5054  Expr *E = Arg.getArgument().getAsExpr();
5055  TemplateArgument SugaredResult, CanonicalResult;
5056  unsigned CurSFINAEErrors = NumSFINAEErrors;
5057  ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
5058  CanonicalResult, CTAK);
5059  if (Res.isInvalid())
5060  return true;
5061  // If the current template argument causes an error, give up now.
5062  if (CurSFINAEErrors < NumSFINAEErrors)
5063  return true;
5064 
5065  // If the resulting expression is new, then use it in place of the
5066  // old expression in the template argument.
5067  if (Res.get() != E) {
5068  TemplateArgument TA(Res.get());
5069  Arg = TemplateArgumentLoc(TA, Res.get());
5070  }
5071 
5072  SugaredConverted.push_back(SugaredResult);
5073  CanonicalConverted.push_back(CanonicalResult);
5074  break;
5075  }
5076 
5081  // We've already checked this template argument, so just copy
5082  // it to the list of converted arguments.
5083  SugaredConverted.push_back(Arg.getArgument());
5084  CanonicalConverted.push_back(
5085  Context.getCanonicalTemplateArgument(Arg.getArgument()));
5086  break;
5087 
5090  // We were given a template template argument. It may not be ill-formed;
5091  // see below.
5092  if (DependentTemplateName *DTN
5095  // We have a template argument such as \c T::template X, which we
5096  // parsed as a template template argument. However, since we now
5097  // know that we need a non-type template argument, convert this
5098  // template name into an expression.
5099 
5100  DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5101  Arg.getTemplateNameLoc());
5102 
5103  CXXScopeSpec SS;
5104  SS.Adopt(Arg.getTemplateQualifierLoc());
5105  // FIXME: the template-template arg was a DependentTemplateName,
5106  // so it was provided with a template keyword. However, its source
5107  // location is not stored in the template argument structure.
5108  SourceLocation TemplateKWLoc;
5110  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5111  nullptr);
5112 
5113  // If we parsed the template argument as a pack expansion, create a
5114  // pack expansion expression.
5116  E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5117  if (E.isInvalid())
5118  return true;
5119  }
5120 
5121  TemplateArgument SugaredResult, CanonicalResult;
5122  E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
5123  CanonicalResult, CTAK_Specified);
5124  if (E.isInvalid())
5125  return true;
5126 
5127  SugaredConverted.push_back(SugaredResult);
5128  CanonicalConverted.push_back(CanonicalResult);
5129  break;
5130  }
5131 
5132  // We have a template argument that actually does refer to a class
5133  // template, alias template, or template template parameter, and
5134  // therefore cannot be a non-type template argument.
5135  Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5136  << Arg.getSourceRange();
5137  NoteTemplateParameterLocation(*Param);
5138 
5139  return true;
5140 
5141  case TemplateArgument::Type: {
5142  // We have a non-type template parameter but the template
5143  // argument is a type.
5144 
5145  // C++ [temp.arg]p2:
5146  // In a template-argument, an ambiguity between a type-id and
5147  // an expression is resolved to a type-id, regardless of the
5148  // form of the corresponding template-parameter.
5149  //
5150  // We warn specifically about this case, since it can be rather
5151  // confusing for users.
5152  QualType T = Arg.getArgument().getAsType();
5153  SourceRange SR = Arg.getSourceRange();
5154  if (T->isFunctionType())
5155  Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5156  else
5157  Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5158  NoteTemplateParameterLocation(*Param);
5159  return true;
5160  }
5161 
5163  llvm_unreachable("Caller must expand template argument packs");
5164  }
5165 
5166  return false;
5167  }
5168 
5169 
5170  // Check template template parameters.
5171  TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5172 
5173  TemplateParameterList *Params = TempParm->getTemplateParameters();
5174  if (TempParm->isExpandedParameterPack())
5175  Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5176 
5177  // Substitute into the template parameter list of the template
5178  // template parameter, since previously-supplied template arguments
5179  // may appear within the template template parameter.
5180  //
5181  // FIXME: Skip this if the parameters aren't instantiation-dependent.
5182  {
5183  // Set up a template instantiation context.
5185  InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5186  SugaredConverted,
5187  SourceRange(TemplateLoc, RAngleLoc));
5188  if (Inst.isInvalid())
5189  return true;
5190 
5191  Params =
5192  SubstTemplateParams(Params, CurContext,
5194  Template, SugaredConverted, /*Final=*/true),
5195  /*EvaluateConstraints=*/false);
5196  if (!Params)
5197  return true;
5198  }
5199 
5200  // C++1z [temp.local]p1: (DR1004)
5201  // When [the injected-class-name] is used [...] as a template-argument for
5202  // a template template-parameter [...] it refers to the class template
5203  // itself.
5204  if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5206  Context, Arg.getTypeSourceInfo()->getTypeLoc());
5207  if (!ConvertedArg.getArgument().isNull())
5208  Arg = ConvertedArg;
5209  }
5210 
5211  switch (Arg.getArgument().getKind()) {
5213  llvm_unreachable("Should never see a NULL template argument here");
5214 
5217  if (CheckTemplateTemplateArgument(TempParm, Params, Arg,
5218  /*IsDeduced=*/CTAK != CTAK_Specified))
5219  return true;
5220 
5221  SugaredConverted.push_back(Arg.getArgument());
5222  CanonicalConverted.push_back(
5223  Context.getCanonicalTemplateArgument(Arg.getArgument()));
5224  break;
5225 
5228  // We have a template template parameter but the template
5229  // argument does not refer to a template.
5230  Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5231  << getLangOpts().CPlusPlus11;
5232  return true;
5233 
5238  llvm_unreachable("non-type argument with template template parameter");
5239 
5241  llvm_unreachable("Caller must expand template argument packs");
5242  }
5243 
5244  return false;
5245 }
5246 
5247 /// Diagnose a missing template argument.
5248 template<typename TemplateParmDecl>
5250  TemplateDecl *TD,
5251  const TemplateParmDecl *D,
5252  TemplateArgumentListInfo &Args) {
5253  // Dig out the most recent declaration of the template parameter; there may be
5254  // declarations of the template that are more recent than TD.
5255  D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5256  ->getTemplateParameters()
5257  ->getParam(D->getIndex()));
5258 
5259  // If there's a default argument that's not reachable, diagnose that we're
5260  // missing a module import.
5262  if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5263  S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5264  D->getDefaultArgumentLoc(), Modules,
5266  /*Recover*/true);
5267  return true;
5268  }
5269 
5270  // FIXME: If there's a more recent default argument that *is* visible,
5271  // diagnose that it was declared too late.
5272 
5274 
5275  S.Diag(Loc, diag::err_template_arg_list_different_arity)
5276  << /*not enough args*/0
5278  << TD;
5279  S.NoteTemplateLocation(*TD, Params->getSourceRange());
5280  return true;
5281 }
5282 
5283 /// Check that the given template argument list is well-formed
5284 /// for specializing the given template.
5286  TemplateDecl *Template, SourceLocation TemplateLoc,
5287  TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5288  SmallVectorImpl<TemplateArgument> &SugaredConverted,
5289  SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5290  bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied,
5291  bool PartialOrderingTTP) {
5292 
5294  *ConstraintsNotSatisfied = false;
5295 
5296  // Make a copy of the template arguments for processing. Only make the
5297  // changes at the end when successful in matching the arguments to the
5298  // template.
5299  TemplateArgumentListInfo NewArgs = TemplateArgs;
5300 
5301  TemplateParameterList *Params = GetTemplateParameterList(Template);
5302 
5303  SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5304 
5305  // C++ [temp.arg]p1:
5306  // [...] The type and form of each template-argument specified in
5307  // a template-id shall match the type and form specified for the
5308  // corresponding parameter declared by the template in its
5309  // template-parameter-list.
5310  bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5311  SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5312  SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5313  unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5314  LocalInstantiationScope InstScope(*this, true);
5315  for (TemplateParameterList::iterator Param = Params->begin(),
5316  ParamEnd = Params->end();
5317  Param != ParamEnd; /* increment in loop */) {
5318  // If we have an expanded parameter pack, make sure we don't have too
5319  // many arguments.
5320  if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5321  if (*Expansions == SugaredArgumentPack.size()) {
5322  // We're done with this parameter pack. Pack up its arguments and add
5323  // them to the list.
5324  SugaredConverted.push_back(
5325  TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5326  SugaredArgumentPack.clear();
5327 
5328  CanonicalConverted.push_back(
5329  TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5330  CanonicalArgumentPack.clear();
5331 
5332  // This argument is assigned to the next parameter.
5333  ++Param;
5334  continue;
5335  } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5336  // Not enough arguments for this parameter pack.
5337  Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5338  << /*not enough args*/0
5339  << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5340  << Template;
5341  NoteTemplateLocation(*Template, Params->getSourceRange());
5342  return true;
5343  }
5344  }
5345 
5346  if (ArgIdx < NumArgs) {
5347  // Check the template argument we were given.
5348  if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
5349  RAngleLoc, SugaredArgumentPack.size(),
5350  SugaredConverted, CanonicalConverted,
5351  CTAK_Specified))
5352  return true;
5353 
5354  CanonicalConverted.back().setIsDefaulted(
5356  Context, NewArgs[ArgIdx].getArgument(), *Param,
5357  CanonicalConverted, Params->getDepth()));
5358 
5359  bool PackExpansionIntoNonPack =
5360  NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5361  (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5362  // CWG1430: Don't diagnose this pack expansion when partial
5363  // ordering template template parameters. Some uses of the template could
5364  // be valid, and invalid uses will be diagnosed later during
5365  // instantiation.
5366  if (PackExpansionIntoNonPack && !PartialOrderingTTP &&
5367  (isa<TypeAliasTemplateDecl>(Template) ||
5368  isa<ConceptDecl>(Template))) {
5369  // CWG1430: we have a pack expansion as an argument to an
5370  // alias template, and it's not part of a parameter pack. This
5371  // can't be canonicalized, so reject it now.
5372  // As for concepts - we cannot normalize constraints where this
5373  // situation exists.
5374  Diag(NewArgs[ArgIdx].getLocation(),
5375  diag::err_template_expansion_into_fixed_list)
5376  << (isa<ConceptDecl>(Template) ? 1 : 0)
5377  << NewArgs[ArgIdx].getSourceRange();
5378  NoteTemplateParameterLocation(**Param);
5379  return true;
5380  }
5381 
5382  // We're now done with this argument.
5383  ++ArgIdx;
5384 
5385  if ((*Param)->isTemplateParameterPack()) {
5386  // The template parameter was a template parameter pack, so take the
5387  // deduced argument and place it on the argument pack. Note that we
5388  // stay on the same template parameter so that we can deduce more
5389  // arguments.
5390  SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
5391  CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
5392  } else {
5393  // Move to the next template parameter.
5394  ++Param;
5395  }
5396 
5397  // If we just saw a pack expansion into a non-pack, then directly convert
5398  // the remaining arguments, because we don't know what parameters they'll
5399  // match up with.
5400  if (PackExpansionIntoNonPack) {
5401  if (!SugaredArgumentPack.empty()) {
5402  // If we were part way through filling in an expanded parameter pack,
5403  // fall back to just producing individual arguments.
5404  SugaredConverted.insert(SugaredConverted.end(),
5405  SugaredArgumentPack.begin(),
5406  SugaredArgumentPack.end());
5407  SugaredArgumentPack.clear();
5408 
5409  CanonicalConverted.insert(CanonicalConverted.end(),
5410  CanonicalArgumentPack.begin(),
5411  CanonicalArgumentPack.end());
5412  CanonicalArgumentPack.clear();
5413  }
5414 
5415  while (ArgIdx < NumArgs) {
5416  const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5417  SugaredConverted.push_back(Arg);
5418  CanonicalConverted.push_back(
5419  Context.getCanonicalTemplateArgument(Arg));
5420  ++ArgIdx;
5421  }
5422 
5423  return false;
5424  }
5425 
5426  continue;
5427  }
5428 
5429  // If we're checking a partial template argument list, we're done.
5430  if (PartialTemplateArgs) {
5431  if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
5432  SugaredConverted.push_back(
5433  TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5434  CanonicalConverted.push_back(
5435  TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5436  }
5437  return false;
5438  }
5439 
5440  // If we have a template parameter pack with no more corresponding
5441  // arguments, just break out now and we'll fill in the argument pack below.
5442  if ((*Param)->isTemplateParameterPack()) {
5443  assert(!getExpandedPackSize(*Param) &&
5444  "Should have dealt with this already");
5445 
5446  // A non-expanded parameter pack before the end of the parameter list
5447  // only occurs for an ill-formed template parameter list, unless we've
5448  // got a partial argument list for a function template, so just bail out.
5449  if (Param + 1 != ParamEnd) {
5450  assert(
5451  (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
5452  "Concept templates must have parameter packs at the end.");
5453  return true;
5454  }
5455 
5456  SugaredConverted.push_back(
5457  TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5458  SugaredArgumentPack.clear();
5459 
5460  CanonicalConverted.push_back(
5461  TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5462  CanonicalArgumentPack.clear();
5463 
5464  ++Param;
5465  continue;
5466  }
5467 
5468  // Check whether we have a default argument.
5469  TemplateArgumentLoc Arg;
5470 
5471  // Retrieve the default template argument from the template
5472  // parameter. For each kind of template parameter, we substitute the
5473  // template arguments provided thus far and any "outer" template arguments
5474  // (when the template parameter was part of a nested template) into
5475  // the default argument.
5476  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5477  if (!hasReachableDefaultArgument(TTP))
5478  return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5479  NewArgs);
5480 
5481  if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5482  TTP, SugaredConverted,
5483  CanonicalConverted, Arg))
5484  return true;
5485  } else if (NonTypeTemplateParmDecl *NTTP
5486  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5487  if (!hasReachableDefaultArgument(NTTP))
5488  return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5489  NewArgs);
5490 
5491  if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5492  NTTP, SugaredConverted,
5493  CanonicalConverted, Arg))
5494  return true;
5495  } else {
5496  TemplateTemplateParmDecl *TempParm
5497  = cast<TemplateTemplateParmDecl>(*Param);
5498 
5499  if (!hasReachableDefaultArgument(TempParm))
5500  return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5501  NewArgs);
5502 
5503  NestedNameSpecifierLoc QualifierLoc;
5505  *this, Template, TemplateLoc, RAngleLoc, TempParm, SugaredConverted,
5506  CanonicalConverted, QualifierLoc);
5507  if (Name.isNull())
5508  return true;
5509 
5510  Arg = TemplateArgumentLoc(
5511  Context, TemplateArgument(Name), QualifierLoc,
5512  TempParm->getDefaultArgument().getTemplateNameLoc());
5513  }
5514 
5515  // Introduce an instantiation record that describes where we are using
5516  // the default template argument. We're not actually instantiating a
5517  // template here, we just create this object to put a note into the
5518  // context stack.
5519  InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
5520  SugaredConverted,
5521  SourceRange(TemplateLoc, RAngleLoc));
5522  if (Inst.isInvalid())
5523  return true;
5524 
5525  // Check the default template argument.
5526  if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
5527  SugaredConverted, CanonicalConverted,
5528  CTAK_Specified))
5529  return true;
5530 
5531  CanonicalConverted.back().setIsDefaulted(true);
5532 
5533  // Core issue 150 (assumed resolution): if this is a template template
5534  // parameter, keep track of the default template arguments from the
5535  // template definition.
5536  if (isTemplateTemplateParameter)
5537  NewArgs.addArgument(Arg);
5538 
5539  // Move to the next template parameter and argument.
5540  ++Param;
5541  ++ArgIdx;
5542  }
5543 
5544  // If we're performing a partial argument substitution, allow any trailing
5545  // pack expansions; they might be empty. This can happen even if
5546  // PartialTemplateArgs is false (the list of arguments is complete but
5547  // still dependent).
5548  if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5549  CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5550  while (ArgIdx < NumArgs &&
5551  NewArgs[ArgIdx].getArgument().isPackExpansion()) {
5552  const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
5553  SugaredConverted.push_back(Arg);
5554  CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
5555  }
5556  }
5557 
5558  // If we have any leftover arguments, then there were too many arguments.
5559  // Complain and fail.
5560  if (ArgIdx < NumArgs) {
5561  Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5562  << /*too many args*/1
5563  << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5564  << Template
5565  << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5566  NoteTemplateLocation(*Template, Params->getSourceRange());
5567  return true;
5568  }
5569 
5570  // No problems found with the new argument list, propagate changes back
5571  // to caller.
5572  if (UpdateArgsWithConversions)
5573  TemplateArgs = std::move(NewArgs);
5574 
5575  if (!PartialTemplateArgs) {
5576  // Setup the context/ThisScope for the case where we are needing to
5577  // re-instantiate constraints outside of normal instantiation.
5578  DeclContext *NewContext = Template->getDeclContext();
5579 
5580  // If this template is in a template, make sure we extract the templated
5581  // decl.
5582  if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
5583  NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
5584  auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
5585 
5586  Qualifiers ThisQuals;
5587  if (const auto *Method =
5588  dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
5589  ThisQuals = Method->getMethodQualifiers();
5590 
5591  ContextRAII Context(*this, NewContext);
5592  CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
5593 
5594  MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
5595  Template, NewContext, /*Final=*/false, CanonicalConverted,
5596  /*RelativeToPrimary=*/true,
5597  /*Pattern=*/nullptr,
5598  /*ForConceptInstantiation=*/true);
5599  if (EnsureTemplateArgumentListConstraints(
5600  Template, MLTAL,
5601  SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
5603  *ConstraintsNotSatisfied = true;
5604  return true;
5605  }
5606  }
5607 
5608  return false;
5609 }
5610 
5611 namespace {
5612  class UnnamedLocalNoLinkageFinder
5613  : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5614  {
5615  Sema &S;
5616  SourceRange SR;
5617 
5619 
5620  public:
5621  UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5622 
5623  bool Visit(QualType T) {
5624  return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5625  }
5626 
5627 #define TYPE(Class, Parent) \
5628  bool Visit##Class##Type(const Class##Type *);
5629 #define ABSTRACT_TYPE(Class, Parent) \
5630  bool Visit##Class##Type(const Class##Type *) { return false; }
5631 #define NON_CANONICAL_TYPE(Class, Parent) \
5632  bool Visit##Class##Type(const Class##Type *) { return false; }
5633 #include "clang/AST/TypeNodes.inc"
5634 
5635  bool VisitTagDecl(const TagDecl *Tag);
5636  bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5637  };
5638 } // end anonymous namespace
5639 
5640 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5641  return false;
5642 }
5643 
5644 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5645  return Visit(T->getElementType());
5646 }
5647 
5648 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5649  return Visit(T->getPointeeType());
5650 }
5651 
5652 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5653  const BlockPointerType* T) {
5654  return Visit(T->getPointeeType());
5655 }
5656 
5657 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5658  const LValueReferenceType* T) {
5659  return Visit(T->getPointeeType());
5660 }
5661 
5662 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5663  const RValueReferenceType* T) {
5664  return Visit(T->getPointeeType());
5665 }
5666 
5667 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5668  const MemberPointerType* T) {
5669  return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5670 }
5671 
5672 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5673  const ConstantArrayType* T) {
5674  return Visit(T->getElementType());
5675 }
5676 
5677 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5678  const IncompleteArrayType* T) {
5679  return Visit(T->getElementType());
5680 }
5681 
5682 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5683  const VariableArrayType* T) {
5684  return Visit(T->getElementType());
5685 }
5686 
5687 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5688  const DependentSizedArrayType* T) {
5689  return Visit(T->getElementType());
5690 }
5691 
5692 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5693  const DependentSizedExtVectorType* T) {
5694  return Visit(T->getElementType());
5695 }
5696 
5697 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
5698  const DependentSizedMatrixType *T) {
5699  return Visit(T->getElementType());
5700 }
5701 
5702 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5703  const DependentAddressSpaceType *T) {
5704  return Visit(T->getPointeeType());
5705 }
5706 
5707 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5708  return Visit(T->getElementType());
5709 }
5710 
5711 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5712  const DependentVectorType *T) {
5713  return Visit(T->getElementType());
5714 }
5715 
5716 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5717  return Visit(T->getElementType());
5718 }
5719 
5720 bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
5721  const ConstantMatrixType *T) {
5722  return Visit(T->getElementType());
5723 }
5724 
5725 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5726  const FunctionProtoType* T) {
5727  for (const auto &A : T->param_types()) {
5728  if (Visit(A))
5729  return true;
5730  }
5731 
5732  return Visit(T->getReturnType());
5733 }
5734 
5735 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5736  const FunctionNoProtoType* T) {
5737  return Visit(T->getReturnType());
5738 }
5739 
5740 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5741  const UnresolvedUsingType*) {
5742  return false;
5743 }
5744 
5745 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5746  return false;
5747 }
5748 
5749 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5750  return Visit(T->getUnmodifiedType());
5751 }
5752 
5753 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5754  return false;
5755 }
5756 
5757 bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
5758  const PackIndexingType *) {
5759  return false;
5760 }
5761 
5762 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5763  const UnaryTransformType*) {
5764  return false;
5765 }
5766 
5767 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5768  return Visit(T->getDeducedType());
5769 }
5770 
5771 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5773  return Visit(T->getDeducedType());
5774 }
5775 
5776 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5777  return VisitTagDecl(T->getDecl());
5778 }
5779 
5780 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5781  return VisitTagDecl(T->getDecl());
5782 }
5783 
5784 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5785  const TemplateTypeParmType*) {
5786  return false;
5787 }
5788 
5789 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5791  return false;
5792 }
5793 
5794 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5795  const TemplateSpecializationType*) {
5796  return false;
5797 }
5798 
5799 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5800  const InjectedClassNameType* T) {
5801  return VisitTagDecl(T->getDecl());
5802 }
5803 
5804 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5805  const DependentNameType* T) {
5806  return VisitNestedNameSpecifier(T->getQualifier());
5807 }
5808 
5809 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5811  if (auto *Q = T->getQualifier())
5812  return VisitNestedNameSpecifier(Q);
5813  return false;
5814 }
5815 
5816 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5817  const PackExpansionType* T) {
5818  return Visit(T->getPattern());
5819 }
5820 
5821 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5822  return false;
5823 }
5824 
5825 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5826  const ObjCInterfaceType *) {
5827  return false;
5828 }
5829 
5830 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5831  const ObjCObjectPointerType *) {
5832  return false;
5833 }
5834 
5835 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5836  return Visit(T->getValueType());
5837 }
5838 
5839 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5840  return false;
5841 }
5842 
5843 bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
5844  return false;
5845 }
5846 
5847 bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
5848  const ArrayParameterType *T) {
5849  return VisitConstantArrayType(T);
5850 }
5851 
5852 bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
5853  const DependentBitIntType *T) {
5854  return false;
5855 }
5856 
5857 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5858  if (Tag->getDeclContext()->isFunctionOrMethod()) {
5859  S.Diag(SR.getBegin(),
5860  S.getLangOpts().CPlusPlus11 ?
5861  diag::warn_cxx98_compat_template_arg_local_type :
5862  diag::ext_template_arg_local_type)
5863  << S.Context.getTypeDeclType(Tag) << SR;
5864  return true;
5865  }
5866 
5867  if (!Tag->hasNameForLinkage()) {
5868  S.Diag(SR.getBegin(),
5869  S.getLangOpts().CPlusPlus11 ?
5870  diag::warn_cxx98_compat_template_arg_unnamed_type :
5871  diag::ext_template_arg_unnamed_type) << SR;
5872  S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5873  return true;
5874  }
5875 
5876  return false;
5877 }
5878 
5879 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5880  NestedNameSpecifier *NNS) {
5881  assert(NNS);
5882  if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5883  return true;
5884 
5885  switch (NNS->getKind()) {
5891  return false;
5892 
5895  return Visit(QualType(NNS->getAsType(), 0));
5896  }
5897  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5898 }
5899 
5901  assert(ArgInfo && "invalid TypeSourceInfo");
5902  QualType Arg = ArgInfo->getType();
5903  SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5904  QualType CanonArg = Context.getCanonicalType(Arg);
5905 
5906  if (CanonArg->isVariablyModifiedType()) {
5907  return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5908  } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5909  return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5910  }
5911 
5912  // C++03 [temp.arg.type]p2:
5913  // A local type, a type with no linkage, an unnamed type or a type
5914  // compounded from any of these types shall not be used as a
5915  // template-argument for a template type-parameter.
5916  //
5917  // C++11 allows these, and even in C++03 we allow them as an extension with
5918  // a warning.
5919  if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
5920  UnnamedLocalNoLinkageFinder Finder(*this, SR);
5921  (void)Finder.Visit(CanonArg);
5922  }
5923 
5924  return false;
5925 }
5926 
5930  NPV_Error
5931 };
5932 
5933 /// Determine whether the given template argument is a null pointer
5934 /// value of the appropriate type.
5935 static NullPointerValueKind
5937  QualType ParamType, Expr *Arg,
5938  Decl *Entity = nullptr) {
5939  if (Arg->isValueDependent() || Arg->isTypeDependent())
5940  return NPV_NotNullPointer;
5941 
5942  // dllimport'd entities aren't constant but are available inside of template
5943  // arguments.
5944  if (Entity && Entity->hasAttr<DLLImportAttr>())
5945  return NPV_NotNullPointer;
5946 
5947  if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5948  llvm_unreachable(
5949  "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5950 
5951  if (!S.getLangOpts().CPlusPlus11)
5952  return NPV_NotNullPointer;
5953 
5954  // Determine whether we have a constant expression.
5956  if (ArgRV.isInvalid())
5957  return NPV_Error;
5958  Arg = ArgRV.get();
5959 
5960  Expr::EvalResult EvalResult;
5962  EvalResult.Diag = &Notes;
5963  if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5964  EvalResult.HasSideEffects) {
5965  SourceLocation DiagLoc = Arg->getExprLoc();
5966 
5967  // If our only note is the usual "invalid subexpression" note, just point
5968  // the caret at its location rather than producing an essentially
5969  // redundant note.
5970  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5971  diag::note_invalid_subexpr_in_const_expr) {
5972  DiagLoc = Notes[0].first;
5973  Notes.clear();
5974  }
5975 
5976  S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5977  << Arg->getType() << Arg->getSourceRange();
5978  for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5979  S.Diag(Notes[I].first, Notes[I].second);
5980 
5982  return NPV_Error;
5983  }
5984 
5985  // C++11 [temp.arg.nontype]p1:
5986  // - an address constant expression of type std::nullptr_t
5987  if (Arg->getType()->isNullPtrType())
5988  return NPV_NullPointer;
5989 
5990  // - a constant expression that evaluates to a null pointer value (4.10); or
5991  // - a constant expression that evaluates to a null member pointer value
5992  // (4.11); or
5993  if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
5994  (EvalResult.Val.isMemberPointer() &&
5995  !EvalResult.Val.getMemberPointerDecl())) {
5996  // If our expression has an appropriate type, we've succeeded.
5997  bool ObjCLifetimeConversion;
5998  if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5999  S.IsQualificationConversion(Arg->getType(), ParamType, false,
6000  ObjCLifetimeConversion))
6001  return NPV_NullPointer;
6002 
6003  // The types didn't match, but we know we got a null pointer; complain,
6004  // then recover as if the types were correct.
6005  S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6006  << Arg->getType() << ParamType << Arg->getSourceRange();
6008  return NPV_NullPointer;
6009  }
6010 
6011  if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6012  // We found a pointer that isn't null, but doesn't refer to an object.
6013  // We could just return NPV_NotNullPointer, but we can print a better
6014  // message with the information we have here.
6015  S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6016  << EvalResult.Val.getAsString(S.Context, ParamType);
6018  return NPV_Error;
6019  }
6020 
6021  // If we don't have a null pointer value, but we do have a NULL pointer
6022  // constant, suggest a cast to the appropriate type.
6024  std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6025  S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6026  << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6028  ")");
6030  return NPV_NullPointer;
6031  }
6032 
6033  // FIXME: If we ever want to support general, address-constant expressions
6034  // as non-type template arguments, we should return the ExprResult here to
6035  // be interpreted by the caller.
6036  return NPV_NotNullPointer;
6037 }
6038 
6039 /// Checks whether the given template argument is compatible with its
6040 /// template parameter.
6042  Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6043  Expr *Arg, QualType ArgType) {
6044  bool ObjCLifetimeConversion;
6045  if (ParamType->isPointerType() &&
6046  !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6047  S.IsQualificationConversion(ArgType, ParamType, false,
6048  ObjCLifetimeConversion)) {
6049  // For pointer-to-object types, qualification conversions are
6050  // permitted.
6051  } else {
6052  if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6053  if (!ParamRef->getPointeeType()->isFunctionType()) {
6054  // C++ [temp.arg.nontype]p5b3:
6055  // For a non-type template-parameter of type reference to
6056  // object, no conversions apply. The type referred to by the
6057  // reference may be more cv-qualified than the (otherwise
6058  // identical) type of the template- argument. The
6059  // template-parameter is bound directly to the
6060  // template-argument, which shall be an lvalue.
6061 
6062  // FIXME: Other qualifiers?
6063  unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6064  unsigned ArgQuals = ArgType.getCVRQualifiers();
6065 
6066  if ((ParamQuals | ArgQuals) != ParamQuals) {
6067  S.Diag(Arg->getBeginLoc(),
6068  diag::err_template_arg_ref_bind_ignores_quals)
6069  << ParamType << Arg->getType() << Arg->getSourceRange();
6071  return true;
6072  }
6073  }
6074  }
6075 
6076  // At this point, the template argument refers to an object or
6077  // function with external linkage. We now need to check whether the
6078  // argument and parameter types are compatible.
6079  if (!S.Context.hasSameUnqualifiedType(ArgType,
6080  ParamType.getNonReferenceType())) {
6081  // We can't perform this conversion or binding.
6082  if (ParamType->isReferenceType())
6083  S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6084  << ParamType << ArgIn->getType() << Arg->getSourceRange();
6085  else
6086  S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6087  << ArgIn->getType() << ParamType << Arg->getSourceRange();
6089  return true;
6090  }
6091  }
6092 
6093  return false;
6094 }
6095 
6096 /// Checks whether the given template argument is the address
6097 /// of an object or function according to C++ [temp.arg.nontype]p1.
6099  Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6100  TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6101  bool Invalid = false;
6102  Expr *Arg = ArgIn;
6103  QualType ArgType = Arg->getType();
6104 
6105  bool AddressTaken = false;
6106  SourceLocation AddrOpLoc;
6107  if (S.getLangOpts().MicrosoftExt) {
6108  // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6109  // dereference and address-of operators.
6110  Arg = Arg->IgnoreParenCasts();
6111 
6112  bool ExtWarnMSTemplateArg = false;
6113  UnaryOperatorKind FirstOpKind;
6114  SourceLocation FirstOpLoc;
6115  while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6116  UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6117  if (UnOpKind == UO_Deref)
6118  ExtWarnMSTemplateArg = true;
6119  if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6120  Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6121  if (!AddrOpLoc.isValid()) {
6122  FirstOpKind = UnOpKind;
6123  FirstOpLoc = UnOp->getOperatorLoc();
6124  }
6125  } else
6126  break;
6127  }
6128  if (FirstOpLoc.isValid()) {
6129  if (ExtWarnMSTemplateArg)
6130  S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6131  << ArgIn->getSourceRange();
6132 
6133  if (FirstOpKind == UO_AddrOf)
6134  AddressTaken = true;
6135  else if (Arg->getType()->isPointerType()) {
6136  // We cannot let pointers get dereferenced here, that is obviously not a
6137  // constant expression.
6138  assert(FirstOpKind == UO_Deref);
6139  S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6140  << Arg->getSourceRange();
6141  }
6142  }
6143  } else {
6144  // See through any implicit casts we added to fix the type.
6145  Arg = Arg->IgnoreImpCasts();
6146 
6147  // C++ [temp.arg.nontype]p1:
6148  //
6149  // A template-argument for a non-type, non-template
6150  // template-parameter shall be one of: [...]
6151  //
6152  // -- the address of an object or function with external
6153  // linkage, including function templates and function
6154  // template-ids but excluding non-static class members,
6155  // expressed as & id-expression where the & is optional if
6156  // the name refers to a function or array, or if the
6157  // corresponding template-parameter is a reference; or
6158 
6159  // In C++98/03 mode, give an extension warning on any extra parentheses.
6160  // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6161  bool ExtraParens = false;
6162  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6163  if (!Invalid && !ExtraParens) {
6164  S.Diag(Arg->getBeginLoc(),
6165  S.getLangOpts().CPlusPlus11
6166  ? diag::warn_cxx98_compat_template_arg_extra_parens
6167  : diag::ext_template_arg_extra_parens)
6168  << Arg->getSourceRange();
6169  ExtraParens = true;
6170  }
6171 
6172  Arg = Parens->getSubExpr();
6173  }
6174 
6175  while (SubstNonTypeTemplateParmExpr *subst =
6176  dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6177  Arg = subst->getReplacement()->IgnoreImpCasts();
6178 
6179  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6180  if (UnOp->getOpcode() == UO_AddrOf) {
6181  Arg = UnOp->getSubExpr();
6182  AddressTaken = true;
6183  AddrOpLoc = UnOp->getOperatorLoc();
6184  }
6185  }
6186 
6187  while (SubstNonTypeTemplateParmExpr *subst =
6188  dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6189  Arg = subst->getReplacement()->IgnoreImpCasts();
6190  }
6191 
6192  ValueDecl *Entity = nullptr;
6193  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6194  Entity = DRE->getDecl();
6195  else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6196  Entity = CUE->getGuidDecl();
6197 
6198  // If our parameter has pointer type, check for a null template value.
6199  if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6200  switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6201  Entity)) {
6202  case NPV_NullPointer:
6203  S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6204  SugaredConverted = TemplateArgument(ParamType,
6205  /*isNullPtr=*/true);
6206  CanonicalConverted =
6208  /*isNullPtr=*/true);
6209  return false;
6210 
6211  case NPV_Error:
6212  return true;
6213 
6214  case NPV_NotNullPointer:
6215  break;
6216  }
6217  }
6218 
6219  // Stop checking the precise nature of the argument if it is value dependent,
6220  // it should be checked when instantiated.
6221  if (Arg->isValueDependent()) {
6222  SugaredConverted = TemplateArgument(ArgIn);
6223  CanonicalConverted =
6224  S.Context.getCanonicalTemplateArgument(SugaredConverted);
6225  return false;
6226  }
6227 
6228  if (!Entity) {
6229  S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6230  << Arg->getSourceRange();
6232  return true;
6233  }
6234 
6235  // Cannot refer to non-static data members
6236  if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6237  S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6238  << Entity << Arg->getSourceRange();
6240  return true;
6241  }
6242 
6243  // Cannot refer to non-static member functions
6244  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6245  if (!Method->isStatic()) {
6246  S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6247  << Method << Arg->getSourceRange();
6249  return true;
6250  }
6251  }
6252 
6253  FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6254  VarDecl *Var = dyn_cast<VarDecl>(Entity);
6255  MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6256 
6257  // A non-type template argument must refer to an object or function.
6258  if (!Func && !Var && !Guid) {
6259  // We found something, but we don't know specifically what it is.
6260  S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6261  << Arg->getSourceRange();
6262  S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6263  return true;
6264  }
6265 
6266  // Address / reference template args must have external linkage in C++98.
6267  if (Entity->getFormalLinkage() == Linkage::Internal) {
6268  S.Diag(Arg->getBeginLoc(),
6269  S.getLangOpts().CPlusPlus11
6270  ? diag::warn_cxx98_compat_template_arg_object_internal
6271  : diag::ext_template_arg_object_internal)
6272  << !Func << Entity << Arg->getSourceRange();
6273  S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6274  << !Func;
6275  } else if (!Entity->hasLinkage()) {
6276  S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6277  << !Func << Entity << Arg->getSourceRange();
6278  S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6279  << !Func;
6280  return true;
6281  }
6282 
6283  if (Var) {
6284  // A value of reference type is not an object.
6285  if (Var->getType()->isReferenceType()) {
6286  S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6287  << Var->getType() << Arg->getSourceRange();
6289  return true;
6290  }
6291 
6292  // A template argument must have static storage duration.
6293  if (Var->getTLSKind()) {
6294  S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6295  << Arg->getSourceRange();
6296  S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6297  return true;
6298  }
6299  }
6300 
6301  if (AddressTaken && ParamType->isReferenceType()) {
6302  // If we originally had an address-of operator, but the
6303  // parameter has reference type, complain and (if things look
6304  // like they will work) drop the address-of operator.
6305  if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6306  ParamType.getNonReferenceType())) {
6307  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6308  << ParamType;
6310  return true;
6311  }
6312 
6313  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6314  << ParamType
6315  << FixItHint::CreateRemoval(AddrOpLoc);
6317 
6318  ArgType = Entity->getType();
6319  }
6320 
6321  // If the template parameter has pointer type, either we must have taken the
6322  // address or the argument must decay to a pointer.
6323  if (!AddressTaken && ParamType->isPointerType()) {
6324  if (Func) {
6325  // Function-to-pointer decay.
6326  ArgType = S.Context.getPointerType(Func->getType());
6327  } else if (Entity->getType()->isArrayType()) {
6328  // Array-to-pointer decay.
6329  ArgType = S.Context.getArrayDecayedType(Entity->getType());
6330  } else {
6331  // If the template parameter has pointer type but the address of
6332  // this object was not taken, complain and (possibly) recover by
6333  // taking the address of the entity.
6334  ArgType = S.Context.getPointerType(Entity->getType());
6335  if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6336  S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6337  << ParamType;
6339  return true;
6340  }
6341 
6342  S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6343  << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6344 
6346  }
6347  }
6348 
6349  if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6350  Arg, ArgType))
6351  return true;
6352 
6353  // Create the template argument.
6354  SugaredConverted = TemplateArgument(Entity, ParamType);
6355  CanonicalConverted =
6356  TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
6357  S.Context.getCanonicalType(ParamType));
6358  S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6359  return false;
6360 }
6361 
6362 /// Checks whether the given template argument is a pointer to
6363 /// member constant according to C++ [temp.arg.nontype]p1.
6364 static bool
6366  QualType ParamType, Expr *&ResultArg,
6367  TemplateArgument &SugaredConverted,
6368  TemplateArgument &CanonicalConverted) {
6369  bool Invalid = false;
6370 
6371  Expr *Arg = ResultArg;
6372  bool ObjCLifetimeConversion;
6373 
6374  // C++ [temp.arg.nontype]p1:
6375  //
6376  // A template-argument for a non-type, non-template
6377  // template-parameter shall be one of: [...]
6378  //
6379  // -- a pointer to member expressed as described in 5.3.1.
6380  DeclRefExpr *DRE = nullptr;
6381 
6382  // In C++98/03 mode, give an extension warning on any extra parentheses.
6383  // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6384  bool ExtraParens = false;
6385  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6386  if (!Invalid && !ExtraParens) {
6387  S.Diag(Arg->getBeginLoc(),
6388  S.getLangOpts().CPlusPlus11
6389  ? diag::warn_cxx98_compat_template_arg_extra_parens
6390  : diag::ext_template_arg_extra_parens)
6391  << Arg->getSourceRange();
6392  ExtraParens = true;
6393  }
6394 
6395  Arg = Parens->getSubExpr();
6396  }
6397 
6398  while (SubstNonTypeTemplateParmExpr *subst =
6399  dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6400  Arg = subst->getReplacement()->IgnoreImpCasts();
6401 
6402  // A pointer-to-member constant written &Class::member.
6403  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6404  if (UnOp->getOpcode() == UO_AddrOf) {
6405  DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6406  if (DRE && !DRE->getQualifier())
6407  DRE = nullptr;
6408  }
6409  }
6410  // A constant of pointer-to-member type.
6411  else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6412  ValueDecl *VD = DRE->getDecl();
6413  if (VD->getType()->isMemberPointerType()) {
6414  if (isa<NonTypeTemplateParmDecl>(VD)) {
6415  if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6416  SugaredConverted = TemplateArgument(Arg);
6417  CanonicalConverted =
6418  S.Context.getCanonicalTemplateArgument(SugaredConverted);
6419  } else {
6420  SugaredConverted = TemplateArgument(VD, ParamType);
6421  CanonicalConverted =
6422  TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
6423  S.Context.getCanonicalType(ParamType));
6424  }
6425  return Invalid;
6426  }
6427  }
6428 
6429  DRE = nullptr;
6430  }
6431 
6432  ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6433 
6434  // Check for a null pointer value.
6435  switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6436  Entity)) {
6437  case NPV_Error:
6438  return true;
6439  case NPV_NullPointer:
6440  S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6441  SugaredConverted = TemplateArgument(ParamType,
6442  /*isNullPtr*/ true);
6443  CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6444  /*isNullPtr*/ true);
6445  return false;
6446  case NPV_NotNullPointer:
6447  break;
6448  }
6449 
6450  if (S.IsQualificationConversion(ResultArg->getType(),
6451  ParamType.getNonReferenceType(), false,
6452  ObjCLifetimeConversion)) {
6453  ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6454  ResultArg->getValueKind())
6455  .get();
6456  } else if (!S.Context.hasSameUnqualifiedType(
6457  ResultArg->getType(), ParamType.getNonReferenceType())) {
6458  // We can't perform this conversion.
6459  S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6460  << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6462  return true;
6463  }
6464 
6465  if (!DRE)
6466  return S.Diag(Arg->getBeginLoc(),
6467  diag::err_template_arg_not_pointer_to_member_form)
6468  << Arg->getSourceRange();
6469 
6470  if (isa<FieldDecl>(DRE->getDecl()) ||
6471  isa<IndirectFieldDecl>(DRE->getDecl()) ||
6472  isa<CXXMethodDecl>(DRE->getDecl())) {
6473  assert((isa<FieldDecl>(DRE->getDecl()) ||
6474  isa<IndirectFieldDecl>(DRE->getDecl()) ||
6475  cast<CXXMethodDecl>(DRE->getDecl())
6476  ->isImplicitObjectMemberFunction()) &&
6477  "Only non-static member pointers can make it here");
6478 
6479  // Okay: this is the address of a non-static member, and therefore
6480  // a member pointer constant.
6481  if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6482  SugaredConverted = TemplateArgument(Arg);
6483  CanonicalConverted =
6484  S.Context.getCanonicalTemplateArgument(SugaredConverted);
6485  } else {
6486  ValueDecl *D = DRE->getDecl();
6487  SugaredConverted = TemplateArgument(D, ParamType);
6488  CanonicalConverted =
6489  TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
6490  S.Context.getCanonicalType(ParamType));
6491  }
6492  return Invalid;
6493  }
6494 
6495  // We found something else, but we don't know specifically what it is.
6496  S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6497  << Arg->getSourceRange();
6498  S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6499  return true;
6500 }
6501 
6503  QualType ParamType, Expr *Arg,
6504  TemplateArgument &SugaredConverted,
6505  TemplateArgument &CanonicalConverted,
6507  SourceLocation StartLoc = Arg->getBeginLoc();
6508 
6509  // If the parameter type somehow involves auto, deduce the type now.
6510  DeducedType *DeducedT = ParamType->getContainedDeducedType();
6511  if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
6512  // During template argument deduction, we allow 'decltype(auto)' to
6513  // match an arbitrary dependent argument.
6514  // FIXME: The language rules don't say what happens in this case.
6515  // FIXME: We get an opaque dependent type out of decltype(auto) if the
6516  // expression is merely instantiation-dependent; is this enough?
6517  if (Arg->isTypeDependent()) {
6518  auto *AT = dyn_cast<AutoType>(DeducedT);
6519  if (AT && AT->isDecltypeAuto()) {
6520  SugaredConverted = TemplateArgument(Arg);
6521  CanonicalConverted = TemplateArgument(
6522  Context.getCanonicalTemplateArgument(SugaredConverted));
6523  return Arg;
6524  }
6525  }
6526 
6527  // When checking a deduced template argument, deduce from its type even if
6528  // the type is dependent, in order to check the types of non-type template
6529  // arguments line up properly in partial ordering.
6530  Expr *DeductionArg = Arg;
6531  if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6532  DeductionArg = PE->getPattern();
6533  TypeSourceInfo *TSI =
6534  Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
6535  if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
6536  InitializedEntity Entity =
6539  DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
6540  Expr *Inits[1] = {DeductionArg};
6541  ParamType =
6542  DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
6543  if (ParamType.isNull())
6544  return ExprError();
6545  } else {
6546  TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
6547  Param->getDepth() + 1);
6548  ParamType = QualType();
6549  TemplateDeductionResult Result =
6550  DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
6551  /*DependentDeduction=*/true,
6552  // We do not check constraints right now because the
6553  // immediately-declared constraint of the auto type is
6554  // also an associated constraint, and will be checked
6555  // along with the other associated constraints after
6556  // checking the template argument list.
6557  /*IgnoreConstraints=*/true);
6559  if (ParamType.isNull())
6560  return ExprError();
6561  } else if (Result != TemplateDeductionResult::Success) {
6562  Diag(Arg->getExprLoc(),
6563  diag::err_non_type_template_parm_type_deduction_failure)
6564  << Param->getDeclName() << Param->getType() << Arg->getType()
6565  << Arg->getSourceRange();
6566  NoteTemplateParameterLocation(*Param);
6567  return ExprError();
6568  }
6569  }
6570  // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6571  // an error. The error message normally references the parameter
6572  // declaration, but here we'll pass the argument location because that's
6573  // where the parameter type is deduced.
6574  ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6575  if (ParamType.isNull()) {
6576  NoteTemplateParameterLocation(*Param);
6577  return ExprError();
6578  }
6579  }
6580 
6581  // We should have already dropped all cv-qualifiers by now.
6582  assert(!ParamType.hasQualifiers() &&
6583  "non-type template parameter type cannot be qualified");
6584 
6585  // FIXME: When Param is a reference, should we check that Arg is an lvalue?
6586  if (CTAK == CTAK_Deduced &&
6587  (ParamType->isReferenceType()
6588  ? !Context.hasSameType(ParamType.getNonReferenceType(),
6589  Arg->getType())
6590  : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
6591  // FIXME: If either type is dependent, we skip the check. This isn't
6592  // correct, since during deduction we're supposed to have replaced each
6593  // template parameter with some unique (non-dependent) placeholder.
6594  // FIXME: If the argument type contains 'auto', we carry on and fail the
6595  // type check in order to force specific types to be more specialized than
6596  // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6597  // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
6598  if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6599  !Arg->getType()->getContainedDeducedType()) {
6600  SugaredConverted = TemplateArgument(Arg);
6601  CanonicalConverted = TemplateArgument(
6602  Context.getCanonicalTemplateArgument(SugaredConverted));
6603  return Arg;
6604  }
6605  // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6606  // we should actually be checking the type of the template argument in P,
6607  // not the type of the template argument deduced from A, against the
6608  // template parameter type.
6609  Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6610  << Arg->getType()
6611  << ParamType.getUnqualifiedType();
6612  NoteTemplateParameterLocation(*Param);
6613  return ExprError();
6614  }
6615 
6616  // If either the parameter has a dependent type or the argument is
6617  // type-dependent, there's nothing we can check now.
6618  if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6619  // Force the argument to the type of the parameter to maintain invariants.
6620  auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6621  if (PE)
6622  Arg = PE->getPattern();
6623  ExprResult E = ImpCastExprToType(
6624  Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6625  ParamType->isLValueReferenceType() ? VK_LValue
6626  : ParamType->isRValueReferenceType() ? VK_XValue
6627  : VK_PRValue);
6628  if (E.isInvalid())
6629  return ExprError();
6630  if (PE) {
6631  // Recreate a pack expansion if we unwrapped one.
6632  E = new (Context)
6633  PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6634  PE->getNumExpansions());
6635  }
6636  SugaredConverted = TemplateArgument(E.get());
6637  CanonicalConverted = TemplateArgument(
6638  Context.getCanonicalTemplateArgument(SugaredConverted));
6639  return E;
6640  }
6641 
6642  QualType CanonParamType = Context.getCanonicalType(ParamType);
6643  // Avoid making a copy when initializing a template parameter of class type
6644  // from a template parameter object of the same type. This is going beyond
6645  // the standard, but is required for soundness: in
6646  // template<A a> struct X { X *p; X<a> *q; };
6647  // ... we need p and q to have the same type.
6648  //
6649  // Similarly, don't inject a call to a copy constructor when initializing
6650  // from a template parameter of the same type.
6651  Expr *InnerArg = Arg->IgnoreParenImpCasts();
6652  if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
6653  Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
6654  NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
6655  if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
6656 
6657  SugaredConverted = TemplateArgument(TPO, ParamType);
6658  CanonicalConverted =
6659  TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
6660  return Arg;
6661  }
6662  if (isa<NonTypeTemplateParmDecl>(ND)) {
6663  SugaredConverted = TemplateArgument(Arg);
6664  CanonicalConverted =
6665  Context.getCanonicalTemplateArgument(SugaredConverted);
6666  return Arg;
6667  }
6668  }
6669 
6670  // The initialization of the parameter from the argument is
6671  // a constant-evaluated context.
6672  EnterExpressionEvaluationContext ConstantEvaluated(
6674 
6675  bool IsConvertedConstantExpression = true;
6676  if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) {
6678  Arg->getBeginLoc(), /*DirectInit=*/false, Arg);
6679  Expr *Inits[1] = {Arg};
6680  InitializedEntity Entity =
6682  InitializationSequence InitSeq(*this, Entity, Kind, Inits);
6683  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
6684  if (Result.isInvalid() || !Result.get())
6685  return ExprError();
6686  Result = ActOnConstantExpression(Result.get());
6687  if (Result.isInvalid() || !Result.get())
6688  return ExprError();
6689  Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
6690  /*DiscardedValue=*/false,
6691  /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
6692  .get();
6693  IsConvertedConstantExpression = false;
6694  }
6695 
6696  if (getLangOpts().CPlusPlus17) {
6697  // C++17 [temp.arg.nontype]p1:
6698  // A template-argument for a non-type template parameter shall be
6699  // a converted constant expression of the type of the template-parameter.
6700  APValue Value;
6701  ExprResult ArgResult;
6702  if (IsConvertedConstantExpression) {
6703  ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
6704  CCEK_TemplateArg, Param);
6705  if (ArgResult.isInvalid())
6706  return ExprError();
6707  } else {
6708  ArgResult = Arg;
6709  }
6710 
6711  // For a value-dependent argument, CheckConvertedConstantExpression is
6712  // permitted (and expected) to be unable to determine a value.
6713  if (ArgResult.get()->isValueDependent()) {
6714  SugaredConverted = TemplateArgument(ArgResult.get());
6715  CanonicalConverted =
6716  Context.getCanonicalTemplateArgument(SugaredConverted);
6717  return ArgResult;
6718  }
6719 
6720  APValue PreNarrowingValue;
6721  ArgResult = EvaluateConvertedConstantExpression(
6722  ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/
6723  false, PreNarrowingValue);
6724  if (ArgResult.isInvalid())
6725  return ExprError();
6726 
6727  if (Value.isLValue()) {
6728  APValue::LValueBase Base = Value.getLValueBase();
6729  auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6730  // For a non-type template-parameter of pointer or reference type,
6731  // the value of the constant expression shall not refer to
6732  assert(ParamType->isPointerOrReferenceType() ||
6733  ParamType->isNullPtrType());
6734  // -- a temporary object
6735  // -- a string literal
6736  // -- the result of a typeid expression, or
6737  // -- a predefined __func__ variable
6738  if (Base &&
6739  (!VD ||
6740  isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
6741  Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6742  << Arg->getSourceRange();
6743  return ExprError();
6744  }
6745 
6746  if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
6747  VD->getType()->isArrayType() &&
6748  Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
6749  !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6750  SugaredConverted = TemplateArgument(VD, ParamType);
6751  CanonicalConverted = TemplateArgument(
6752  cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType);
6753  return ArgResult.get();
6754  }
6755 
6756  // -- a subobject [until C++20]
6757  if (!getLangOpts().CPlusPlus20) {
6758  if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6759  Value.isLValueOnePastTheEnd()) {
6760  Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6761  << Value.getAsString(Context, ParamType);
6762  return ExprError();
6763  }
6764  assert((VD || !ParamType->isReferenceType()) &&
6765  "null reference should not be a constant expression");
6766  assert((!VD || !ParamType->isNullPtrType()) &&
6767  "non-null value of type nullptr_t?");
6768  }
6769  }
6770 
6771  if (Value.isAddrLabelDiff())
6772  return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6773 
6774  SugaredConverted = TemplateArgument(Context, ParamType, Value);
6775  CanonicalConverted = TemplateArgument(Context, CanonParamType, Value);
6776  return ArgResult.get();
6777  }
6778 
6779  // C++ [temp.arg.nontype]p5:
6780  // The following conversions are performed on each expression used
6781  // as a non-type template-argument. If a non-type
6782  // template-argument cannot be converted to the type of the
6783  // corresponding template-parameter then the program is
6784  // ill-formed.
6785  if (ParamType->isIntegralOrEnumerationType()) {
6786  // C++11:
6787  // -- for a non-type template-parameter of integral or
6788  // enumeration type, conversions permitted in a converted
6789  // constant expression are applied.
6790  //
6791  // C++98:
6792  // -- for a non-type template-parameter of integral or
6793  // enumeration type, integral promotions (4.5) and integral
6794  // conversions (4.7) are applied.
6795 
6796  if (getLangOpts().CPlusPlus11) {
6797  // C++ [temp.arg.nontype]p1:
6798  // A template-argument for a non-type, non-template template-parameter
6799  // shall be one of:
6800  //
6801  // -- for a non-type template-parameter of integral or enumeration
6802  // type, a converted constant expression of the type of the
6803  // template-parameter; or
6805  ExprResult ArgResult =
6806  CheckConvertedConstantExpression(Arg, ParamType, Value,
6807  CCEK_TemplateArg);
6808  if (ArgResult.isInvalid())
6809  return ExprError();
6810 
6811  // We can't check arbitrary value-dependent arguments.
6812  if (ArgResult.get()->isValueDependent()) {
6813  SugaredConverted = TemplateArgument(ArgResult.get());
6814  CanonicalConverted =
6815  Context.getCanonicalTemplateArgument(SugaredConverted);
6816  return ArgResult;
6817  }
6818 
6819  // Widen the argument value to sizeof(parameter type). This is almost
6820  // always a no-op, except when the parameter type is bool. In
6821  // that case, this may extend the argument from 1 bit to 8 bits.
6822  QualType IntegerType = ParamType;
6823  if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6824  IntegerType = Enum->getDecl()->getIntegerType();
6825  Value = Value.extOrTrunc(IntegerType->isBitIntType()
6826  ? Context.getIntWidth(IntegerType)
6827  : Context.getTypeSize(IntegerType));
6828 
6829  SugaredConverted = TemplateArgument(Context, Value, ParamType);
6830  CanonicalConverted =
6831  TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
6832  return ArgResult;
6833  }
6834 
6835  ExprResult ArgResult = DefaultLvalueConversion(Arg);
6836  if (ArgResult.isInvalid())
6837  return ExprError();
6838  Arg = ArgResult.get();
6839 
6840  QualType ArgType = Arg->getType();
6841 
6842  // C++ [temp.arg.nontype]p1:
6843  // A template-argument for a non-type, non-template
6844  // template-parameter shall be one of:
6845  //
6846  // -- an integral constant-expression of integral or enumeration
6847  // type; or
6848  // -- the name of a non-type template-parameter; or
6850  if (!ArgType->isIntegralOrEnumerationType()) {
6851  Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6852  << ArgType << Arg->getSourceRange();
6853  NoteTemplateParameterLocation(*Param);
6854  return ExprError();
6855  } else if (!Arg->isValueDependent()) {
6856  class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6857  QualType T;
6858 
6859  public:
6860  TmplArgICEDiagnoser(QualType T) : T(T) { }
6861 
6862  SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
6863  SourceLocation Loc) override {
6864  return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
6865  }
6866  } Diagnoser(ArgType);
6867 
6868  Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
6869  if (!Arg)
6870  return ExprError();
6871  }
6872 
6873  // From here on out, all we care about is the unqualified form
6874  // of the argument type.
6875  ArgType = ArgType.getUnqualifiedType();
6876 
6877  // Try to convert the argument to the parameter's type.
6878  if (Context.hasSameType(ParamType, ArgType)) {
6879  // Okay: no conversion necessary
6880  } else if (ParamType->isBooleanType()) {
6881  // This is an integral-to-boolean conversion.
6882  Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6883  } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6884  !ParamType->isEnumeralType()) {
6885  // This is an integral promotion or conversion.
6886  Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6887  } else {
6888  // We can't perform this conversion.
6889  Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6890  << Arg->getType() << ParamType << Arg->getSourceRange();
6891  NoteTemplateParameterLocation(*Param);
6892  return ExprError();
6893  }
6894 
6895  // Add the value of this argument to the list of converted
6896  // arguments. We use the bitwidth and signedness of the template
6897  // parameter.
6898  if (Arg->isValueDependent()) {
6899  // The argument is value-dependent. Create a new
6900  // TemplateArgument with the converted expression.
6901  SugaredConverted = TemplateArgument(Arg);
6902  CanonicalConverted =
6903  Context.getCanonicalTemplateArgument(SugaredConverted);
6904  return Arg;
6905  }
6906 
6907  QualType IntegerType = ParamType;
6908  if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
6909  IntegerType = Enum->getDecl()->getIntegerType();
6910  }
6911 
6912  if (ParamType->isBooleanType()) {
6913  // Value must be zero or one.
6914  Value = Value != 0;
6915  unsigned AllowedBits = Context.getTypeSize(IntegerType);
6916  if (Value.getBitWidth() != AllowedBits)
6917  Value = Value.extOrTrunc(AllowedBits);
6918  Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6919  } else {
6920  llvm::APSInt OldValue = Value;
6921 
6922  // Coerce the template argument's value to the value it will have
6923  // based on the template parameter's type.
6924  unsigned AllowedBits = IntegerType->isBitIntType()
6925  ? Context.getIntWidth(IntegerType)
6926  : Context.getTypeSize(IntegerType);
6927  if (Value.getBitWidth() != AllowedBits)
6928  Value = Value.extOrTrunc(AllowedBits);
6929  Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6930 
6931  // Complain if an unsigned parameter received a negative value.
6932  if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
6933  (OldValue.isSigned() && OldValue.isNegative())) {
6934  Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6935  << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
6936  << Arg->getSourceRange();
6937  NoteTemplateParameterLocation(*Param);
6938  }
6939 
6940  // Complain if we overflowed the template parameter's type.
6941  unsigned RequiredBits;
6942  if (IntegerType->isUnsignedIntegerOrEnumerationType())
6943  RequiredBits = OldValue.getActiveBits();
6944  else if (OldValue.isUnsigned())
6945  RequiredBits = OldValue.getActiveBits() + 1;
6946  else
6947  RequiredBits = OldValue.getSignificantBits();
6948  if (RequiredBits > AllowedBits) {
6949  Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6950  << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
6951  << Arg->getSourceRange();
6952  NoteTemplateParameterLocation(*Param);
6953  }
6954  }
6955 
6956  QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
6957  SugaredConverted = TemplateArgument(Context, Value, T);
6958  CanonicalConverted =
6959  TemplateArgument(Context, Value, Context.getCanonicalType(T));
6960  return Arg;
6961  }
6962 
6963  QualType ArgType = Arg->getType();
6964  DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6965 
6966  // Handle pointer-to-function, reference-to-function, and
6967  // pointer-to-member-function all in (roughly) the same way.
6968  if (// -- For a non-type template-parameter of type pointer to
6969  // function, only the function-to-pointer conversion (4.3) is
6970  // applied. If the template-argument represents a set of
6971  // overloaded functions (or a pointer to such), the matching
6972  // function is selected from the set (13.4).
6973  (ParamType->isPointerType() &&
6974  ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6975  // -- For a non-type template-parameter of type reference to
6976  // function, no conversions apply. If the template-argument
6977  // represents a set of overloaded functions, the matching
6978  // function is selected from the set (13.4).
6979  (ParamType->isReferenceType() &&
6980  ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6981  // -- For a non-type template-parameter of type pointer to
6982  // member function, no conversions apply. If the
6983  // template-argument represents a set of overloaded member
6984  // functions, the matching member function is selected from
6985  // the set (13.4).
6986  (ParamType->isMemberPointerType() &&
6987  ParamType->castAs<MemberPointerType>()->getPointeeType()
6988  ->isFunctionType())) {
6989 
6990  if (Arg->getType() == Context.OverloadTy) {
6991  if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6992  true,
6993  FoundResult)) {
6994  if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
6995  return ExprError();
6996 
6997  ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6998  if (Res.isInvalid())
6999  return ExprError();
7000  Arg = Res.get();
7001  ArgType = Arg->getType();
7002  } else
7003  return ExprError();
7004  }
7005 
7006  if (!ParamType->isMemberPointerType()) {
7008  *this, Param, ParamType, Arg, SugaredConverted,
7009  CanonicalConverted))
7010  return ExprError();
7011  return Arg;
7012  }
7013 
7015  *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7016  return ExprError();
7017  return Arg;
7018  }
7019 
7020  if (ParamType->isPointerType()) {
7021  // -- for a non-type template-parameter of type pointer to
7022  // object, qualification conversions (4.4) and the
7023  // array-to-pointer conversion (4.2) are applied.
7024  // C++0x also allows a value of std::nullptr_t.
7025  assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7026  "Only object pointers allowed here");
7027 
7029  *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7030  return ExprError();
7031  return Arg;
7032  }
7033 
7034  if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7035  // -- For a non-type template-parameter of type reference to
7036  // object, no conversions apply. The type referred to by the
7037  // reference may be more cv-qualified than the (otherwise
7038  // identical) type of the template-argument. The
7039  // template-parameter is bound directly to the
7040  // template-argument, which must be an lvalue.
7041  assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7042  "Only object references allowed here");
7043 
7044  if (Arg->getType() == Context.OverloadTy) {
7045  if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
7046  ParamRefType->getPointeeType(),
7047  true,
7048  FoundResult)) {
7049  if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7050  return ExprError();
7051  ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7052  if (Res.isInvalid())
7053  return ExprError();
7054  Arg = Res.get();
7055  ArgType = Arg->getType();
7056  } else
7057  return ExprError();
7058  }
7059 
7061  *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7062  return ExprError();
7063  return Arg;
7064  }
7065 
7066  // Deal with parameters of type std::nullptr_t.
7067  if (ParamType->isNullPtrType()) {
7068  if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7069  SugaredConverted = TemplateArgument(Arg);
7070  CanonicalConverted =
7071  Context.getCanonicalTemplateArgument(SugaredConverted);
7072  return Arg;
7073  }
7074 
7075  switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7076  case NPV_NotNullPointer:
7077  Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7078  << Arg->getType() << ParamType;
7079  NoteTemplateParameterLocation(*Param);
7080  return ExprError();
7081 
7082  case NPV_Error:
7083  return ExprError();
7084 
7085  case NPV_NullPointer:
7086  Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7087  SugaredConverted = TemplateArgument(ParamType,
7088  /*isNullPtr=*/true);
7089  CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7090  /*isNullPtr=*/true);
7091  return Arg;
7092  }
7093  }
7094 
7095  // -- For a non-type template-parameter of type pointer to data
7096  // member, qualification conversions (4.4) are applied.
7097  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7098 
7100  *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7101  return ExprError();
7102  return Arg;
7103 }
7104 
7108 
7110  TemplateParameterList *Params,
7111  TemplateArgumentLoc &Arg,
7112  bool IsDeduced) {
7114  TemplateDecl *Template = Name.getAsTemplateDecl();
7115  if (!Template) {
7116  // Any dependent template name is fine.
7117  assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7118  return false;
7119  }
7120 
7121  if (Template->isInvalidDecl())
7122  return true;
7123 
7124  // C++0x [temp.arg.template]p1:
7125  // A template-argument for a template template-parameter shall be
7126  // the name of a class template or an alias template, expressed as an
7127  // id-expression. When the template-argument names a class template, only
7128  // primary class templates are considered when matching the
7129  // template template argument with the corresponding parameter;
7130  // partial specializations are not considered even if their
7131  // parameter lists match that of the template template parameter.
7132  //
7133  // Note that we also allow template template parameters here, which
7134  // will happen when we are dealing with, e.g., class template
7135  // partial specializations.
7136  if (!isa<ClassTemplateDecl>(Template) &&
7137  !isa<TemplateTemplateParmDecl>(Template) &&
7138  !isa<TypeAliasTemplateDecl>(Template) &&
7139  !isa<BuiltinTemplateDecl>(Template)) {
7140  assert(isa<FunctionTemplateDecl>(Template) &&
7141  "Only function templates are possible here");
7142  Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7143  Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7144  << Template;
7145  }
7146 
7147  // C++1z [temp.arg.template]p3: (DR 150)
7148  // A template-argument matches a template template-parameter P when P
7149  // is at least as specialized as the template-argument A.
7150  if (getLangOpts().RelaxedTemplateTemplateArgs) {
7151  // Quick check for the common case:
7152  // If P contains a parameter pack, then A [...] matches P if each of A's
7153  // template parameters matches the corresponding template parameter in
7154  // the template-parameter-list of P.
7155  if (TemplateParameterListsAreEqual(
7156  Template->getTemplateParameters(), Params, false,
7157  TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) &&
7158  // If the argument has no associated constraints, then the parameter is
7159  // definitely at least as specialized as the argument.
7160  // Otherwise - we need a more thorough check.
7161  !Template->hasAssociatedConstraints())
7162  return false;
7163 
7164  if (isTemplateTemplateParameterAtLeastAsSpecializedAs(
7165  Params, Template, Arg.getLocation(), IsDeduced)) {
7166  // P2113
7167  // C++20[temp.func.order]p2
7168  // [...] If both deductions succeed, the partial ordering selects the
7169  // more constrained template (if one exists) as determined below.
7170  SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7171  Params->getAssociatedConstraints(ParamsAC);
7172  // C++2a[temp.arg.template]p3
7173  // [...] In this comparison, if P is unconstrained, the constraints on A
7174  // are not considered.
7175  if (ParamsAC.empty())
7176  return false;
7177 
7178  Template->getAssociatedConstraints(TemplateAC);
7179 
7180  bool IsParamAtLeastAsConstrained;
7181  if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7182  IsParamAtLeastAsConstrained))
7183  return true;
7184  if (!IsParamAtLeastAsConstrained) {
7185  Diag(Arg.getLocation(),
7186  diag::err_template_template_parameter_not_at_least_as_constrained)
7187  << Template << Param << Arg.getSourceRange();
7188  Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7189  Diag(Template->getLocation(), diag::note_entity_declared_at)
7190  << Template;
7191  MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7192  TemplateAC);
7193  return true;
7194  }
7195  return false;
7196  }
7197  // FIXME: Produce better diagnostics for deduction failures.
7198  }
7199 
7200  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
7201  Params,
7202  true,
7203  TPL_TemplateTemplateArgumentMatch,
7204  Arg.getLocation());
7205 }
7206 
7207 static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7208  unsigned HereDiagID,
7209  unsigned ExternalDiagID) {
7210  if (Decl.getLocation().isValid())
7211  return S.Diag(Decl.getLocation(), HereDiagID);
7212 
7213  SmallString<128> Str;
7214  llvm::raw_svector_ostream Out(Str);
7216  PP.TerseOutput = 1;
7217  Decl.print(Out, PP);
7218  return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7219 }
7220 
7222  std::optional<SourceRange> ParamRange) {
7224  noteLocation(*this, Decl, diag::note_template_decl_here,
7225  diag::note_template_decl_external);
7226  if (ParamRange && ParamRange->isValid()) {
7227  assert(Decl.getLocation().isValid() &&
7228  "Parameter range has location when Decl does not");
7229  DB << *ParamRange;
7230  }
7231 }
7232 
7234  noteLocation(*this, Decl, diag::note_template_param_here,
7235  diag::note_template_param_external);
7236 }
7237 
7239  const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7240  NamedDecl *TemplateParam) {
7241  // C++ [temp.param]p8:
7242  //
7243  // A non-type template-parameter of type "array of T" or
7244  // "function returning T" is adjusted to be of type "pointer to
7245  // T" or "pointer to function returning T", respectively.
7246  if (ParamType->isArrayType())
7247  ParamType = Context.getArrayDecayedType(ParamType);
7248  else if (ParamType->isFunctionType())
7249  ParamType = Context.getPointerType(ParamType);
7250 
7251  // For a NULL non-type template argument, return nullptr casted to the
7252  // parameter's type.
7253  if (Arg.getKind() == TemplateArgument::NullPtr) {
7254  return ImpCastExprToType(
7255  new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7256  ParamType,
7257  ParamType->getAs<MemberPointerType>()
7258  ? CK_NullToMemberPointer
7259  : CK_NullToPointer);
7260  }
7261  assert(Arg.getKind() == TemplateArgument::Declaration &&
7262  "Only declaration template arguments permitted here");
7263 
7264  ValueDecl *VD = Arg.getAsDecl();
7265 
7266  CXXScopeSpec SS;
7267  if (ParamType->isMemberPointerType()) {
7268  // If this is a pointer to member, we need to use a qualified name to
7269  // form a suitable pointer-to-member constant.
7270  assert(VD->getDeclContext()->isRecord() &&
7271  (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7272  isa<IndirectFieldDecl>(VD)));
7273  QualType ClassType
7274  = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
7275  NestedNameSpecifier *Qualifier
7276  = NestedNameSpecifier::Create(Context, nullptr, false,
7277  ClassType.getTypePtr());
7278  SS.MakeTrivial(Context, Qualifier, Loc);
7279  }
7280 
7281  ExprResult RefExpr = BuildDeclarationNameExpr(
7282  SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7283  if (RefExpr.isInvalid())
7284  return ExprError();
7285 
7286  // For a pointer, the argument declaration is the pointee. Take its address.
7287  QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7288  if (ParamType->isPointerType() && !ElemT.isNull() &&
7289  Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7290  // Decay an array argument if we want a pointer to its first element.
7291  RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7292  if (RefExpr.isInvalid())
7293  return ExprError();
7294  } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7295  // For any other pointer, take the address (or form a pointer-to-member).
7296  RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7297  if (RefExpr.isInvalid())
7298  return ExprError();
7299  } else if (ParamType->isRecordType()) {
7300  assert(isa<TemplateParamObjectDecl>(VD) &&
7301  "arg for class template param not a template parameter object");
7302  // No conversions apply in this case.
7303  return RefExpr;
7304  } else {
7305  assert(ParamType->isReferenceType() &&
7306  "unexpected type for decl template argument");
7307  if (NonTypeTemplateParmDecl *NTTP =
7308  dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7309  QualType TemplateParamType = NTTP->getType();
7310  const AutoType *AT = TemplateParamType->getAs<AutoType>();
7311  if (AT && AT->isDecltypeAuto()) {
7312  RefExpr = new (getASTContext()) SubstNonTypeTemplateParmExpr(
7313  ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7314  RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7315  /*PackIndex=*/std::nullopt,
7316  /*RefParam=*/true);
7317  }
7318  }
7319  }
7320 
7321  // At this point we should have the right value category.
7322  assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7323  "value kind mismatch for non-type template argument");
7324 
7325  // The type of the template parameter can differ from the type of the
7326  // argument in various ways; convert it now if necessary.
7327  QualType DestExprType = ParamType.getNonLValueExprType(Context);
7328  if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7329  CastKind CK;
7330  QualType Ignored;
7331  if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7332  IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7333  CK = CK_NoOp;
7334  } else if (ParamType->isVoidPointerType() &&
7335  RefExpr.get()->getType()->isPointerType()) {
7336  CK = CK_BitCast;
7337  } else {
7338  // FIXME: Pointers to members can need conversion derived-to-base or
7339  // base-to-derived conversions. We currently don't retain enough
7340  // information to convert properly (we need to track a cast path or
7341  // subobject number in the template argument).
7342  llvm_unreachable(
7343  "unexpected conversion required for non-type template argument");
7344  }
7345  RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7346  RefExpr.get()->getValueKind());
7347  }
7348 
7349  return RefExpr;
7350 }
7351 
7352 /// Construct a new expression that refers to the given
7353 /// integral template argument with the given source-location
7354 /// information.
7355 ///
7356 /// This routine takes care of the mapping from an integral template
7357 /// argument (which may have any integral type) to the appropriate
7358 /// literal value.
7360  Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
7361  assert(OrigT->isIntegralOrEnumerationType());
7362 
7363  // If this is an enum type that we're instantiating, we need to use an integer
7364  // type the same size as the enumerator. We don't want to build an
7365  // IntegerLiteral with enum type. The integer type of an enum type can be of
7366  // any integral type with C++11 enum classes, make sure we create the right
7367  // type of literal for it.
7368  QualType T = OrigT;
7369  if (const EnumType *ET = OrigT->getAs<EnumType>())
7370  T = ET->getDecl()->getIntegerType();
7371 
7372  Expr *E;
7373  if (T->isAnyCharacterType()) {
7375  if (T->isWideCharType())
7377  else if (T->isChar8Type() && S.getLangOpts().Char8)
7379  else if (T->isChar16Type())
7381  else if (T->isChar32Type())
7383  else
7385 
7386  E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
7387  } else if (T->isBooleanType()) {
7388  E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
7389  } else {
7390  E = IntegerLiteral::Create(S.Context, Int, T, Loc);
7391  }
7392 
7393  if (OrigT->isEnumeralType()) {
7394  // FIXME: This is a hack. We need a better way to handle substituted
7395  // non-type template parameters.
7396  E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
7397  nullptr, S.CurFPFeatureOverrides(),
7399  Loc, Loc);
7400  }
7401 
7402  return E;
7403 }
7404 
7406  Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
7407  auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
7408  auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
7409  ILE->setType(T);
7410  return ILE;
7411  };
7412 
7413  switch (Val.getKind()) {
7415  // This cannot occur in a template argument at all.
7416  case APValue::Array:
7417  case APValue::Struct:
7418  case APValue::Union:
7419  // These can only occur within a template parameter object, which is
7420  // represented as a TemplateArgument::Declaration.
7421  llvm_unreachable("unexpected template argument value");
7422 
7423  case APValue::Int:
7425  Loc);
7426 
7427  case APValue::Float:
7428  return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
7429  T, Loc);
7430 
7431  case APValue::FixedPoint:
7433  S.Context, Val.getFixedPoint().getValue(), T, Loc,
7434  Val.getFixedPoint().getScale());
7435 
7436  case APValue::ComplexInt: {
7437  QualType ElemT = T->castAs<ComplexType>()->getElementType();
7439  S, ElemT, Val.getComplexIntReal(), Loc),
7441  S, ElemT, Val.getComplexIntImag(), Loc)});
7442  }
7443 
7444  case APValue::ComplexFloat: {
7445  QualType ElemT = T->castAs<ComplexType>()->getElementType();
7446  return MakeInitList(
7448  ElemT, Loc),
7450  ElemT, Loc)});
7451  }
7452 
7453  case APValue::Vector: {
7454  QualType ElemT = T->castAs<VectorType>()->getElementType();
7456  for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
7458  S, ElemT, Val.getVectorElt(I), Loc));
7459  return MakeInitList(Elts);
7460  }
7461 
7462  case APValue::None:
7464  llvm_unreachable("Unexpected APValue kind.");
7465  case APValue::LValue:
7467  // There isn't necessarily a valid equivalent source-level syntax for
7468  // these; in particular, a naive lowering might violate access control.
7469  // So for now we lower to a ConstantExpr holding the value, wrapped around
7470  // an OpaqueValueExpr.
7471  // FIXME: We should have a better representation for this.
7473  if (T->isReferenceType()) {
7474  T = T->getPointeeType();
7475  VK = VK_LValue;
7476  }
7477  auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
7478  return ConstantExpr::Create(S.Context, OVE, Val);
7479  }
7480  llvm_unreachable("Unhandled APValue::ValueKind enum");
7481 }
7482 
7483 ExprResult
7485  SourceLocation Loc) {
7486  switch (Arg.getKind()) {
7492  llvm_unreachable("not a non-type template argument");
7493 
7495  return Arg.getAsExpr();
7496 
7499  return BuildExpressionFromDeclTemplateArgument(
7500  Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
7501 
7504  *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
7505 
7508  *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
7509  }
7510  llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
7511 }
7512 
7513 /// Match two template parameters within template parameter lists.
7515  Sema &S, NamedDecl *New,
7516  const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
7517  const NamedDecl *OldInstFrom, bool Complain,
7519  // Check the actual kind (type, non-type, template).
7520  if (Old->getKind() != New->getKind()) {
7521  if (Complain) {
7522  unsigned NextDiag = diag::err_template_param_different_kind;
7523  if (TemplateArgLoc.isValid()) {
7524  S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7525  NextDiag = diag::note_template_param_different_kind;
7526  }
7527  S.Diag(New->getLocation(), NextDiag)
7528  << (Kind != Sema::TPL_TemplateMatch);
7529  S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7530  << (Kind != Sema::TPL_TemplateMatch);
7531  }
7532 
7533  return false;
7534  }
7535 
7536  // Check that both are parameter packs or neither are parameter packs.
7537  // However, if we are matching a template template argument to a
7538  // template template parameter, the template template parameter can have
7539  // a parameter pack where the template template argument does not.
7540  if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7542  Old->isTemplateParameterPack())) {
7543  if (Complain) {
7544  unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7545  if (TemplateArgLoc.isValid()) {
7546  S.Diag(TemplateArgLoc,
7547  diag::err_template_arg_template_params_mismatch);
7548  NextDiag = diag::note_template_parameter_pack_non_pack;
7549  }
7550 
7551  unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7552  : isa<NonTypeTemplateParmDecl>(New)? 1
7553  : 2;
7554  S.Diag(New->getLocation(), NextDiag)
7555  << ParamKind << New->isParameterPack();
7556  S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7557  << ParamKind << Old->isParameterPack();
7558  }
7559 
7560  return false;
7561  }
7562 
7563  // For non-type template parameters, check the type of the parameter.
7564  if (NonTypeTemplateParmDecl *OldNTTP
7565  = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7566  NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7567 
7568  // If we are matching a template template argument to a template
7569  // template parameter and one of the non-type template parameter types
7570  // is dependent, then we must wait until template instantiation time
7571  // to actually compare the arguments.
7573  (!OldNTTP->getType()->isDependentType() &&
7574  !NewNTTP->getType()->isDependentType())) {
7575  // C++20 [temp.over.link]p6:
7576  // Two [non-type] template-parameters are equivalent [if] they have
7577  // equivalent types ignoring the use of type-constraints for
7578  // placeholder types
7579  QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
7580  QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
7581  if (!S.Context.hasSameType(OldType, NewType)) {
7582  if (Complain) {
7583  unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7584  if (TemplateArgLoc.isValid()) {
7585  S.Diag(TemplateArgLoc,
7586  diag::err_template_arg_template_params_mismatch);
7587  NextDiag = diag::note_template_nontype_parm_different_type;
7588  }
7589  S.Diag(NewNTTP->getLocation(), NextDiag)
7590  << NewNTTP->getType()
7591  << (Kind != Sema::TPL_TemplateMatch);
7592  S.Diag(OldNTTP->getLocation(),
7593  diag::note_template_nontype_parm_prev_declaration)
7594  << OldNTTP->getType();
7595  }
7596 
7597  return false;
7598  }
7599  }
7600  }
7601  // For template template parameters, check the template parameter types.
7602  // The template parameter lists of template template
7603  // parameters must agree.
7604  else if (TemplateTemplateParmDecl *OldTTP =
7605  dyn_cast<TemplateTemplateParmDecl>(Old)) {
7606  TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7608  NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
7609  OldTTP->getTemplateParameters(), Complain,
7612  : Kind),
7613  TemplateArgLoc))
7614  return false;
7615  }
7616 
7619  !isa<TemplateTemplateParmDecl>(Old)) {
7620  const Expr *NewC = nullptr, *OldC = nullptr;
7621 
7622  if (isa<TemplateTypeParmDecl>(New)) {
7623  if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
7624  NewC = TC->getImmediatelyDeclaredConstraint();
7625  if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
7626  OldC = TC->getImmediatelyDeclaredConstraint();
7627  } else if (isa<NonTypeTemplateParmDecl>(New)) {
7628  if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
7629  ->getPlaceholderTypeConstraint())
7630  NewC = E;
7631  if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
7632  ->getPlaceholderTypeConstraint())
7633  OldC = E;
7634  } else
7635  llvm_unreachable("unexpected template parameter type");
7636 
7637  auto Diagnose = [&] {
7638  S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
7639  diag::err_template_different_type_constraint);
7640  S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
7641  diag::note_template_prev_declaration) << /*declaration*/0;
7642  };
7643 
7644  if (!NewC != !OldC) {
7645  if (Complain)
7646  Diagnose();
7647  return false;
7648  }
7649 
7650  if (NewC) {
7651  if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
7652  NewC)) {
7653  if (Complain)
7654  Diagnose();
7655  return false;
7656  }
7657  }
7658  }
7659 
7660  return true;
7661 }
7662 
7663 /// Diagnose a known arity mismatch when comparing template argument
7664 /// lists.
7665 static
7667  TemplateParameterList *New,
7668  TemplateParameterList *Old,
7670  SourceLocation TemplateArgLoc) {
7671  unsigned NextDiag = diag::err_template_param_list_different_arity;
7672  if (TemplateArgLoc.isValid()) {
7673  S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7674  NextDiag = diag::note_template_param_list_different_arity;
7675  }
7676  S.Diag(New->getTemplateLoc(), NextDiag)
7677  << (New->size() > Old->size())
7679  << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7680  S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7682  << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7683 }
7684 
7686  const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
7687  const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
7689  if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7690  if (Complain)
7692  TemplateArgLoc);
7693 
7694  return false;
7695  }
7696 
7697  // C++0x [temp.arg.template]p3:
7698  // A template-argument matches a template template-parameter (call it P)
7699  // when each of the template parameters in the template-parameter-list of
7700  // the template-argument's corresponding class template or alias template
7701  // (call it A) matches the corresponding template parameter in the
7702  // template-parameter-list of P. [...]
7703  TemplateParameterList::iterator NewParm = New->begin();
7704  TemplateParameterList::iterator NewParmEnd = New->end();
7705  for (TemplateParameterList::iterator OldParm = Old->begin(),
7706  OldParmEnd = Old->end();
7707  OldParm != OldParmEnd; ++OldParm) {
7708  if (Kind != TPL_TemplateTemplateArgumentMatch ||
7709  !(*OldParm)->isTemplateParameterPack()) {
7710  if (NewParm == NewParmEnd) {
7711  if (Complain)
7713  TemplateArgLoc);
7714 
7715  return false;
7716  }
7717 
7718  if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7719  OldInstFrom, Complain, Kind,
7720  TemplateArgLoc))
7721  return false;
7722 
7723  ++NewParm;
7724  continue;
7725  }
7726 
7727  // C++0x [temp.arg.template]p3:
7728  // [...] When P's template- parameter-list contains a template parameter
7729  // pack (14.5.3), the template parameter pack will match zero or more
7730  // template parameters or template parameter packs in the
7731  // template-parameter-list of A with the same type and form as the
7732  // template parameter pack in P (ignoring whether those template
7733  // parameters are template parameter packs).
7734  for (; NewParm != NewParmEnd; ++NewParm) {
7735  if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7736  OldInstFrom, Complain, Kind,
7737  TemplateArgLoc))
7738  return false;
7739  }
7740  }
7741 
7742  // Make sure we exhausted all of the arguments.
7743  if (NewParm != NewParmEnd) {
7744  if (Complain)
7746  TemplateArgLoc);
7747 
7748  return false;
7749  }
7750 
7751  if (Kind != TPL_TemplateTemplateArgumentMatch &&
7752  Kind != TPL_TemplateParamsEquivalent) {
7753  const Expr *NewRC = New->getRequiresClause();
7754  const Expr *OldRC = Old->getRequiresClause();
7755 
7756  auto Diagnose = [&] {
7757  Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
7758  diag::err_template_different_requires_clause);
7759  Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
7760  diag::note_template_prev_declaration) << /*declaration*/0;
7761  };
7762 
7763  if (!NewRC != !OldRC) {
7764  if (Complain)
7765  Diagnose();
7766  return false;
7767  }
7768 
7769  if (NewRC) {
7770  if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
7771  NewRC)) {
7772  if (Complain)
7773  Diagnose();
7774  return false;
7775  }
7776  }
7777  }
7778 
7779  return true;
7780 }
7781 
7782 bool
7784  if (!S)
7785  return false;
7786 
7787  // Find the nearest enclosing declaration scope.
7788  S = S->getDeclParent();
7789 
7790  // C++ [temp.pre]p6: [P2096]
7791  // A template, explicit specialization, or partial specialization shall not
7792  // have C linkage.
7793  DeclContext *Ctx = S->getEntity();
7794  if (Ctx && Ctx->isExternCContext()) {
7795  Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7796  << TemplateParams->getSourceRange();
7797  if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7798  Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7799  return true;
7800  }
7801  Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
7802 
7803  // C++ [temp]p2:
7804  // A template-declaration can appear only as a namespace scope or
7805  // class scope declaration.
7806  // C++ [temp.expl.spec]p3:
7807  // An explicit specialization may be declared in any scope in which the
7808  // corresponding primary template may be defined.
7809  // C++ [temp.class.spec]p6: [P2096]
7810  // A partial specialization may be declared in any scope in which the
7811  // corresponding primary template may be defined.
7812  if (Ctx) {
7813  if (Ctx->isFileContext())
7814  return false;
7815  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7816  // C++ [temp.mem]p2:
7817  // A local class shall not have member templates.
7818  if (RD->isLocalClass())
7819  return Diag(TemplateParams->getTemplateLoc(),
7820  diag::err_template_inside_local_class)
7821  << TemplateParams->getSourceRange();
7822  else
7823  return false;
7824  }
7825  }
7826 
7827  return Diag(TemplateParams->getTemplateLoc(),
7828  diag::err_template_outside_namespace_or_class_scope)
7829  << TemplateParams->getSourceRange();
7830 }
7831 
7832 /// Determine what kind of template specialization the given declaration
7833 /// is.
7835  if (!D)
7836  return TSK_Undeclared;
7837 
7838  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7839  return Record->getTemplateSpecializationKind();
7840  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7841  return Function->getTemplateSpecializationKind();
7842  if (VarDecl *Var = dyn_cast<VarDecl>(D))
7843  return Var->getTemplateSpecializationKind();
7844 
7845  return TSK_Undeclared;
7846 }
7847 
7848 /// Check whether a specialization is well-formed in the current
7849 /// context.
7850 ///
7851 /// This routine determines whether a template specialization can be declared
7852 /// in the current context (C++ [temp.expl.spec]p2).
7853 ///
7854 /// \param S the semantic analysis object for which this check is being
7855 /// performed.
7856 ///
7857 /// \param Specialized the entity being specialized or instantiated, which
7858 /// may be a kind of template (class template, function template, etc.) or
7859 /// a member of a class template (member function, static data member,
7860 /// member class).
7861 ///
7862 /// \param PrevDecl the previous declaration of this entity, if any.
7863 ///
7864 /// \param Loc the location of the explicit specialization or instantiation of
7865 /// this entity.
7866 ///
7867 /// \param IsPartialSpecialization whether this is a partial specialization of
7868 /// a class template.
7869 ///
7870 /// \returns true if there was an error that we cannot recover from, false
7871 /// otherwise.
7873  NamedDecl *Specialized,
7874  NamedDecl *PrevDecl,
7876  bool IsPartialSpecialization) {
7877  // Keep these "kind" numbers in sync with the %select statements in the
7878  // various diagnostics emitted by this routine.
7879  int EntityKind = 0;
7880  if (isa<ClassTemplateDecl>(Specialized))
7881  EntityKind = IsPartialSpecialization? 1 : 0;
7882  else if (isa<VarTemplateDecl>(Specialized))
7883  EntityKind = IsPartialSpecialization ? 3 : 2;
7884  else if (isa<FunctionTemplateDecl>(Specialized))
7885  EntityKind = 4;
7886  else if (isa<CXXMethodDecl>(Specialized))
7887  EntityKind = 5;
7888  else if (isa<VarDecl>(Specialized))
7889  EntityKind = 6;
7890  else if (isa<RecordDecl>(Specialized))
7891  EntityKind = 7;
7892  else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7893  EntityKind = 8;
7894  else {
7895  S.Diag(Loc, diag::err_template_spec_unknown_kind)
7896  << S.getLangOpts().CPlusPlus11;
7897  S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7898  return true;
7899  }
7900 
7901  // C++ [temp.expl.spec]p2:
7902  // An explicit specialization may be declared in any scope in which
7903  // the corresponding primary template may be defined.
7905  S.Diag(Loc, diag::err_template_spec_decl_function_scope)
7906  << Specialized;
7907  return true;
7908  }
7909 
7910  // C++ [temp.class.spec]p6:
7911  // A class template partial specialization may be declared in any
7912  // scope in which the primary template may be defined.
7913  DeclContext *SpecializedContext =
7914  Specialized->getDeclContext()->getRedeclContext();
7916 
7917  // Make sure that this redeclaration (or definition) occurs in the same
7918  // scope or an enclosing namespace.
7919  if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7920  : DC->Equals(SpecializedContext))) {
7921  if (isa<TranslationUnitDecl>(SpecializedContext))
7922  S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7923  << EntityKind << Specialized;
7924  else {
7925  auto *ND = cast<NamedDecl>(SpecializedContext);
7926  int Diag = diag::err_template_spec_redecl_out_of_scope;
7927  if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
7928  Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7929  S.Diag(Loc, Diag) << EntityKind << Specialized
7930  << ND << isa<CXXRecordDecl>(ND);
7931  }
7932 
7933  S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7934 
7935  // Don't allow specializing in the wrong class during error recovery.
7936  // Otherwise, things can go horribly wrong.
7937  if (DC->isRecord())
7938  return true;
7939  }
7940 
7941  return false;
7942 }
7943 
7945  if (!E->isTypeDependent())
7946  return SourceLocation();
7947  DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7948  Checker.TraverseStmt(E);
7949  if (Checker.MatchLoc.isInvalid())
7950  return E->getSourceRange();
7951  return Checker.MatchLoc;
7952 }
7953 
7955  if (!TL.getType()->isDependentType())
7956  return SourceLocation();
7957  DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7958  Checker.TraverseTypeLoc(TL);
7959  if (Checker.MatchLoc.isInvalid())
7960  return TL.getSourceRange();
7961  return Checker.MatchLoc;
7962 }
7963 
7964 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7965 /// that checks non-type template partial specialization arguments.
7967  Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7968  const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7969  for (unsigned I = 0; I != NumArgs; ++I) {
7970  if (Args[I].getKind() == TemplateArgument::Pack) {
7972  S, TemplateNameLoc, Param, Args[I].pack_begin(),
7973  Args[I].pack_size(), IsDefaultArgument))
7974  return true;
7975 
7976  continue;
7977  }
7978 
7979  if (Args[I].getKind() != TemplateArgument::Expression)
7980  continue;
7981 
7982  Expr *ArgExpr = Args[I].getAsExpr();
7983 
7984  // We can have a pack expansion of any of the bullets below.
7985  if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7986  ArgExpr = Expansion->getPattern();
7987 
7988  // Strip off any implicit casts we added as part of type checking.
7989  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7990  ArgExpr = ICE->getSubExpr();
7991 
7992  // C++ [temp.class.spec]p8:
7993  // A non-type argument is non-specialized if it is the name of a
7994  // non-type parameter. All other non-type arguments are
7995  // specialized.
7996  //
7997  // Below, we check the two conditions that only apply to
7998  // specialized non-type arguments, so skip any non-specialized
7999  // arguments.
8000  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8001  if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8002  continue;
8003 
8004  // C++ [temp.class.spec]p9:
8005  // Within the argument list of a class template partial
8006  // specialization, the following restrictions apply:
8007  // -- A partially specialized non-type argument expression
8008  // shall not involve a template parameter of the partial
8009  // specialization except when the argument expression is a
8010  // simple identifier.
8011  // -- The type of a template parameter corresponding to a
8012  // specialized non-type argument shall not be dependent on a
8013  // parameter of the specialization.
8014  // DR1315 removes the first bullet, leaving an incoherent set of rules.
8015  // We implement a compromise between the original rules and DR1315:
8016  // -- A specialized non-type template argument shall not be
8017  // type-dependent and the corresponding template parameter
8018  // shall have a non-dependent type.
8019  SourceRange ParamUseRange =
8020  findTemplateParameterInType(Param->getDepth(), ArgExpr);
8021  if (ParamUseRange.isValid()) {
8022  if (IsDefaultArgument) {
8023  S.Diag(TemplateNameLoc,
8024  diag::err_dependent_non_type_arg_in_partial_spec);
8025  S.Diag(ParamUseRange.getBegin(),
8026  diag::note_dependent_non_type_default_arg_in_partial_spec)
8027  << ParamUseRange;
8028  } else {
8029  S.Diag(ParamUseRange.getBegin(),
8030  diag::err_dependent_non_type_arg_in_partial_spec)
8031  << ParamUseRange;
8032  }
8033  return true;
8034  }
8035 
8036  ParamUseRange = findTemplateParameter(
8037  Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8038  if (ParamUseRange.isValid()) {
8039  S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8040  diag::err_dependent_typed_non_type_arg_in_partial_spec)
8041  << Param->getType();
8043  return true;
8044  }
8045  }
8046 
8047  return false;
8048 }
8049 
8051  SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8052  unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8053  // We have to be conservative when checking a template in a dependent
8054  // context.
8055  if (PrimaryTemplate->getDeclContext()->isDependentContext())
8056  return false;
8057 
8058  TemplateParameterList *TemplateParams =
8059  PrimaryTemplate->getTemplateParameters();
8060  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8062  = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8063  if (!Param)
8064  continue;
8065 
8066  if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8067  Param, &TemplateArgs[I],
8068  1, I >= NumExplicit))
8069  return true;
8070  }
8071 
8072  return false;
8073 }
8074 
8076  Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8077  SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8078  TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8079  MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8080  assert(TUK != TagUseKind::Reference && "References are not specializations");
8081 
8082  SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8083  SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8084  SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8085 
8086  // Find the class template we're specializing
8087  TemplateName Name = TemplateId.Template.get();
8088  ClassTemplateDecl *ClassTemplate
8089  = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8090 
8091  if (!ClassTemplate) {
8092  Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8093  << (Name.getAsTemplateDecl() &&
8094  isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8095  return true;
8096  }
8097 
8098  bool isMemberSpecialization = false;
8099  bool isPartialSpecialization = false;
8100 
8101  if (SS.isSet()) {
8102  if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8103  diagnoseQualifiedDeclaration(SS, ClassTemplate->getDeclContext(),
8104  ClassTemplate->getDeclName(),
8105  TemplateNameLoc, &TemplateId,
8106  /*IsMemberSpecialization=*/false))
8107  return true;
8108  }
8109 
8110  // Check the validity of the template headers that introduce this
8111  // template.
8112  // FIXME: We probably shouldn't complain about these headers for
8113  // friend declarations.
8114  bool Invalid = false;
8115  TemplateParameterList *TemplateParams =
8116  MatchTemplateParametersToScopeSpecifier(
8117  KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8118  TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8119  if (Invalid)
8120  return true;
8121 
8122  // Check that we can declare a template specialization here.
8123  if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8124  return true;
8125 
8126  if (TemplateParams && TemplateParams->size() > 0) {
8127  isPartialSpecialization = true;
8128 
8129  if (TUK == TagUseKind::Friend) {
8130  Diag(KWLoc, diag::err_partial_specialization_friend)
8131  << SourceRange(LAngleLoc, RAngleLoc);
8132  return true;
8133  }
8134 
8135  // C++ [temp.class.spec]p10:
8136  // The template parameter list of a specialization shall not
8137  // contain default template argument values.
8138  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8139  Decl *Param = TemplateParams->getParam(I);
8140  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8141  if (TTP->hasDefaultArgument()) {
8142  Diag(TTP->getDefaultArgumentLoc(),
8143  diag::err_default_arg_in_partial_spec);
8144  TTP->removeDefaultArgument();
8145  }
8146  } else if (NonTypeTemplateParmDecl *NTTP
8147  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8148  if (NTTP->hasDefaultArgument()) {
8149  Diag(NTTP->getDefaultArgumentLoc(),
8150  diag::err_default_arg_in_partial_spec)
8151  << NTTP->getDefaultArgument().getSourceRange();
8152  NTTP->removeDefaultArgument();
8153  }
8154  } else {
8155  TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8156  if (TTP->hasDefaultArgument()) {
8158  diag::err_default_arg_in_partial_spec)
8159  << TTP->getDefaultArgument().getSourceRange();
8160  TTP->removeDefaultArgument();
8161  }
8162  }
8163  }
8164  } else if (TemplateParams) {
8165  if (TUK == TagUseKind::Friend)
8166  Diag(KWLoc, diag::err_template_spec_friend)
8168  SourceRange(TemplateParams->getTemplateLoc(),
8169  TemplateParams->getRAngleLoc()))
8170  << SourceRange(LAngleLoc, RAngleLoc);
8171  } else {
8172  assert(TUK == TagUseKind::Friend &&
8173  "should have a 'template<>' for this decl");
8174  }
8175 
8176  // Check that the specialization uses the same tag kind as the
8177  // original template.
8179  assert(Kind != TagTypeKind::Enum &&
8180  "Invalid enum tag in class template spec!");
8181  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8182  TUK == TagUseKind::Definition, KWLoc,
8183  ClassTemplate->getIdentifier())) {
8184  Diag(KWLoc, diag::err_use_with_wrong_tag)
8185  << ClassTemplate
8187  ClassTemplate->getTemplatedDecl()->getKindName());
8188  Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8189  diag::note_previous_use);
8190  Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8191  }
8192 
8193  // Translate the parser's template argument list in our AST format.
8194  TemplateArgumentListInfo TemplateArgs =
8195  makeTemplateArgumentListInfo(*this, TemplateId);
8196 
8197  // Check for unexpanded parameter packs in any of the template arguments.
8198  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8199  if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8200  isPartialSpecialization
8201  ? UPPC_PartialSpecialization
8202  : UPPC_ExplicitSpecialization))
8203  return true;
8204 
8205  // Check that the template argument list is well-formed for this
8206  // template.
8207  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
8208  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8209  false, SugaredConverted, CanonicalConverted,
8210  /*UpdateArgsWithConversions=*/true))
8211  return true;
8212 
8213  // Find the class template (partial) specialization declaration that
8214  // corresponds to these arguments.
8215  if (isPartialSpecialization) {
8216  if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
8217  TemplateArgs.size(),
8218  CanonicalConverted))
8219  return true;
8220 
8221  // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8222  // also do it during instantiation.
8223  if (!Name.isDependent() &&
8225  TemplateArgs, CanonicalConverted)) {
8226  Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8227  << ClassTemplate->getDeclName();
8228  isPartialSpecialization = false;
8229  Invalid = true;
8230  }
8231  }
8232 
8233  void *InsertPos = nullptr;
8234  ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8235 
8236  if (isPartialSpecialization)
8237  PrevDecl = ClassTemplate->findPartialSpecialization(
8238  CanonicalConverted, TemplateParams, InsertPos);
8239  else
8240  PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
8241 
8243 
8244  // Check whether we can declare a class template specialization in
8245  // the current scope.
8246  if (TUK != TagUseKind::Friend &&
8247  CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
8248  TemplateNameLoc,
8249  isPartialSpecialization))
8250  return true;
8251 
8252  // The canonical type
8253  QualType CanonType;
8254  if (isPartialSpecialization) {
8255  // Build the canonical type that describes the converted template
8256  // arguments of the class template partial specialization.
8257  TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8258  CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8259  CanonicalConverted);
8260 
8261  if (Context.hasSameType(CanonType,
8262  ClassTemplate->getInjectedClassNameSpecialization()) &&
8263  (!Context.getLangOpts().CPlusPlus20 ||
8264  !TemplateParams->hasAssociatedConstraints())) {
8265  // C++ [temp.class.spec]p9b3:
8266  //
8267  // -- The argument list of the specialization shall not be identical
8268  // to the implicit argument list of the primary template.
8269  //
8270  // This rule has since been removed, because it's redundant given DR1495,
8271  // but we keep it because it produces better diagnostics and recovery.
8272  Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8273  << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8274  << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8275  return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
8276  ClassTemplate->getIdentifier(),
8277  TemplateNameLoc,
8278  Attr,
8279  TemplateParams,
8280  AS_none, /*ModulePrivateLoc=*/SourceLocation(),
8281  /*FriendLoc*/SourceLocation(),
8282  TemplateParameterLists.size() - 1,
8283  TemplateParameterLists.data());
8284  }
8285 
8286  // Create a new class template partial specialization declaration node.
8288  = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8291  Context, Kind, ClassTemplate->getDeclContext(), KWLoc,
8292  TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted,
8293  CanonType, PrevPartial);
8294  Partial->setTemplateArgsAsWritten(TemplateArgs);
8295  SetNestedNameSpecifier(*this, Partial, SS);
8296  if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8298  Context, TemplateParameterLists.drop_back(1));
8299  }
8300 
8301  if (!PrevPartial)
8302  ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8303  Specialization = Partial;
8304 
8305  // If we are providing an explicit specialization of a member class
8306  // template specialization, make a note of that.
8307  if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8308  PrevPartial->setMemberSpecialization();
8309 
8310  CheckTemplatePartialSpecialization(Partial);
8311  } else {
8312  // Create a new class template specialization declaration node for
8313  // this explicit specialization or friend declaration.
8315  Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8316  ClassTemplate, CanonicalConverted, PrevDecl);
8317  Specialization->setTemplateArgsAsWritten(TemplateArgs);
8319  if (TemplateParameterLists.size() > 0) {
8320  Specialization->setTemplateParameterListsInfo(Context,
8321  TemplateParameterLists);
8322  }
8323 
8324  if (!PrevDecl)
8325  ClassTemplate->AddSpecialization(Specialization, InsertPos);
8326 
8327  if (CurContext->isDependentContext()) {
8328  TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8329  CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8330  CanonicalConverted);
8331  } else {
8332  CanonType = Context.getTypeDeclType(Specialization);
8333  }
8334  }
8335 
8336  // C++ [temp.expl.spec]p6:
8337  // If a template, a member template or the member of a class template is
8338  // explicitly specialized then that specialization shall be declared
8339  // before the first use of that specialization that would cause an implicit
8340  // instantiation to take place, in every translation unit in which such a
8341  // use occurs; no diagnostic is required.
8342  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8343  bool Okay = false;
8344  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8345  // Is there any previous explicit specialization declaration?
8347  Okay = true;
8348  break;
8349  }
8350  }
8351 
8352  if (!Okay) {
8353  SourceRange Range(TemplateNameLoc, RAngleLoc);
8354  Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8355  << Context.getTypeDeclType(Specialization) << Range;
8356 
8357  Diag(PrevDecl->getPointOfInstantiation(),
8358  diag::note_instantiation_required_here)
8359  << (PrevDecl->getTemplateSpecializationKind()
8361  return true;
8362  }
8363  }
8364 
8365  // If this is not a friend, note that this is an explicit specialization.
8366  if (TUK != TagUseKind::Friend)
8367  Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8368 
8369  // Check that this isn't a redefinition of this specialization.
8370  if (TUK == TagUseKind::Definition) {
8371  RecordDecl *Def = Specialization->getDefinition();
8372  NamedDecl *Hidden = nullptr;
8373  if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8374  SkipBody->ShouldSkip = true;
8375  SkipBody->Previous = Def;
8376  makeMergedDefinitionVisible(Hidden);
8377  } else if (Def) {
8378  SourceRange Range(TemplateNameLoc, RAngleLoc);
8379  Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8380  Diag(Def->getLocation(), diag::note_previous_definition);
8381  Specialization->setInvalidDecl();
8382  return true;
8383  }
8384  }
8385 
8386  ProcessDeclAttributeList(S, Specialization, Attr);
8388 
8389  // Add alignment attributes if necessary; these attributes are checked when
8390  // the ASTContext lays out the structure.
8391  if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8392  AddAlignmentAttributesForRecord(Specialization);
8393  AddMsStructLayoutForRecord(Specialization);
8394  }
8395 
8396  if (ModulePrivateLoc.isValid())
8397  Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8398  << (isPartialSpecialization? 1 : 0)
8399  << FixItHint::CreateRemoval(ModulePrivateLoc);
8400 
8401  // C++ [temp.expl.spec]p9:
8402  // A template explicit specialization is in the scope of the
8403  // namespace in which the template was defined.
8404  //
8405  // We actually implement this paragraph where we set the semantic
8406  // context (in the creation of the ClassTemplateSpecializationDecl),
8407  // but we also maintain the lexical context where the actual
8408  // definition occurs.
8409  Specialization->setLexicalDeclContext(CurContext);
8410 
8411  // We may be starting the definition of this specialization.
8412  if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
8413  Specialization->startDefinition();
8414 
8415  if (TUK == TagUseKind::Friend) {
8416  // Build the fully-sugared type for this class template
8417  // specialization as the user wrote in the specialization
8418  // itself. This means that we'll pretty-print the type retrieved
8419  // from the specialization's declaration the way that the user
8420  // actually wrote the specialization, rather than formatting the
8421  // name based on the "canonical" representation used to store the
8422  // template arguments in the specialization.
8424  Name, TemplateNameLoc, TemplateArgs, CanonType);
8425  FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
8426  TemplateNameLoc,
8427  WrittenTy,
8428  /*FIXME:*/KWLoc);
8429  Friend->setAccess(AS_public);
8430  CurContext->addDecl(Friend);
8431  } else {
8432  // Add the specialization into its lexical context, so that it can
8433  // be seen when iterating through the list of declarations in that
8434  // context. However, specializations are not found by name lookup.
8435  CurContext->addDecl(Specialization);
8436  }
8437 
8438  if (SkipBody && SkipBody->ShouldSkip)
8439  return SkipBody->Previous;
8440 
8441  Specialization->setInvalidDecl(Invalid);
8442  return Specialization;
8443 }
8444 
8446  MultiTemplateParamsArg TemplateParameterLists,
8447  Declarator &D) {
8448  Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8449  ActOnDocumentableDecl(NewDecl);
8450  return NewDecl;
8451 }
8452 
8454  Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8455  const IdentifierInfo *Name, SourceLocation NameLoc) {
8456  DeclContext *DC = CurContext;
8457 
8458  if (!DC->getRedeclContext()->isFileContext()) {
8459  Diag(NameLoc,
8460  diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8461  return nullptr;
8462  }
8463 
8464  if (TemplateParameterLists.size() > 1) {
8465  Diag(NameLoc, diag::err_concept_extra_headers);
8466  return nullptr;
8467  }
8468 
8469  TemplateParameterList *Params = TemplateParameterLists.front();
8470 
8471  if (Params->size() == 0) {
8472  Diag(NameLoc, diag::err_concept_no_parameters);
8473  return nullptr;
8474  }
8475 
8476  // Ensure that the parameter pack, if present, is the last parameter in the
8477  // template.
8478  for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
8479  ParamEnd = Params->end();
8480  ParamIt != ParamEnd; ++ParamIt) {
8481  Decl const *Param = *ParamIt;
8482  if (Param->isParameterPack()) {
8483  if (++ParamIt == ParamEnd)
8484  break;
8485  Diag(Param->getLocation(),
8486  diag::err_template_param_pack_must_be_last_template_parameter);
8487  return nullptr;
8488  }
8489  }
8490 
8491  ConceptDecl *NewDecl =
8492  ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
8493 
8494  if (NewDecl->hasAssociatedConstraints()) {
8495  // C++2a [temp.concept]p4:
8496  // A concept shall not have associated constraints.
8497  Diag(NameLoc, diag::err_concept_no_associated_constraints);
8498  NewDecl->setInvalidDecl();
8499  }
8500 
8501  DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
8502  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8503  forRedeclarationInCurContext());
8504  LookupName(Previous, S);
8505  FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8506  /*AllowInlineNamespace*/ false);
8507 
8508  // We cannot properly handle redeclarations until we parse the constraint
8509  // expression, so only inject the name if we are sure we are not redeclaring a
8510  // symbol
8511  if (Previous.empty())
8512  PushOnScopeChains(NewDecl, S, true);
8513 
8514  return NewDecl;
8515 }
8516 
8518  bool Found = false;
8520  while (F.hasNext()) {
8521  NamedDecl *D = F.next();
8522  if (D == C) {
8523  F.erase();
8524  Found = true;
8525  break;
8526  }
8527  }
8528  F.done();
8529  return Found;
8530 }
8531 
8532 ConceptDecl *
8534  Expr *ConstraintExpr,
8535  const ParsedAttributesView &Attrs) {
8536  assert(!C->hasDefinition() && "Concept already defined");
8537  if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
8538  return nullptr;
8539  C->setDefinition(ConstraintExpr);
8540  ProcessDeclAttributeList(S, C, Attrs);
8541 
8542  // Check for conflicting previous declaration.
8543  DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
8544  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8545  forRedeclarationInCurContext());
8546  LookupName(Previous, S);
8547  FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8548  /*AllowInlineNamespace*/ false);
8549  bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
8550  bool AddToScope = true;
8551  CheckConceptRedefinition(C, Previous, AddToScope);
8552 
8553  ActOnDocumentableDecl(C);
8554  if (!WasAlreadyAdded && AddToScope)
8555  PushOnScopeChains(C, S);
8556 
8557  return C;
8558 }
8559 
8561  LookupResult &Previous, bool &AddToScope) {
8562  AddToScope = true;
8563 
8564  if (Previous.empty())
8565  return;
8566 
8567  auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
8568  if (!OldConcept) {
8569  auto *Old = Previous.getRepresentativeDecl();
8570  Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
8571  << NewDecl->getDeclName();
8572  notePreviousDefinition(Old, NewDecl->getLocation());
8573  AddToScope = false;
8574  return;
8575  }
8576  // Check if we can merge with a concept declaration.
8577  bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
8578  if (!IsSame) {
8579  Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
8580  << NewDecl->getDeclName();
8581  notePreviousDefinition(OldConcept, NewDecl->getLocation());
8582  AddToScope = false;
8583  return;
8584  }
8585  if (hasReachableDefinition(OldConcept) &&
8586  IsRedefinitionInModule(NewDecl, OldConcept)) {
8587  Diag(NewDecl->getLocation(), diag::err_redefinition)
8588  << NewDecl->getDeclName();
8589  notePreviousDefinition(OldConcept, NewDecl->getLocation());
8590  AddToScope = false;
8591  return;
8592  }
8593  if (!Previous.isSingleResult()) {
8594  // FIXME: we should produce an error in case of ambig and failed lookups.
8595  // Other decls (e.g. namespaces) also have this shortcoming.
8596  return;
8597  }
8598  // We unwrap canonical decl late to check for module visibility.
8599  Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
8600 }
8601 
8603  SourceLocation Loc) {
8604  if (!Concept->isInvalidDecl() && !Concept->hasDefinition()) {
8605  Diag(Loc, diag::err_recursive_concept) << Concept;
8606  Diag(Concept->getLocation(), diag::note_declared_at);
8607  return true;
8608  }
8609  return false;
8610 }
8611 
8612 /// \brief Strips various properties off an implicit instantiation
8613 /// that has just been explicitly specialized.
8614 static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
8615  if (MinGW || (isa<FunctionDecl>(D) &&
8616  cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
8617  D->dropAttrs<DLLImportAttr, DLLExportAttr>();
8618 
8619  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8620  FD->setInlineSpecified(false);
8621 }
8622 
8623 /// Compute the diagnostic location for an explicit instantiation
8624 // declaration or definition.
8626  NamedDecl* D, SourceLocation PointOfInstantiation) {
8627  // Explicit instantiations following a specialization have no effect and
8628  // hence no PointOfInstantiation. In that case, walk decl backwards
8629  // until a valid name loc is found.
8630  SourceLocation PrevDiagLoc = PointOfInstantiation;
8631  for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8632  Prev = Prev->getPreviousDecl()) {
8633  PrevDiagLoc = Prev->getLocation();
8634  }
8635  assert(PrevDiagLoc.isValid() &&
8636  "Explicit instantiation without point of instantiation?");
8637  return PrevDiagLoc;
8638 }
8639 
8640 bool
8643  NamedDecl *PrevDecl,
8645  SourceLocation PrevPointOfInstantiation,
8646  bool &HasNoEffect) {
8647  HasNoEffect = false;
8648 
8649  switch (NewTSK) {
8650  case TSK_Undeclared:
8652  assert(
8653  (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8654  "previous declaration must be implicit!");
8655  return false;
8656 
8658  switch (PrevTSK) {
8659  case TSK_Undeclared:
8661  // Okay, we're just specializing something that is either already
8662  // explicitly specialized or has merely been mentioned without any
8663  // instantiation.
8664  return false;
8665 
8667  if (PrevPointOfInstantiation.isInvalid()) {
8668  // The declaration itself has not actually been instantiated, so it is
8669  // still okay to specialize it.
8671  PrevDecl,
8672  Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
8673  return false;
8674  }
8675  // Fall through
8676  [[fallthrough]];
8677 
8680  assert((PrevTSK == TSK_ImplicitInstantiation ||
8681  PrevPointOfInstantiation.isValid()) &&
8682  "Explicit instantiation without point of instantiation?");
8683 
8684  // C++ [temp.expl.spec]p6:
8685  // If a template, a member template or the member of a class template
8686  // is explicitly specialized then that specialization shall be declared
8687  // before the first use of that specialization that would cause an
8688  // implicit instantiation to take place, in every translation unit in
8689  // which such a use occurs; no diagnostic is required.
8690  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8691  // Is there any previous explicit specialization declaration?
8693  return false;
8694  }
8695 
8696  Diag(NewLoc, diag::err_specialization_after_instantiation)
8697  << PrevDecl;
8698  Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
8699  << (PrevTSK != TSK_ImplicitInstantiation);
8700 
8701  return true;
8702  }
8703  llvm_unreachable("The switch over PrevTSK must be exhaustive.");
8704 
8706  switch (PrevTSK) {
8708  // This explicit instantiation declaration is redundant (that's okay).
8709  HasNoEffect = true;
8710  return false;
8711 
8712  case TSK_Undeclared:
8714  // We're explicitly instantiating something that may have already been
8715  // implicitly instantiated; that's fine.
8716  return false;
8717 
8719  // C++0x [temp.explicit]p4:
8720  // For a given set of template parameters, if an explicit instantiation
8721  // of a template appears after a declaration of an explicit
8722  // specialization for that template, the explicit instantiation has no
8723  // effect.
8724  HasNoEffect = true;
8725  return false;
8726 
8728  // C++0x [temp.explicit]p10:
8729  // If an entity is the subject of both an explicit instantiation
8730  // declaration and an explicit instantiation definition in the same
8731  // translation unit, the definition shall follow the declaration.
8732  Diag(NewLoc,
8733  diag::err_explicit_instantiation_declaration_after_definition);
8734 
8735  // Explicit instantiations following a specialization have no effect and
8736  // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8737  // until a valid name loc is found.
8738  Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8739  diag::note_explicit_instantiation_definition_here);
8740  HasNoEffect = true;
8741  return false;
8742  }
8743  llvm_unreachable("Unexpected TemplateSpecializationKind!");
8744 
8746  switch (PrevTSK) {
8747  case TSK_Undeclared:
8749  // We're explicitly instantiating something that may have already been
8750  // implicitly instantiated; that's fine.
8751  return false;
8752 
8754  // C++ DR 259, C++0x [temp.explicit]p4:
8755  // For a given set of template parameters, if an explicit
8756  // instantiation of a template appears after a declaration of
8757  // an explicit specialization for that template, the explicit
8758  // instantiation has no effect.
8759  Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
8760  << PrevDecl;
8761  Diag(PrevDecl->getLocation(),
8762  diag::note_previous_template_specialization);
8763  HasNoEffect = true;
8764  return false;
8765 
8767  // We're explicitly instantiating a definition for something for which we
8768  // were previously asked to suppress instantiations. That's fine.
8769 
8770  // C++0x [temp.explicit]p4:
8771  // For a given set of template parameters, if an explicit instantiation
8772  // of a template appears after a declaration of an explicit
8773  // specialization for that template, the explicit instantiation has no
8774  // effect.
8775  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8776  // Is there any previous explicit specialization declaration?
8778  HasNoEffect = true;
8779  break;
8780  }
8781  }
8782 
8783  return false;
8784 
8786  // C++0x [temp.spec]p5:
8787  // For a given template and a given set of template-arguments,
8788  // - an explicit instantiation definition shall appear at most once
8789  // in a program,
8790 
8791  // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8792  Diag(NewLoc, (getLangOpts().MSVCCompat)
8793  ? diag::ext_explicit_instantiation_duplicate
8794  : diag::err_explicit_instantiation_duplicate)
8795  << PrevDecl;
8796  Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8797  diag::note_previous_explicit_instantiation);
8798  HasNoEffect = true;
8799  return false;
8800  }
8801  }
8802 
8803  llvm_unreachable("Missing specialization/instantiation case?");
8804 }
8805 
8807  FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
8809  // Remove anything from Previous that isn't a function template in
8810  // the correct context.
8811  DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8812  LookupResult::Filter F = Previous.makeFilter();
8813  enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8814  SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
8815  while (F.hasNext()) {
8816  NamedDecl *D = F.next()->getUnderlyingDecl();
8817  if (!isa<FunctionTemplateDecl>(D)) {
8818  F.erase();
8819  DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8820  continue;
8821  }
8822 
8823  if (!FDLookupContext->InEnclosingNamespaceSetOf(
8825  F.erase();
8826  DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8827  continue;
8828  }
8829  }
8830  F.done();
8831 
8832  bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
8833  if (Previous.empty()) {
8834  Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
8835  << IsFriend;
8836  for (auto &P : DiscardedCandidates)
8837  Diag(P.second->getLocation(),
8838  diag::note_dependent_function_template_spec_discard_reason)
8839  << P.first << IsFriend;
8840  return true;
8841  }
8842 
8843  FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8844  ExplicitTemplateArgs);
8845  return false;
8846 }
8847 
8849  FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8850  LookupResult &Previous, bool QualifiedFriend) {
8851  // The set of function template specializations that could match this
8852  // explicit function template specialization.
8853  UnresolvedSet<8> Candidates;
8854  TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8855  /*ForTakingAddress=*/false);
8856 
8857  llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8858  ConvertedTemplateArgs;
8859 
8860  DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8861  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8862  I != E; ++I) {
8863  NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8864  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
8865  // Only consider templates found within the same semantic lookup scope as
8866  // FD.
8867  if (!FDLookupContext->InEnclosingNamespaceSetOf(
8868  Ovl->getDeclContext()->getRedeclContext()))
8869  continue;
8870 
8871  QualType FT = FD->getType();
8872  // C++11 [dcl.constexpr]p8:
8873  // A constexpr specifier for a non-static member function that is not
8874  // a constructor declares that member function to be const.
8875  //
8876  // When matching a constexpr member function template specialization
8877  // against the primary template, we don't yet know whether the
8878  // specialization has an implicit 'const' (because we don't know whether
8879  // it will be a static member function until we know which template it
8880  // specializes). This rule was removed in C++14.
8881  if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
8882  !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
8883  !isa<CXXConstructorDecl, CXXDestructorDecl>(NewMD)) {
8884  auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
8885  if (OldMD && OldMD->isConst()) {
8886  const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
8888  EPI.TypeQuals.addConst();
8889  FT = Context.getFunctionType(FPT->getReturnType(),
8890  FPT->getParamTypes(), EPI);
8891  }
8892  }
8893 
8895  if (ExplicitTemplateArgs)
8896  Args = *ExplicitTemplateArgs;
8897 
8898  // C++ [temp.expl.spec]p11:
8899  // A trailing template-argument can be left unspecified in the
8900  // template-id naming an explicit function template specialization
8901  // provided it can be deduced from the function argument type.
8902  // Perform template argument deduction to determine whether we may be
8903  // specializing this template.
8904  // FIXME: It is somewhat wasteful to build
8905  TemplateDeductionInfo Info(FailedCandidates.getLocation());
8906  FunctionDecl *Specialization = nullptr;
8908  cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
8909  ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
8911  // Template argument deduction failed; record why it failed, so
8912  // that we can provide nifty diagnostics.
8913  FailedCandidates.addCandidate().set(
8914  I.getPair(), FunTmpl->getTemplatedDecl(),
8915  MakeDeductionFailureInfo(Context, TDK, Info));
8916  (void)TDK;
8917  continue;
8918  }
8919 
8920  // Target attributes are part of the cuda function signature, so
8921  // the deduced template's cuda target must match that of the
8922  // specialization. Given that C++ template deduction does not
8923  // take target attributes into account, we reject candidates
8924  // here that have a different target.
8925  if (LangOpts.CUDA &&
8926  CUDA().IdentifyTarget(Specialization,
8927  /* IgnoreImplicitHDAttr = */ true) !=
8928  CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
8929  FailedCandidates.addCandidate().set(
8930  I.getPair(), FunTmpl->getTemplatedDecl(),
8933  continue;
8934  }
8935 
8936  // Record this candidate.
8937  if (ExplicitTemplateArgs)
8938  ConvertedTemplateArgs[Specialization] = std::move(Args);
8939  Candidates.addDecl(Specialization, I.getAccess());
8940  }
8941  }
8942 
8943  // For a qualified friend declaration (with no explicit marker to indicate
8944  // that a template specialization was intended), note all (template and
8945  // non-template) candidates.
8946  if (QualifiedFriend && Candidates.empty()) {
8947  Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
8948  << FD->getDeclName() << FDLookupContext;
8949  // FIXME: We should form a single candidate list and diagnose all
8950  // candidates at once, to get proper sorting and limiting.
8951  for (auto *OldND : Previous) {
8952  if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
8953  NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
8954  }
8955  FailedCandidates.NoteCandidates(*this, FD->getLocation());
8956  return true;
8957  }
8958 
8959  // Find the most specialized function template.
8960  UnresolvedSetIterator Result = getMostSpecialized(
8961  Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
8962  PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8963  PDiag(diag::err_function_template_spec_ambiguous)
8964  << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
8965  PDiag(diag::note_function_template_spec_matched));
8966 
8967  if (Result == Candidates.end())
8968  return true;
8969 
8970  // Ignore access information; it doesn't figure into redeclaration checking.
8971  FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8972 
8973  // C++23 [except.spec]p13:
8974  // An exception specification is considered to be needed when:
8975  // - [...]
8976  // - the exception specification is compared to that of another declaration
8977  // (e.g., an explicit specialization or an overriding virtual function);
8978  // - [...]
8979  //
8980  // The exception specification of a defaulted function is evaluated as
8981  // described above only when needed; similarly, the noexcept-specifier of a
8982  // specialization of a function template or member function of a class
8983  // template is instantiated only when needed.
8984  //
8985  // The standard doesn't specify what the "comparison with another declaration"
8986  // entails, nor the exact circumstances in which it occurs. Moreover, it does
8987  // not state which properties of an explicit specialization must match the
8988  // primary template.
8989  //
8990  // We assume that an explicit specialization must correspond with (per
8991  // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
8992  // the declaration produced by substitution into the function template.
8993  //
8994  // Since the determination whether two function declarations correspond does
8995  // not consider exception specification, we only need to instantiate it once
8996  // we determine the primary template when comparing types per
8997  // [basic.link]p11.1.
8998  auto *SpecializationFPT =
8999  Specialization->getType()->castAs<FunctionProtoType>();
9000  // If the function has a dependent exception specification, resolve it after
9001  // we have selected the primary template so we can check whether it matches.
9002  if (getLangOpts().CPlusPlus17 &&
9003  isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9004  !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9005  return true;
9006 
9008  = Specialization->getTemplateSpecializationInfo();
9009  assert(SpecInfo && "Function template specialization info missing?");
9010 
9011  // Note: do not overwrite location info if previous template
9012  // specialization kind was explicit.
9014  if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9015  Specialization->setLocation(FD->getLocation());
9016  Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9017  // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9018  // function can differ from the template declaration with respect to
9019  // the constexpr specifier.
9020  // FIXME: We need an update record for this AST mutation.
9021  // FIXME: What if there are multiple such prior declarations (for instance,
9022  // from different modules)?
9023  Specialization->setConstexprKind(FD->getConstexprKind());
9024  }
9025 
9026  // FIXME: Check if the prior specialization has a point of instantiation.
9027  // If so, we have run afoul of .
9028 
9029  // If this is a friend declaration, then we're not really declaring
9030  // an explicit specialization.
9031  bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9032 
9033  // Check the scope of this explicit specialization.
9034  if (!isFriend &&
9036  Specialization->getPrimaryTemplate(),
9037  Specialization, FD->getLocation(),
9038  false))
9039  return true;
9040 
9041  // C++ [temp.expl.spec]p6:
9042  // If a template, a member template or the member of a class template is
9043  // explicitly specialized then that specialization shall be declared
9044  // before the first use of that specialization that would cause an implicit
9045  // instantiation to take place, in every translation unit in which such a
9046  // use occurs; no diagnostic is required.
9047  bool HasNoEffect = false;
9048  if (!isFriend &&
9049  CheckSpecializationInstantiationRedecl(FD->getLocation(),
9052  SpecInfo->getTemplateSpecializationKind(),
9053  SpecInfo->getPointOfInstantiation(),
9054  HasNoEffect))
9055  return true;
9056 
9057  // Mark the prior declaration as an explicit specialization, so that later
9058  // clients know that this is an explicit specialization.
9059  if (!isFriend) {
9060  // Since explicit specializations do not inherit '=delete' from their
9061  // primary function template - check if the 'specialization' that was
9062  // implicitly generated (during template argument deduction for partial
9063  // ordering) from the most specialized of all the function templates that
9064  // 'FD' could have been specializing, has a 'deleted' definition. If so,
9065  // first check that it was implicitly generated during template argument
9066  // deduction by making sure it wasn't referenced, and then reset the deleted
9067  // flag to not-deleted, so that we can inherit that information from 'FD'.
9068  if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9069  !Specialization->getCanonicalDecl()->isReferenced()) {
9070  // FIXME: This assert will not hold in the presence of modules.
9071  assert(
9072  Specialization->getCanonicalDecl() == Specialization &&
9073  "This must be the only existing declaration of this specialization");
9074  // FIXME: We need an update record for this AST mutation.
9075  Specialization->setDeletedAsWritten(false);
9076  }
9077  // FIXME: We need an update record for this AST mutation.
9079  MarkUnusedFileScopedDecl(Specialization);
9080  }
9081 
9082  // Turn the given function declaration into a function template
9083  // specialization, with the template arguments from the previous
9084  // specialization.
9085  // Take copies of (semantic and syntactic) template argument lists.
9087  Context, Specialization->getTemplateSpecializationArgs()->asArray());
9088  FD->setFunctionTemplateSpecialization(
9089  Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9090  SpecInfo->getTemplateSpecializationKind(),
9091  ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9092 
9093  // A function template specialization inherits the target attributes
9094  // of its template. (We require the attributes explicitly in the
9095  // code to match, but a template may have implicit attributes by
9096  // virtue e.g. of being constexpr, and it passes these implicit
9097  // attributes on to its specializations.)
9098  if (LangOpts.CUDA)
9099  CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9100 
9101  // The "previous declaration" for this function template specialization is
9102  // the prior function template specialization.
9103  Previous.clear();
9104  Previous.addDecl(Specialization);
9105  return false;
9106 }
9107 
9108 bool
9110  assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9111  "Only for non-template members");
9112 
9113  // Try to find the member we are instantiating.
9114  NamedDecl *FoundInstantiation = nullptr;
9115  NamedDecl *Instantiation = nullptr;
9116  NamedDecl *InstantiatedFrom = nullptr;
9117  MemberSpecializationInfo *MSInfo = nullptr;
9118 
9119  if (Previous.empty()) {
9120  // Nowhere to look anyway.
9121  } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9122  UnresolvedSet<8> Candidates;
9123  for (NamedDecl *Candidate : Previous) {
9124  auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9125  // Ignore any candidates that aren't member functions.
9126  if (!Method)
9127  continue;
9128 
9129  QualType Adjusted = Function->getType();
9130  if (!hasExplicitCallingConv(Adjusted))
9131  Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9132  // Ignore any candidates with the wrong type.
9133  // This doesn't handle deduced return types, but both function
9134  // declarations should be undeduced at this point.
9135  // FIXME: The exception specification should probably be ignored when
9136  // comparing the types.
9137  if (!Context.hasSameType(Adjusted, Method->getType()))
9138  continue;
9139 
9140  // Ignore any candidates with unsatisfied constraints.
9141  if (ConstraintSatisfaction Satisfaction;
9142  Method->getTrailingRequiresClause() &&
9143  (CheckFunctionConstraints(Method, Satisfaction,
9144  /*UsageLoc=*/Member->getLocation(),
9145  /*ForOverloadResolution=*/true) ||
9146  !Satisfaction.IsSatisfied))
9147  continue;
9148 
9149  Candidates.addDecl(Candidate);
9150  }
9151 
9152  // If we have no viable candidates left after filtering, we are done.
9153  if (Candidates.empty())
9154  return false;
9155 
9156  // Find the function that is more constrained than every other function it
9157  // has been compared to.
9158  UnresolvedSetIterator Best = Candidates.begin();
9159  CXXMethodDecl *BestMethod = nullptr;
9160  for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9161  I != E; ++I) {
9162  auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9163  if (I == Best ||
9164  getMoreConstrainedFunction(Method, BestMethod) == Method) {
9165  Best = I;
9166  BestMethod = Method;
9167  }
9168  }
9169 
9170  FoundInstantiation = *Best;
9171  Instantiation = BestMethod;
9172  InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9173  MSInfo = BestMethod->getMemberSpecializationInfo();
9174 
9175  // Make sure the best candidate is more constrained than all of the others.
9176  bool Ambiguous = false;
9177  for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9178  I != E; ++I) {
9179  auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9180  if (I != Best &&
9181  getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9182  Ambiguous = true;
9183  break;
9184  }
9185  }
9186 
9187  if (Ambiguous) {
9188  Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9189  << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9190  for (NamedDecl *Candidate : Candidates) {
9191  Candidate = Candidate->getUnderlyingDecl();
9192  Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9193  << Candidate;
9194  }
9195  return true;
9196  }
9197  } else if (isa<VarDecl>(Member)) {
9198  VarDecl *PrevVar;
9199  if (Previous.isSingleResult() &&
9200  (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9201  if (PrevVar->isStaticDataMember()) {
9202  FoundInstantiation = Previous.getRepresentativeDecl();
9203  Instantiation = PrevVar;
9204  InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9205  MSInfo = PrevVar->getMemberSpecializationInfo();
9206  }
9207  } else if (isa<RecordDecl>(Member)) {
9208  CXXRecordDecl *PrevRecord;
9209  if (Previous.isSingleResult() &&
9210  (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9211  FoundInstantiation = Previous.getRepresentativeDecl();
9212  Instantiation = PrevRecord;
9213  InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9214  MSInfo = PrevRecord->getMemberSpecializationInfo();
9215  }
9216  } else if (isa<EnumDecl>(Member)) {
9217  EnumDecl *PrevEnum;
9218  if (Previous.isSingleResult() &&
9219  (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9220  FoundInstantiation = Previous.getRepresentativeDecl();
9221  Instantiation = PrevEnum;
9222  InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9223  MSInfo = PrevEnum->getMemberSpecializationInfo();
9224  }
9225  }
9226 
9227  if (!Instantiation) {
9228  // There is no previous declaration that matches. Since member
9229  // specializations are always out-of-line, the caller will complain about
9230  // this mismatch later.
9231  return false;
9232  }
9233 
9234  // A member specialization in a friend declaration isn't really declaring
9235  // an explicit specialization, just identifying a specific (possibly implicit)
9236  // specialization. Don't change the template specialization kind.
9237  //
9238  // FIXME: Is this really valid? Other compilers reject.
9239  if (Member->getFriendObjectKind() != Decl::FOK_None) {
9240  // Preserve instantiation information.
9241  if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9242  cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9243  cast<CXXMethodDecl>(InstantiatedFrom),
9244  cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
9245  } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9246  cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9247  cast<CXXRecordDecl>(InstantiatedFrom),
9248  cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
9249  }
9250 
9251  Previous.clear();
9252  Previous.addDecl(FoundInstantiation);
9253  return false;
9254  }
9255 
9256  // Make sure that this is a specialization of a member.
9257  if (!InstantiatedFrom) {
9258  Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9259  << Member;
9260  Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9261  return true;
9262  }
9263 
9264  // C++ [temp.expl.spec]p6:
9265  // If a template, a member template or the member of a class template is
9266  // explicitly specialized then that specialization shall be declared
9267  // before the first use of that specialization that would cause an implicit
9268  // instantiation to take place, in every translation unit in which such a
9269  // use occurs; no diagnostic is required.
9270  assert(MSInfo && "Member specialization info missing?");
9271 
9272  bool HasNoEffect = false;
9273  if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
9275  Instantiation,
9277  MSInfo->getPointOfInstantiation(),
9278  HasNoEffect))
9279  return true;
9280 
9281  // Check the scope of this explicit specialization.
9283  InstantiatedFrom,
9284  Instantiation, Member->getLocation(),
9285  false))
9286  return true;
9287 
9288  // Note that this member specialization is an "instantiation of" the
9289  // corresponding member of the original template.
9290  if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9291  FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9292  if (InstantiationFunction->getTemplateSpecializationKind() ==
9294  // Explicit specializations of member functions of class templates do not
9295  // inherit '=delete' from the member function they are specializing.
9296  if (InstantiationFunction->isDeleted()) {
9297  // FIXME: This assert will not hold in the presence of modules.
9298  assert(InstantiationFunction->getCanonicalDecl() ==
9299  InstantiationFunction);
9300  // FIXME: We need an update record for this AST mutation.
9301  InstantiationFunction->setDeletedAsWritten(false);
9302  }
9303  }
9304 
9305  MemberFunction->setInstantiationOfMemberFunction(
9306  cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9307  } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9308  MemberVar->setInstantiationOfStaticDataMember(
9309  cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9310  } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9311  MemberClass->setInstantiationOfMemberClass(
9312  cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9313  } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9314  MemberEnum->setInstantiationOfMemberEnum(
9315  cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9316  } else {
9317  llvm_unreachable("unknown member specialization kind");
9318  }
9319 
9320  // Save the caller the trouble of having to figure out which declaration
9321  // this specialization matches.
9322  Previous.clear();
9323  Previous.addDecl(FoundInstantiation);
9324  return false;
9325 }
9326 
9327 /// Complete the explicit specialization of a member of a class template by
9328 /// updating the instantiated member to be marked as an explicit specialization.
9329 ///
9330 /// \param OrigD The member declaration instantiated from the template.
9331 /// \param Loc The location of the explicit specialization of the member.
9332 template<typename DeclT>
9333 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9334  SourceLocation Loc) {
9335  if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9336  return;
9337 
9338  // FIXME: Inform AST mutation listeners of this AST mutation.
9339  // FIXME: If there are multiple in-class declarations of the member (from
9340  // multiple modules, or a declaration and later definition of a member type),
9341  // should we update all of them?
9342  OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9343  OrigD->setLocation(Loc);
9344 }
9345 
9348  NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9349  if (Instantiation == Member)
9350  return;
9351 
9352  if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9353  completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9354  else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9355  completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9356  else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9357  completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9358  else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9359  completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9360  else
9361  llvm_unreachable("unknown member specialization kind");
9362 }
9363 
9364 /// Check the scope of an explicit instantiation.
9365 ///
9366 /// \returns true if a serious error occurs, false otherwise.
9368  SourceLocation InstLoc,
9369  bool WasQualifiedName) {
9371  DeclContext *CurContext = S.CurContext->getRedeclContext();
9372 
9373  if (CurContext->isRecord()) {
9374  S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9375  << D;
9376  return true;
9377  }
9378 
9379  // C++11 [temp.explicit]p3:
9380  // An explicit instantiation shall appear in an enclosing namespace of its
9381  // template. If the name declared in the explicit instantiation is an
9382  // unqualified name, the explicit instantiation shall appear in the
9383  // namespace where its template is declared or, if that namespace is inline
9384  // (7.3.1), any namespace from its enclosing namespace set.
9385  //
9386  // This is DR275, which we do not retroactively apply to C++98/03.
9387  if (WasQualifiedName) {
9388  if (CurContext->Encloses(OrigContext))
9389  return false;
9390  } else {
9391  if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9392  return false;
9393  }
9394 
9395  if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9396  if (WasQualifiedName)
9397  S.Diag(InstLoc,
9398  S.getLangOpts().CPlusPlus11?
9399  diag::err_explicit_instantiation_out_of_scope :
9400  diag::warn_explicit_instantiation_out_of_scope_0x)
9401  << D << NS;
9402  else
9403  S.Diag(InstLoc,
9404  S.getLangOpts().CPlusPlus11?
9405  diag::err_explicit_instantiation_unqualified_wrong_namespace :
9406  diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9407  << D << NS;
9408  } else
9409  S.Diag(InstLoc,
9410  S.getLangOpts().CPlusPlus11?
9411  diag::err_explicit_instantiation_must_be_global :
9412  diag::warn_explicit_instantiation_must_be_global_0x)
9413  << D;
9414  S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9415  return false;
9416 }
9417 
9418 /// Common checks for whether an explicit instantiation of \p D is valid.
9420  SourceLocation InstLoc,
9421  bool WasQualifiedName,
9423  // C++ [temp.explicit]p13:
9424  // An explicit instantiation declaration shall not name a specialization of
9425  // a template with internal linkage.
9427  D->getFormalLinkage() == Linkage::Internal) {
9428  S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9429  return true;
9430  }
9431 
9432  // C++11 [temp.explicit]p3: [DR 275]
9433  // An explicit instantiation shall appear in an enclosing namespace of its
9434  // template.
9435  if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9436  return true;
9437 
9438  return false;
9439 }
9440 
9441 /// Determine whether the given scope specifier has a template-id in it.
9443  if (!SS.isSet())
9444  return false;
9445 
9446  // C++11 [temp.explicit]p3:
9447  // If the explicit instantiation is for a member function, a member class
9448  // or a static data member of a class template specialization, the name of
9449  // the class template specialization in the qualified-id for the member
9450  // name shall be a simple-template-id.
9451  //
9452  // C++98 has the same restriction, just worded differently.
9453  for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9454  NNS = NNS->getPrefix())
9455  if (const Type *T = NNS->getAsType())
9456  if (isa<TemplateSpecializationType>(T))
9457  return true;
9458 
9459  return false;
9460 }
9461 
9462 /// Make a dllexport or dllimport attr on a class template specialization take
9463 /// effect.
9466  auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
9467  assert(A && "dllExportImportClassTemplateSpecialization called "
9468  "on Def without dllexport or dllimport");
9469 
9470  // We reject explicit instantiations in class scope, so there should
9471  // never be any delayed exported classes to worry about.
9472  assert(S.DelayedDllExportClasses.empty() &&
9473  "delayed exports present at explicit instantiation");
9475 
9476  // Propagate attribute to base class templates.
9477  for (auto &B : Def->bases()) {
9478  if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9479  B.getType()->getAsCXXRecordDecl()))
9481  }
9482 
9484 }
9485 
9487  Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9488  unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9489  TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9490  SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9491  SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9492  // Find the class template we're specializing
9493  TemplateName Name = TemplateD.get();
9494  TemplateDecl *TD = Name.getAsTemplateDecl();
9495  // Check that the specialization uses the same tag kind as the
9496  // original template.
9498  assert(Kind != TagTypeKind::Enum &&
9499  "Invalid enum tag in class template explicit instantiation!");
9500 
9501  ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
9502 
9503  if (!ClassTemplate) {
9504  NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9505  Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
9506  << TD << NTK << llvm::to_underlying(Kind);
9507  Diag(TD->getLocation(), diag::note_previous_use);
9508  return true;
9509  }
9510 
9511  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9512  Kind, /*isDefinition*/false, KWLoc,
9513  ClassTemplate->getIdentifier())) {
9514  Diag(KWLoc, diag::err_use_with_wrong_tag)
9515  << ClassTemplate
9517  ClassTemplate->getTemplatedDecl()->getKindName());
9518  Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9519  diag::note_previous_use);
9520  Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9521  }
9522 
9523  // C++0x [temp.explicit]p2:
9524  // There are two forms of explicit instantiation: an explicit instantiation
9525  // definition and an explicit instantiation declaration. An explicit
9526  // instantiation declaration begins with the extern keyword. [...]
9527  TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9530 
9532  !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9533  // Check for dllexport class template instantiation declarations,
9534  // except for MinGW mode.
9535  for (const ParsedAttr &AL : Attr) {
9536  if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9537  Diag(ExternLoc,
9538  diag::warn_attribute_dllexport_explicit_instantiation_decl);
9539  Diag(AL.getLoc(), diag::note_attribute);
9540  break;
9541  }
9542  }
9543 
9544  if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9545  Diag(ExternLoc,
9546  diag::warn_attribute_dllexport_explicit_instantiation_decl);
9547  Diag(A->getLocation(), diag::note_attribute);
9548  }
9549  }
9550 
9551  // In MSVC mode, dllimported explicit instantiation definitions are treated as
9552  // instantiation declarations for most purposes.
9553  bool DLLImportExplicitInstantiationDef = false;
9555  Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9556  // Check for dllimport class template instantiation definitions.
9557  bool DLLImport =
9558  ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9559  for (const ParsedAttr &AL : Attr) {
9560  if (AL.getKind() == ParsedAttr::AT_DLLImport)
9561  DLLImport = true;
9562  if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9563  // dllexport trumps dllimport here.
9564  DLLImport = false;
9565  break;
9566  }
9567  }
9568  if (DLLImport) {
9570  DLLImportExplicitInstantiationDef = true;
9571  }
9572  }
9573 
9574  // Translate the parser's template argument list in our AST format.
9575  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9576  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9577 
9578  // Check that the template argument list is well-formed for this
9579  // template.
9580  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
9581  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
9582  false, SugaredConverted, CanonicalConverted,
9583  /*UpdateArgsWithConversions=*/true))
9584  return true;
9585 
9586  // Find the class template specialization declaration that
9587  // corresponds to these arguments.
9588  void *InsertPos = nullptr;
9590  ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
9591 
9592  TemplateSpecializationKind PrevDecl_TSK
9593  = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9594 
9595  if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9596  Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9597  // Check for dllexport class template instantiation definitions in MinGW
9598  // mode, if a previous declaration of the instantiation was seen.
9599  for (const ParsedAttr &AL : Attr) {
9600  if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9601  Diag(AL.getLoc(),
9602  diag::warn_attribute_dllexport_explicit_instantiation_def);
9603  break;
9604  }
9605  }
9606  }
9607 
9608  if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9609  SS.isSet(), TSK))
9610  return true;
9611 
9613 
9614  bool HasNoEffect = false;
9615  if (PrevDecl) {
9616  if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
9617  PrevDecl, PrevDecl_TSK,
9618  PrevDecl->getPointOfInstantiation(),
9619  HasNoEffect))
9620  return PrevDecl;
9621 
9622  // Even though HasNoEffect == true means that this explicit instantiation
9623  // has no effect on semantics, we go on to put its syntax in the AST.
9624 
9625  if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9626  PrevDecl_TSK == TSK_Undeclared) {
9627  // Since the only prior class template specialization with these
9628  // arguments was referenced but not declared, reuse that
9629  // declaration node as our own, updating the source location
9630  // for the template name to reflect our new declaration.
9631  // (Other source locations will be updated later.)
9632  Specialization = PrevDecl;
9633  Specialization->setLocation(TemplateNameLoc);
9634  PrevDecl = nullptr;
9635  }
9636 
9637  if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9638  DLLImportExplicitInstantiationDef) {
9639  // The new specialization might add a dllimport attribute.
9640  HasNoEffect = false;
9641  }
9642  }
9643 
9644  if (!Specialization) {
9645  // Create a new class template specialization declaration node for
9646  // this explicit specialization.
9648  Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9649  ClassTemplate, CanonicalConverted, PrevDecl);
9651 
9652  // A MSInheritanceAttr attached to the previous declaration must be
9653  // propagated to the new node prior to instantiation.
9654  if (PrevDecl) {
9655  if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
9656  auto *Clone = A->clone(getASTContext());
9657  Clone->setInherited(true);
9658  Specialization->addAttr(Clone);
9659  Consumer.AssignInheritanceModel(Specialization);
9660  }
9661  }
9662 
9663  if (!HasNoEffect && !PrevDecl) {
9664  // Insert the new specialization.
9665  ClassTemplate->AddSpecialization(Specialization, InsertPos);
9666  }
9667  }
9668 
9669  Specialization->setTemplateArgsAsWritten(TemplateArgs);
9670 
9671  // Set source locations for keywords.
9672  Specialization->setExternKeywordLoc(ExternLoc);
9673  Specialization->setTemplateKeywordLoc(TemplateLoc);
9674  Specialization->setBraceRange(SourceRange());
9675 
9676  bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
9677  ProcessDeclAttributeList(S, Specialization, Attr);
9679 
9680  // Add the explicit instantiation into its lexical context. However,
9681  // since explicit instantiations are never found by name lookup, we
9682  // just put it into the declaration context directly.
9683  Specialization->setLexicalDeclContext(CurContext);
9684  CurContext->addDecl(Specialization);
9685 
9686  // Syntax is now OK, so return if it has no other effect on semantics.
9687  if (HasNoEffect) {
9688  // Set the template specialization kind.
9689  Specialization->setTemplateSpecializationKind(TSK);
9690  return Specialization;
9691  }
9692 
9693  // C++ [temp.explicit]p3:
9694  // A definition of a class template or class member template
9695  // shall be in scope at the point of the explicit instantiation of
9696  // the class template or class member template.
9697  //
9698  // This check comes when we actually try to perform the
9699  // instantiation.
9701  = cast_or_null<ClassTemplateSpecializationDecl>(
9702  Specialization->getDefinition());
9703  if (!Def)
9704  InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
9705  else if (TSK == TSK_ExplicitInstantiationDefinition) {
9706  MarkVTableUsed(TemplateNameLoc, Specialization, true);
9707  Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9708  }
9709 
9710  // Instantiate the members of this class template specialization.
9711  Def = cast_or_null<ClassTemplateSpecializationDecl>(
9712  Specialization->getDefinition());
9713  if (Def) {
9715  // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9716  // TSK_ExplicitInstantiationDefinition
9717  if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
9719  DLLImportExplicitInstantiationDef)) {
9720  // FIXME: Need to notify the ASTMutationListener that we did this.
9722 
9723  if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
9725  // An explicit instantiation definition can add a dll attribute to a
9726  // template with a previous instantiation declaration. MinGW doesn't
9727  // allow this.
9728  auto *A = cast<InheritableAttr>(
9729  getDLLAttr(Specialization)->clone(getASTContext()));
9730  A->setInherited(true);
9731  Def->addAttr(A);
9733  }
9734  }
9735 
9736  // Fix a TSK_ImplicitInstantiation followed by a
9737  // TSK_ExplicitInstantiationDefinition
9738  bool NewlyDLLExported =
9739  !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9740  if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
9742  // An explicit instantiation definition can add a dll attribute to a
9743  // template with a previous implicit instantiation. MinGW doesn't allow
9744  // this. We limit clang to only adding dllexport, to avoid potentially
9745  // strange codegen behavior. For example, if we extend this conditional
9746  // to dllimport, and we have a source file calling a method on an
9747  // implicitly instantiated template class instance and then declaring a
9748  // dllimport explicit instantiation definition for the same template
9749  // class, the codegen for the method call will not respect the dllimport,
9750  // while it will with cl. The Def will already have the DLL attribute,
9751  // since the Def and Specialization will be the same in the case of
9752  // Old_TSK == TSK_ImplicitInstantiation, and we already added the
9753  // attribute to the Specialization; we just need to make it take effect.
9754  assert(Def == Specialization &&
9755  "Def and Specialization should match for implicit instantiation");
9757  }
9758 
9759  // In MinGW mode, export the template instantiation if the declaration
9760  // was marked dllexport.
9761  if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9762  Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
9763  PrevDecl->hasAttr<DLLExportAttr>()) {
9765  }
9766 
9767  // Set the template specialization kind. Make sure it is set before
9768  // instantiating the members which will trigger ASTConsumer callbacks.
9769  Specialization->setTemplateSpecializationKind(TSK);
9770  InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
9771  } else {
9772 
9773  // Set the template specialization kind.
9774  Specialization->setTemplateSpecializationKind(TSK);
9775  }
9776 
9777  return Specialization;
9778 }
9779 
9780 DeclResult
9782  SourceLocation TemplateLoc, unsigned TagSpec,
9783  SourceLocation KWLoc, CXXScopeSpec &SS,
9784  IdentifierInfo *Name, SourceLocation NameLoc,
9785  const ParsedAttributesView &Attr) {
9786 
9787  bool Owned = false;
9788  bool IsDependent = false;
9789  Decl *TagD =
9790  ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
9791  Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
9792  MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
9793  false, TypeResult(), /*IsTypeSpecifier*/ false,
9794  /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside)
9795  .get();
9796  assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
9797 
9798  if (!TagD)
9799  return true;
9800 
9801  TagDecl *Tag = cast<TagDecl>(TagD);
9802  assert(!Tag->isEnum() && "shouldn't see enumerations here");
9803 
9804  if (Tag->isInvalidDecl())
9805  return true;
9806 
9807  CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
9809  if (!Pattern) {
9810  Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
9811  << Context.getTypeDeclType(Record);
9812  Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
9813  return true;
9814  }
9815 
9816  // C++0x [temp.explicit]p2:
9817  // If the explicit instantiation is for a class or member class, the
9818  // elaborated-type-specifier in the declaration shall include a
9819  // simple-template-id.
9820  //
9821  // C++98 has the same restriction, just worded differently.
9822  if (!ScopeSpecifierHasTemplateId(SS))
9823  Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
9824  << Record << SS.getRange();
9825 
9826  // C++0x [temp.explicit]p2:
9827  // There are two forms of explicit instantiation: an explicit instantiation
9828  // definition and an explicit instantiation declaration. An explicit
9829  // instantiation declaration begins with the extern keyword. [...]
9833 
9834  CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
9835 
9836  // Verify that it is okay to explicitly instantiate here.
9837  CXXRecordDecl *PrevDecl
9838  = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
9839  if (!PrevDecl && Record->getDefinition())
9840  PrevDecl = Record;
9841  if (PrevDecl) {
9843  bool HasNoEffect = false;
9844  assert(MSInfo && "No member specialization information?");
9845  if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
9846  PrevDecl,
9848  MSInfo->getPointOfInstantiation(),
9849  HasNoEffect))
9850  return true;
9851  if (HasNoEffect)
9852  return TagD;
9853  }
9854 
9855  CXXRecordDecl *RecordDef
9856  = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9857  if (!RecordDef) {
9858  // C++ [temp.explicit]p3:
9859  // A definition of a member class of a class template shall be in scope
9860  // at the point of an explicit instantiation of the member class.
9861  CXXRecordDecl *Def
9862  = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
9863  if (!Def) {
9864  Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
9865  << 0 << Record->getDeclName() << Record->getDeclContext();
9866  Diag(Pattern->getLocation(), diag::note_forward_declaration)
9867  << Pattern;
9868  return true;
9869  } else {
9870  if (InstantiateClass(NameLoc, Record, Def,
9871  getTemplateInstantiationArgs(Record),
9872  TSK))
9873  return true;
9874 
9875  RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9876  if (!RecordDef)
9877  return true;
9878  }
9879  }
9880 
9881  // Instantiate all of the members of the class.
9882  InstantiateClassMembers(NameLoc, RecordDef,
9883  getTemplateInstantiationArgs(Record), TSK);
9884 
9886  MarkVTableUsed(NameLoc, RecordDef, true);
9887 
9888  // FIXME: We don't have any representation for explicit instantiations of
9889  // member classes. Such a representation is not needed for compilation, but it
9890  // should be available for clients that want to see all of the declarations in
9891  // the source code.
9892  return TagD;
9893 }
9894 
9896  SourceLocation ExternLoc,
9897  SourceLocation TemplateLoc,
9898  Declarator &D) {
9899  // Explicit instantiations always require a name.
9900  // TODO: check if/when DNInfo should replace Name.
9901  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9902  DeclarationName Name = NameInfo.getName();
9903  if (!Name) {
9904  if (!D.isInvalidType())
9905  Diag(D.getDeclSpec().getBeginLoc(),
9906  diag::err_explicit_instantiation_requires_name)
9907  << D.getDeclSpec().getSourceRange() << D.getSourceRange();
9908 
9909  return true;
9910  }
9911 
9912  // Get the innermost enclosing declaration scope.
9913  S = S->getDeclParent();
9914 
9915  // Determine the type of the declaration.
9916  TypeSourceInfo *T = GetTypeForDeclarator(D);
9917  QualType R = T->getType();
9918  if (R.isNull())
9919  return true;
9920 
9921  // C++ [dcl.stc]p1:
9922  // A storage-class-specifier shall not be specified in [...] an explicit
9923  // instantiation (14.7.2) directive.
9924  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
9925  Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9926  << Name;
9927  return true;
9928  } else if (D.getDeclSpec().getStorageClassSpec()
9930  // Complain about then remove the storage class specifier.
9931  Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9932  << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9933 
9934  D.getMutableDeclSpec().ClearStorageClassSpecs();
9935  }
9936 
9937  // C++0x [temp.explicit]p1:
9938  // [...] An explicit instantiation of a function template shall not use the
9939  // inline or constexpr specifiers.
9940  // Presumably, this also applies to member functions of class templates as
9941  // well.
9942  if (D.getDeclSpec().isInlineSpecified())
9943  Diag(D.getDeclSpec().getInlineSpecLoc(),
9944  getLangOpts().CPlusPlus11 ?
9945  diag::err_explicit_instantiation_inline :
9946  diag::warn_explicit_instantiation_inline_0x)
9947  << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9948  if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
9949  // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9950  // not already specified.
9951  Diag(D.getDeclSpec().getConstexprSpecLoc(),
9952  diag::err_explicit_instantiation_constexpr);
9953 
9954  // A deduction guide is not on the list of entities that can be explicitly
9955  // instantiated.
9956  if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9957  Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9958  << /*explicit instantiation*/ 0;
9959  return true;
9960  }
9961 
9962  // C++0x [temp.explicit]p2:
9963  // There are two forms of explicit instantiation: an explicit instantiation
9964  // definition and an explicit instantiation declaration. An explicit
9965  // instantiation declaration begins with the extern keyword. [...]
9969 
9970  LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
9971  LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
9972  /*ObjectType=*/QualType());
9973 
9974  if (!R->isFunctionType()) {
9975  // C++ [temp.explicit]p1:
9976  // A [...] static data member of a class template can be explicitly
9977  // instantiated from the member definition associated with its class
9978  // template.
9979  // C++1y [temp.explicit]p1:
9980  // A [...] variable [...] template specialization can be explicitly
9981  // instantiated from its template.
9982  if (Previous.isAmbiguous())
9983  return true;
9984 
9985  VarDecl *Prev = Previous.getAsSingle<VarDecl>();
9986  VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
9987 
9988  if (!PrevTemplate) {
9989  if (!Prev || !Prev->isStaticDataMember()) {
9990  // We expect to see a static data member here.
9991  Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9992  << Name;
9993  for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9994  P != PEnd; ++P)
9995  Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9996  return true;
9997  }
9998 
9999  if (!Prev->getInstantiatedFromStaticDataMember()) {
10000  // FIXME: Check for explicit specialization?
10001  Diag(D.getIdentifierLoc(),
10002  diag::err_explicit_instantiation_data_member_not_instantiated)
10003  << Prev;
10004  Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10005  // FIXME: Can we provide a note showing where this was declared?
10006  return true;
10007  }
10008  } else {
10009  // Explicitly instantiate a variable template.
10010 
10011  // C++1y [dcl.spec.auto]p6:
10012  // ... A program that uses auto or decltype(auto) in a context not
10013  // explicitly allowed in this section is ill-formed.
10014  //
10015  // This includes auto-typed variable template instantiations.
10016  if (R->isUndeducedType()) {
10017  Diag(T->getTypeLoc().getBeginLoc(),
10018  diag::err_auto_not_allowed_var_inst);
10019  return true;
10020  }
10021 
10022  if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10023  // C++1y [temp.explicit]p3:
10024  // If the explicit instantiation is for a variable, the unqualified-id
10025  // in the declaration shall be a template-id.
10026  Diag(D.getIdentifierLoc(),
10027  diag::err_explicit_instantiation_without_template_id)
10028  << PrevTemplate;
10029  Diag(PrevTemplate->getLocation(),
10030  diag::note_explicit_instantiation_here);
10031  return true;
10032  }
10033 
10034  // Translate the parser's template argument list into our AST format.
10035  TemplateArgumentListInfo TemplateArgs =
10036  makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10037 
10038  DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
10039  D.getIdentifierLoc(), TemplateArgs);
10040  if (Res.isInvalid())
10041  return true;
10042 
10043  if (!Res.isUsable()) {
10044  // We somehow specified dependent template arguments in an explicit
10045  // instantiation. This should probably only happen during error
10046  // recovery.
10047  Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10048  return true;
10049  }
10050 
10051  // Ignore access control bits, we don't need them for redeclaration
10052  // checking.
10053  Prev = cast<VarDecl>(Res.get());
10054  }
10055 
10056  // C++0x [temp.explicit]p2:
10057  // If the explicit instantiation is for a member function, a member class
10058  // or a static data member of a class template specialization, the name of
10059  // the class template specialization in the qualified-id for the member
10060  // name shall be a simple-template-id.
10061  //
10062  // C++98 has the same restriction, just worded differently.
10063  //
10064  // This does not apply to variable template specializations, where the
10065  // template-id is in the unqualified-id instead.
10066  if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10067  Diag(D.getIdentifierLoc(),
10068  diag::ext_explicit_instantiation_without_qualified_id)
10069  << Prev << D.getCXXScopeSpec().getRange();
10070 
10071  CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10072 
10073  // Verify that it is okay to explicitly instantiate here.
10076  bool HasNoEffect = false;
10077  if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
10078  PrevTSK, POI, HasNoEffect))
10079  return true;
10080 
10081  if (!HasNoEffect) {
10082  // Instantiate static data member or variable template.
10083  Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10084  if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10085  VTSD->setExternKeywordLoc(ExternLoc);
10086  VTSD->setTemplateKeywordLoc(TemplateLoc);
10087  }
10088 
10089  // Merge attributes.
10090  ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10091  if (PrevTemplate)
10092  ProcessAPINotes(Prev);
10093 
10095  InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
10096  }
10097 
10098  // Check the new variable specialization against the parsed input.
10099  if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10100  Diag(T->getTypeLoc().getBeginLoc(),
10101  diag::err_invalid_var_template_spec_type)
10102  << 0 << PrevTemplate << R << Prev->getType();
10103  Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10104  << 2 << PrevTemplate->getDeclName();
10105  return true;
10106  }
10107 
10108  // FIXME: Create an ExplicitInstantiation node?
10109  return (Decl*) nullptr;
10110  }
10111 
10112  // If the declarator is a template-id, translate the parser's template
10113  // argument list into our AST format.
10114  bool HasExplicitTemplateArgs = false;
10115  TemplateArgumentListInfo TemplateArgs;
10116  if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10117  TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10118  HasExplicitTemplateArgs = true;
10119  }
10120 
10121  // C++ [temp.explicit]p1:
10122  // A [...] function [...] can be explicitly instantiated from its template.
10123  // A member function [...] of a class template can be explicitly
10124  // instantiated from the member definition associated with its class
10125  // template.
10126  UnresolvedSet<8> TemplateMatches;
10127  FunctionDecl *NonTemplateMatch = nullptr;
10128  TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
10129  for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10130  P != PEnd; ++P) {
10131  NamedDecl *Prev = *P;
10132  if (!HasExplicitTemplateArgs) {
10133  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10134  QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10135  /*AdjustExceptionSpec*/true);
10136  if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10137  if (Method->getPrimaryTemplate()) {
10138  TemplateMatches.addDecl(Method, P.getAccess());
10139  } else {
10140  // FIXME: Can this assert ever happen? Needs a test.
10141  assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
10142  NonTemplateMatch = Method;
10143  }
10144  }
10145  }
10146  }
10147 
10148  FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10149  if (!FunTmpl)
10150  continue;
10151 
10152  TemplateDeductionInfo Info(FailedCandidates.getLocation());
10153  FunctionDecl *Specialization = nullptr;
10155  FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10156  Specialization, Info);
10158  // Keep track of almost-matches.
10159  FailedCandidates.addCandidate()
10160  .set(P.getPair(), FunTmpl->getTemplatedDecl(),
10161  MakeDeductionFailureInfo(Context, TDK, Info));
10162  (void)TDK;
10163  continue;
10164  }
10165 
10166  // Target attributes are part of the cuda function signature, so
10167  // the cuda target of the instantiated function must match that of its
10168  // template. Given that C++ template deduction does not take
10169  // target attributes into account, we reject candidates here that
10170  // have a different target.
10171  if (LangOpts.CUDA &&
10172  CUDA().IdentifyTarget(Specialization,
10173  /* IgnoreImplicitHDAttr = */ true) !=
10174  CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10175  FailedCandidates.addCandidate().set(
10176  P.getPair(), FunTmpl->getTemplatedDecl(),
10179  continue;
10180  }
10181 
10182  TemplateMatches.addDecl(Specialization, P.getAccess());
10183  }
10184 
10185  FunctionDecl *Specialization = NonTemplateMatch;
10186  if (!Specialization) {
10187  // Find the most specialized function template specialization.
10188  UnresolvedSetIterator Result = getMostSpecialized(
10189  TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
10190  D.getIdentifierLoc(),
10191  PDiag(diag::err_explicit_instantiation_not_known) << Name,
10192  PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10193  PDiag(diag::note_explicit_instantiation_candidate));
10194 
10195  if (Result == TemplateMatches.end())
10196  return true;
10197 
10198  // Ignore access control bits, we don't need them for redeclaration checking.
10199  Specialization = cast<FunctionDecl>(*Result);
10200  }
10201 
10202  // C++11 [except.spec]p4
10203  // In an explicit instantiation an exception-specification may be specified,
10204  // but is not required.
10205  // If an exception-specification is specified in an explicit instantiation
10206  // directive, it shall be compatible with the exception-specifications of
10207  // other declarations of that function.
10208  if (auto *FPT = R->getAs<FunctionProtoType>())
10209  if (FPT->hasExceptionSpec()) {
10210  unsigned DiagID =
10211  diag::err_mismatched_exception_spec_explicit_instantiation;
10212  if (getLangOpts().MicrosoftExt)
10213  DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10214  bool Result = CheckEquivalentExceptionSpec(
10215  PDiag(DiagID) << Specialization->getType(),
10216  PDiag(diag::note_explicit_instantiation_here),
10217  Specialization->getType()->getAs<FunctionProtoType>(),
10218  Specialization->getLocation(), FPT, D.getBeginLoc());
10219  // In Microsoft mode, mismatching exception specifications just cause a
10220  // warning.
10221  if (!getLangOpts().MicrosoftExt && Result)
10222  return true;
10223  }
10224 
10225  if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10226  Diag(D.getIdentifierLoc(),
10227  diag::err_explicit_instantiation_member_function_not_instantiated)
10228  << Specialization
10229  << (Specialization->getTemplateSpecializationKind() ==
10231  Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10232  return true;
10233  }
10234 
10235  FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10236  if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10237  PrevDecl = Specialization;
10238 
10239  if (PrevDecl) {
10240  bool HasNoEffect = false;
10241  if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10242  PrevDecl,
10243  PrevDecl->getTemplateSpecializationKind(),
10244  PrevDecl->getPointOfInstantiation(),
10245  HasNoEffect))
10246  return true;
10247 
10248  // FIXME: We may still want to build some representation of this
10249  // explicit specialization.
10250  if (HasNoEffect)
10251  return (Decl*) nullptr;
10252  }
10253 
10254  // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10255  // functions
10256  // valarray<size_t>::valarray(size_t) and
10257  // valarray<size_t>::~valarray()
10258  // that it declared to have internal linkage with the internal_linkage
10259  // attribute. Ignore the explicit instantiation declaration in this case.
10260  if (Specialization->hasAttr<InternalLinkageAttr>() &&
10262  if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10263  if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10264  RD->isInStdNamespace())
10265  return (Decl*) nullptr;
10266  }
10267 
10268  ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10270 
10271  // In MSVC mode, dllimported explicit instantiation definitions are treated as
10272  // instantiation declarations.
10274  Specialization->hasAttr<DLLImportAttr>() &&
10275  Context.getTargetInfo().getCXXABI().isMicrosoft())
10277 
10278  Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10279 
10280  if (Specialization->isDefined()) {
10281  // Let the ASTConsumer know that this function has been explicitly
10282  // instantiated now, and its linkage might have changed.
10283  Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
10284  } else if (TSK == TSK_ExplicitInstantiationDefinition)
10285  InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10286 
10287  // C++0x [temp.explicit]p2:
10288  // If the explicit instantiation is for a member function, a member class
10289  // or a static data member of a class template specialization, the name of
10290  // the class template specialization in the qualified-id for the member
10291  // name shall be a simple-template-id.
10292  //
10293  // C++98 has the same restriction, just worded differently.
10294  FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10295  if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10296  D.getCXXScopeSpec().isSet() &&
10297  !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10298  Diag(D.getIdentifierLoc(),
10299  diag::ext_explicit_instantiation_without_qualified_id)
10300  << Specialization << D.getCXXScopeSpec().getRange();
10301 
10303  *this,
10304  FunTmpl ? (NamedDecl *)FunTmpl
10305  : Specialization->getInstantiatedFromMemberFunction(),
10306  D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10307 
10308  // FIXME: Create some kind of ExplicitInstantiationDecl here.
10309  return (Decl*) nullptr;
10310 }
10311 
10313  const CXXScopeSpec &SS,
10314  const IdentifierInfo *Name,
10315  SourceLocation TagLoc,
10316  SourceLocation NameLoc) {
10317  // This has to hold, because SS is expected to be defined.
10318  assert(Name && "Expected a name in a dependent tag");
10319 
10320  NestedNameSpecifier *NNS = SS.getScopeRep();
10321  if (!NNS)
10322  return true;
10323 
10325 
10326  if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
10327  Diag(NameLoc, diag::err_dependent_tag_decl)
10328  << (TUK == TagUseKind::Definition) << llvm::to_underlying(Kind)
10329  << SS.getRange();
10330  return true;
10331  }
10332 
10333  // Create the resulting type.
10335  QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
10336 
10337  // Create type-source location information for this type.
10338  TypeLocBuilder TLB;
10340  TL.setElaboratedKeywordLoc(TagLoc);
10341  TL.setQualifierLoc(SS.getWithLocInContext(Context));
10342  TL.setNameLoc(NameLoc);
10343  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
10344 }
10345 
10347  const CXXScopeSpec &SS,
10348  const IdentifierInfo &II,
10349  SourceLocation IdLoc,
10350  ImplicitTypenameContext IsImplicitTypename) {
10351  if (SS.isInvalid())
10352  return true;
10353 
10354  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10355  Diag(TypenameLoc,
10356  getLangOpts().CPlusPlus11 ?
10357  diag::warn_cxx98_compat_typename_outside_of_template :
10358  diag::ext_typename_outside_of_template)
10359  << FixItHint::CreateRemoval(TypenameLoc);
10360 
10361  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10362  TypeSourceInfo *TSI = nullptr;
10363  QualType T =
10364  CheckTypenameType((TypenameLoc.isValid() ||
10365  IsImplicitTypename == ImplicitTypenameContext::Yes)
10368  TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
10369  /*DeducedTSTContext=*/true);
10370  if (T.isNull())
10371  return true;
10372  return CreateParsedType(T, TSI);
10373 }
10374 
10375 TypeResult
10377  const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
10378  TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
10379  SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
10380  ASTTemplateArgsPtr TemplateArgsIn,
10381  SourceLocation RAngleLoc) {
10382  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10383  Diag(TypenameLoc,
10384  getLangOpts().CPlusPlus11 ?
10385  diag::warn_cxx98_compat_typename_outside_of_template :
10386  diag::ext_typename_outside_of_template)
10387  << FixItHint::CreateRemoval(TypenameLoc);
10388 
10389  // Strangely, non-type results are not ignored by this lookup, so the
10390  // program is ill-formed if it finds an injected-class-name.
10391  if (TypenameLoc.isValid()) {
10392  auto *LookupRD =
10393  dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10394  if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10395  Diag(TemplateIILoc,
10396  diag::ext_out_of_line_qualified_id_type_names_constructor)
10397  << TemplateII << 0 /*injected-class-name used as template name*/
10398  << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10399  }
10400  }
10401 
10402  // Translate the parser's template argument list in our AST format.
10403  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10404  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10405 
10406  TemplateName Template = TemplateIn.get();
10407  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10408  // Construct a dependent template specialization type.
10409  assert(DTN && "dependent template has non-dependent name?");
10410  assert(DTN->getQualifier() == SS.getScopeRep());
10411 
10412  if (!DTN->isIdentifier()) {
10413  Diag(TemplateIILoc, diag::err_template_id_not_a_type) << Template;
10414  NoteAllFoundTemplates(Template);
10415  return true;
10416  }
10417 
10419  ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
10420  DTN->getIdentifier(), TemplateArgs.arguments());
10421 
10422  // Create source-location information for this type.
10423  TypeLocBuilder Builder;
10425  = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
10426  SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10427  SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
10428  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10429  SpecTL.setTemplateNameLoc(TemplateIILoc);
10430  SpecTL.setLAngleLoc(LAngleLoc);
10431  SpecTL.setRAngleLoc(RAngleLoc);
10432  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10433  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10434  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
10435  }
10436 
10437  QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
10438  if (T.isNull())
10439  return true;
10440 
10441  // Provide source-location information for the template specialization type.
10442  TypeLocBuilder Builder;
10444  = Builder.push<TemplateSpecializationTypeLoc>(T);
10445  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10446  SpecTL.setTemplateNameLoc(TemplateIILoc);
10447  SpecTL.setLAngleLoc(LAngleLoc);
10448  SpecTL.setRAngleLoc(RAngleLoc);
10449  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10450  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10451 
10453  SS.getScopeRep(), T);
10454  ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10455  TL.setElaboratedKeywordLoc(TypenameLoc);
10456  TL.setQualifierLoc(SS.getWithLocInContext(Context));
10457 
10458  TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10459  return CreateParsedType(T, TSI);
10460 }
10461 
10462 /// Determine whether this failed name lookup should be treated as being
10463 /// disabled by a usage of std::enable_if.
10465  SourceRange &CondRange, Expr *&Cond) {
10466  // We must be looking for a ::type...
10467  if (!II.isStr("type"))
10468  return false;
10469 
10470  // ... within an explicitly-written template specialization...
10471  if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10472  return false;
10473  TypeLoc EnableIfTy = NNS.getTypeLoc();
10474  TemplateSpecializationTypeLoc EnableIfTSTLoc =
10475  EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
10476  if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10477  return false;
10478  const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10479 
10480  // ... which names a complete class template declaration...
10481  const TemplateDecl *EnableIfDecl =
10482  EnableIfTST->getTemplateName().getAsTemplateDecl();
10483  if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10484  return false;
10485 
10486  // ... called "enable_if".
10487  const IdentifierInfo *EnableIfII =
10488  EnableIfDecl->getDeclName().getAsIdentifierInfo();
10489  if (!EnableIfII || !EnableIfII->isStr("enable_if"))
10490  return false;
10491 
10492  // Assume the first template argument is the condition.
10493  CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
10494 
10495  // Dig out the condition.
10496  Cond = nullptr;
10497  if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
10499  return true;
10500 
10501  Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
10502 
10503  // Ignore Boolean literals; they add no value.
10504  if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
10505  Cond = nullptr;
10506 
10507  return true;
10508 }
10509 
10510 QualType
10512  SourceLocation KeywordLoc,
10513  NestedNameSpecifierLoc QualifierLoc,
10514  const IdentifierInfo &II,
10515  SourceLocation IILoc,
10516  TypeSourceInfo **TSI,
10517  bool DeducedTSTContext) {
10518  QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
10519  DeducedTSTContext);
10520  if (T.isNull())
10521  return QualType();
10522 
10523  *TSI = Context.CreateTypeSourceInfo(T);
10524  if (isa<DependentNameType>(T)) {
10526  (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
10527  TL.setElaboratedKeywordLoc(KeywordLoc);
10528  TL.setQualifierLoc(QualifierLoc);
10529  TL.setNameLoc(IILoc);
10530  } else {
10531  ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
10532  TL.setElaboratedKeywordLoc(KeywordLoc);
10533  TL.setQualifierLoc(QualifierLoc);
10534  TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
10535  }
10536  return T;
10537 }
10538 
10539 /// Build the type that describes a C++ typename specifier,
10540 /// e.g., "typename T::type".
10541 QualType
10543  SourceLocation KeywordLoc,
10544  NestedNameSpecifierLoc QualifierLoc,
10545  const IdentifierInfo &II,
10546  SourceLocation IILoc, bool DeducedTSTContext) {
10547  CXXScopeSpec SS;
10548  SS.Adopt(QualifierLoc);
10549 
10550  DeclContext *Ctx = nullptr;
10551  if (QualifierLoc) {
10552  Ctx = computeDeclContext(SS);
10553  if (!Ctx) {
10554  // If the nested-name-specifier is dependent and couldn't be
10555  // resolved to a type, build a typename type.
10556  assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
10557  return Context.getDependentNameType(Keyword,
10558  QualifierLoc.getNestedNameSpecifier(),
10559  &II);
10560  }
10561 
10562  // If the nested-name-specifier refers to the current instantiation,
10563  // the "typename" keyword itself is superfluous. In C++03, the
10564  // program is actually ill-formed. However, DR 382 (in C++0x CD1)
10565  // allows such extraneous "typename" keywords, and we retroactively
10566  // apply this DR to C++03 code with only a warning. In any case we continue.
10567 
10568  if (RequireCompleteDeclContext(SS, Ctx))
10569  return QualType();
10570  }
10571 
10572  DeclarationName Name(&II);
10573  LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
10574  if (Ctx)
10575  LookupQualifiedName(Result, Ctx, SS);
10576  else
10577  LookupName(Result, CurScope);
10578  unsigned DiagID = 0;
10579  Decl *Referenced = nullptr;
10580  switch (Result.getResultKind()) {
10581  case LookupResult::NotFound: {
10582  // If we're looking up 'type' within a template named 'enable_if', produce
10583  // a more specific diagnostic.
10584  SourceRange CondRange;
10585  Expr *Cond = nullptr;
10586  if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10587  // If we have a condition, narrow it down to the specific failed
10588  // condition.
10589  if (Cond) {
10590  Expr *FailedCond;
10591  std::string FailedDescription;
10592  std::tie(FailedCond, FailedDescription) =
10593  findFailedBooleanCondition(Cond);
10594 
10595  Diag(FailedCond->getExprLoc(),
10596  diag::err_typename_nested_not_found_requirement)
10597  << FailedDescription
10598  << FailedCond->getSourceRange();
10599  return QualType();
10600  }
10601 
10602  Diag(CondRange.getBegin(),
10603  diag::err_typename_nested_not_found_enable_if)
10604  << Ctx << CondRange;
10605  return QualType();
10606  }
10607 
10608  DiagID = Ctx ? diag::err_typename_nested_not_found
10609  : diag::err_unknown_typename;
10610  break;
10611  }
10612 
10614  // We found a using declaration that is a value. Most likely, the using
10615  // declaration itself is meant to have the 'typename' keyword.
10616  SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10617  IILoc);
10618  Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10619  << Name << Ctx << FullRange;
10620  if (UnresolvedUsingValueDecl *Using
10621  = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
10622  SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
10623  Diag(Loc, diag::note_using_value_decl_missing_typename)
10624  << FixItHint::CreateInsertion(Loc, "typename ");
10625  }
10626  }
10627  // Fall through to create a dependent typename type, from which we can recover
10628  // better.
10629  [[fallthrough]];
10630 
10632  // Okay, it's a member of an unknown instantiation.
10633  return Context.getDependentNameType(Keyword,
10634  QualifierLoc.getNestedNameSpecifier(),
10635  &II);
10636 
10637  case LookupResult::Found:
10638  if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
10639  // C++ [class.qual]p2:
10640  // In a lookup in which function names are not ignored and the
10641  // nested-name-specifier nominates a class C, if the name specified
10642  // after the nested-name-specifier, when looked up in C, is the
10643  // injected-class-name of C [...] then the name is instead considered
10644  // to name the constructor of class C.
10645  //
10646  // Unlike in an elaborated-type-specifier, function names are not ignored
10647  // in typename-specifier lookup. However, they are ignored in all the
10648  // contexts where we form a typename type with no keyword (that is, in
10649  // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10650  //
10651  // FIXME: That's not strictly true: mem-initializer-id lookup does not
10652  // ignore functions, but that appears to be an oversight.
10653  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10654  auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10655  if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
10656  FoundRD->isInjectedClassName() &&
10657  declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10658  Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10659  << &II << 1 << 0 /*'typename' keyword used*/;
10660 
10661  // We found a type. Build an ElaboratedType, since the
10662  // typename-specifier was just sugar.
10663  MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
10664  return Context.getElaboratedType(Keyword,
10665  QualifierLoc.getNestedNameSpecifier(),
10666  Context.getTypeDeclType(Type));
10667  }
10668 
10669  // C++ [dcl.type.simple]p2:
10670  // A type-specifier of the form
10671  // typename[opt] nested-name-specifier[opt] template-name
10672  // is a placeholder for a deduced class type [...].
10673  if (getLangOpts().CPlusPlus17) {
10674  if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10675  if (!DeducedTSTContext) {
10676  QualType T(QualifierLoc
10677  ? QualifierLoc.getNestedNameSpecifier()->getAsType()
10678  : nullptr, 0);
10679  if (!T.isNull())
10680  Diag(IILoc, diag::err_dependent_deduced_tst)
10681  << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T;
10682  else
10683  Diag(IILoc, diag::err_deduced_tst)
10684  << (int)getTemplateNameKindForDiagnostics(TemplateName(TD));
10685  NoteTemplateLocation(*TD);
10686  return QualType();
10687  }
10688  return Context.getElaboratedType(
10689  Keyword, QualifierLoc.getNestedNameSpecifier(),
10691  QualType(), false));
10692  }
10693  }
10694 
10695  DiagID = Ctx ? diag::err_typename_nested_not_type
10696  : diag::err_typename_not_type;
10697  Referenced = Result.getFoundDecl();
10698  break;
10699 
10701  DiagID = Ctx ? diag::err_typename_nested_not_type
10702  : diag::err_typename_not_type;
10703  Referenced = *Result.begin();
10704  break;
10705 
10707  return QualType();
10708  }
10709 
10710  // If we get here, it's because name lookup did not find a
10711  // type. Emit an appropriate diagnostic and return an error.
10712  SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10713  IILoc);
10714  if (Ctx)
10715  Diag(IILoc, DiagID) << FullRange << Name << Ctx;
10716  else
10717  Diag(IILoc, DiagID) << FullRange << Name;
10718  if (Referenced)
10719  Diag(Referenced->getLocation(),
10720  Ctx ? diag::note_typename_member_refers_here
10721  : diag::note_typename_refers_here)
10722  << Name;
10723  return QualType();
10724 }
10725 
10726 namespace {
10727  // See Sema::RebuildTypeInCurrentInstantiation
10728  class CurrentInstantiationRebuilder
10729  : public TreeTransform<CurrentInstantiationRebuilder> {
10731  DeclarationName Entity;
10732 
10733  public:
10735 
10736  CurrentInstantiationRebuilder(Sema &SemaRef,
10738  DeclarationName Entity)
10739  : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
10740  Loc(Loc), Entity(Entity) { }
10741 
10742  /// Determine whether the given type \p T has already been
10743  /// transformed.
10744  ///
10745  /// For the purposes of type reconstruction, a type has already been
10746  /// transformed if it is NULL or if it is not dependent.
10747  bool AlreadyTransformed(QualType T) {
10748  return T.isNull() || !T->isInstantiationDependentType();
10749  }
10750 
10751  /// Returns the location of the entity whose type is being
10752  /// rebuilt.
10753  SourceLocation getBaseLocation() { return Loc; }
10754 
10755  /// Returns the name of the entity whose type is being rebuilt.
10756  DeclarationName getBaseEntity() { return Entity; }
10757 
10758  /// Sets the "base" location and entity when that
10759  /// information is known based on another transformation.
10760  void setBase(SourceLocation Loc, DeclarationName Entity) {
10761  this->Loc = Loc;
10762  this->Entity = Entity;
10763  }
10764 
10765  ExprResult TransformLambdaExpr(LambdaExpr *E) {
10766  // Lambdas never need to be transformed.
10767  return E;
10768  }
10769  };
10770 } // end anonymous namespace
10771 
10774  DeclarationName Name) {
10775  if (!T || !T->getType()->isInstantiationDependentType())
10776  return T;
10777 
10778  CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
10779  return Rebuilder.TransformType(T);
10780 }
10781 
10783  CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
10784  DeclarationName());
10785  return Rebuilder.TransformExpr(E);
10786 }
10787 
10789  if (SS.isInvalid())
10790  return true;
10791 
10792  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10793  CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
10794  DeclarationName());
10795  NestedNameSpecifierLoc Rebuilt
10796  = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
10797  if (!Rebuilt)
10798  return true;
10799 
10800  SS.Adopt(Rebuilt);
10801  return false;
10802 }
10803 
10805  TemplateParameterList *Params) {
10806  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10807  Decl *Param = Params->getParam(I);
10808 
10809  // There is nothing to rebuild in a type parameter.
10810  if (isa<TemplateTypeParmDecl>(Param))
10811  continue;
10812 
10813  // Rebuild the template parameter list of a template template parameter.
10814  if (TemplateTemplateParmDecl *TTP
10815  = dyn_cast<TemplateTemplateParmDecl>(Param)) {
10816  if (RebuildTemplateParamsInCurrentInstantiation(
10817  TTP->getTemplateParameters()))
10818  return true;
10819 
10820  continue;
10821  }
10822 
10823  // Rebuild the type of a non-type template parameter.
10824  NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
10825  TypeSourceInfo *NewTSI
10826  = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
10827  NTTP->getLocation(),
10828  NTTP->getDeclName());
10829  if (!NewTSI)
10830  return true;
10831 
10832  if (NewTSI->getType()->isUndeducedType()) {
10833  // C++17 [temp.dep.expr]p3:
10834  // An id-expression is type-dependent if it contains
10835  // - an identifier associated by name lookup with a non-type
10836  // template-parameter declared with a type that contains a
10837  // placeholder type (7.1.7.4),
10838  NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
10839  }
10840 
10841  if (NewTSI != NTTP->getTypeSourceInfo()) {
10842  NTTP->setTypeSourceInfo(NewTSI);
10843  NTTP->setType(NewTSI->getType());
10844  }
10845  }
10846 
10847  return false;
10848 }
10849 
10850 std::string
10852  const TemplateArgumentList &Args) {
10853  return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
10854 }
10855 
10856 std::string
10858  const TemplateArgument *Args,
10859  unsigned NumArgs) {
10860  SmallString<128> Str;
10861  llvm::raw_svector_ostream Out(Str);
10862 
10863  if (!Params || Params->size() == 0 || NumArgs == 0)
10864  return std::string();
10865 
10866  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10867  if (I >= NumArgs)
10868  break;
10869 
10870  if (I == 0)
10871  Out << "[with ";
10872  else
10873  Out << ", ";
10874 
10875  if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
10876  Out << Id->getName();
10877  } else {
10878  Out << '$' << I;
10879  }
10880 
10881  Out << " = ";
10882  Args[I].print(getPrintingPolicy(), Out,
10884  getPrintingPolicy(), Params, I));
10885  }
10886 
10887  Out << ']';
10888  return std::string(Out.str());
10889 }
10890 
10892  CachedTokens &Toks) {
10893  if (!FD)
10894  return;
10895 
10896  auto LPT = std::make_unique<LateParsedTemplate>();
10897 
10898  // Take tokens to avoid allocations
10899  LPT->Toks.swap(Toks);
10900  LPT->D = FnD;
10901  LPT->FPO = getCurFPFeatures();
10902  LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
10903 
10904  FD->setLateTemplateParsed(true);
10905 }
10906 
10908  if (!FD)
10909  return;
10910  FD->setLateTemplateParsed(false);
10911 }
10912 
10914  DeclContext *DC = CurContext;
10915 
10916  while (DC) {
10917  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
10918  const FunctionDecl *FD = RD->isLocalClass();
10919  return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
10920  } else if (DC->isTranslationUnit() || DC->isNamespace())
10921  return false;
10922 
10923  DC = DC->getParent();
10924  }
10925  return false;
10926 }
10927 
10928 namespace {
10929 /// Walk the path from which a declaration was instantiated, and check
10930 /// that every explicit specialization along that path is visible. This enforces
10931 /// C++ [temp.expl.spec]/6:
10932 ///
10933 /// If a template, a member template or a member of a class template is
10934 /// explicitly specialized then that specialization shall be declared before
10935 /// the first use of that specialization that would cause an implicit
10936 /// instantiation to take place, in every translation unit in which such a
10937 /// use occurs; no diagnostic is required.
10938 ///
10939 /// and also C++ [temp.class.spec]/1:
10940 ///
10941 /// A partial specialization shall be declared before the first use of a
10942 /// class template specialization that would make use of the partial
10943 /// specialization as the result of an implicit or explicit instantiation
10944 /// in every translation unit in which such a use occurs; no diagnostic is
10945 /// required.
10946 class ExplicitSpecializationVisibilityChecker {
10947  Sema &S;
10951 
10952 public:
10953  ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
10955  : S(S), Loc(Loc), Kind(Kind) {}
10956 
10957  void check(NamedDecl *ND) {
10958  if (auto *FD = dyn_cast<FunctionDecl>(ND))
10959  return checkImpl(FD);
10960  if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10961  return checkImpl(RD);
10962  if (auto *VD = dyn_cast<VarDecl>(ND))
10963  return checkImpl(VD);
10964  if (auto *ED = dyn_cast<EnumDecl>(ND))
10965  return checkImpl(ED);
10966  }
10967 
10968 private:
10969  void diagnose(NamedDecl *D, bool IsPartialSpec) {
10972  const bool Recover = true;
10973 
10974  // If we got a custom set of modules (because only a subset of the
10975  // declarations are interesting), use them, otherwise let
10976  // diagnoseMissingImport intelligently pick some.
10977  if (Modules.empty())
10978  S.diagnoseMissingImport(Loc, D, Kind, Recover);
10979  else
10980  S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10981  }
10982 
10983  bool CheckMemberSpecialization(const NamedDecl *D) {
10987  }
10988 
10989  bool CheckExplicitSpecialization(const NamedDecl *D) {
10993  }
10994 
10995  bool CheckDeclaration(const NamedDecl *D) {
10998  }
10999 
11000  // Check a specific declaration. There are three problematic cases:
11001  //
11002  // 1) The declaration is an explicit specialization of a template
11003  // specialization.
11004  // 2) The declaration is an explicit specialization of a member of an
11005  // templated class.
11006  // 3) The declaration is an instantiation of a template, and that template
11007  // is an explicit specialization of a member of a templated class.
11008  //
11009  // We don't need to go any deeper than that, as the instantiation of the
11010  // surrounding class / etc is not triggered by whatever triggered this
11011  // instantiation, and thus should be checked elsewhere.
11012  template<typename SpecDecl>
11013  void checkImpl(SpecDecl *Spec) {
11014  bool IsHiddenExplicitSpecialization = false;
11015  if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
11016  IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11017  ? !CheckMemberSpecialization(Spec)
11018  : !CheckExplicitSpecialization(Spec);
11019  } else {
11020  checkInstantiated(Spec);
11021  }
11022 
11023  if (IsHiddenExplicitSpecialization)
11024  diagnose(Spec->getMostRecentDecl(), false);
11025  }
11026 
11027  void checkInstantiated(FunctionDecl *FD) {
11028  if (auto *TD = FD->getPrimaryTemplate())
11029  checkTemplate(TD);
11030  }
11031 
11032  void checkInstantiated(CXXRecordDecl *RD) {
11033  auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11034  if (!SD)
11035  return;
11036 
11037  auto From = SD->getSpecializedTemplateOrPartial();
11038  if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11039  checkTemplate(TD);
11040  else if (auto *TD =
11041  From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11042  if (!CheckDeclaration(TD))
11043  diagnose(TD, true);
11044  checkTemplate(TD);
11045  }
11046  }
11047 
11048  void checkInstantiated(VarDecl *RD) {
11049  auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11050  if (!SD)
11051  return;
11052 
11053  auto From = SD->getSpecializedTemplateOrPartial();
11054  if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11055  checkTemplate(TD);
11056  else if (auto *TD =
11057  From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11058  if (!CheckDeclaration(TD))
11059  diagnose(TD, true);
11060  checkTemplate(TD);
11061  }
11062  }
11063 
11064  void checkInstantiated(EnumDecl *FD) {}
11065 
11066  template<typename TemplDecl>
11067  void checkTemplate(TemplDecl *TD) {
11068  if (TD->isMemberSpecialization()) {
11069  if (!CheckMemberSpecialization(TD))
11070  diagnose(TD->getMostRecentDecl(), false);
11071  }
11072  }
11073 };
11074 } // end anonymous namespace
11075 
11077  if (!getLangOpts().Modules)
11078  return;
11079 
11080  ExplicitSpecializationVisibilityChecker(*this, Loc,
11082  .check(Spec);
11083 }
11084 
11086  NamedDecl *Spec) {
11087  if (!getLangOpts().CPlusPlusModules)
11088  return checkSpecializationVisibility(Loc, Spec);
11089 
11090  ExplicitSpecializationVisibilityChecker(*this, Loc,
11092  .check(Spec);
11093 }
11094 
11096  if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11097  return N->getLocation();
11098  if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11100  return FD->getLocation();
11103  return N->getLocation();
11104  }
11105  for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11106  if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11107  continue;
11108  return CSC.PointOfInstantiation;
11109  }
11110  return N->getLocation();
11111 }
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
int Depth
Definition: ASTDiff.cpp:190
StringRef P
Defines enum values for all the target-independent builtin functions.
const Decl * D
enum clang::sema::@1659::IndirectLocalPathEntry::EntryKind Kind
Expr * E
llvm::APSInt APSInt
Definition: Compiler.cpp:22
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1171
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
MatchFinder::MatchResult MatchResult
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
static void ProcessAPINotes(Sema &S, Decl *D, const api_notes::CommonEntityInfo &Info, VersionedInfoMetadata Metadata)
uint32_t Id
Definition: SemaARM.cpp:1144
This file declares semantic analysis for CUDA constructs.
static bool CheckConstraintSatisfaction(Sema &S, const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, llvm::SmallVectorImpl< Expr * > &Converted, const MultiLevelTemplateArgumentList &TemplateArgsLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, Sema::CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, PackFold PackFold=PackFold::ParameterToArgument)
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, const IdentifierInfo *Name)
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, unsigned HereDiagID, unsigned ExternalDiagID)
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL)
static NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type.
static ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
static Expr * BuildExpressionFromIntegralTemplateArgumentValue(Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
static bool SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, TemplateArgumentLoc &Output)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
static void StripImplicitInstantiation(NamedDecl *D, bool MinGW)
Strips various properties off an implicit instantiation that has just been explicitly specialized.
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, SourceRange &CondRange, Expr *&Cond)
Determine whether this failed name lookup should be treated as being disabled by a usage of std::enab...
static void DiagnoseTemplateParameterListArityMismatch(Sema &S, TemplateParameterList *New, TemplateParameterList *Old, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Diagnose a known arity mismatch when comparing template argument lists.
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is the address of an object or function according to C++ [...
static void collectConjunctionTerms(Expr *Clause, SmallVectorImpl< Expr * > &Terms)
Collect all of the separable terms in the given condition, which might be a conjunction.
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial)
static bool CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp....
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static bool RemoveLookupResult(LookupResult &R, NamedDecl *C)
static Expr * BuildExpressionFromNonTypeTemplateArgumentValue(Sema &S, QualType T, const APValue &Val, SourceLocation Loc)
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, ArrayRef< TemplateArgument > Args)
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static void SetNestedNameSpecifier(Sema &S, TagDecl *T, const CXXScopeSpec &SS)
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD, ArrayRef< TemplateArgument > Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, SourceLocation Loc)
Complete the explicit specialization of a member of a class template by updating the instantiated mem...
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, const NamedDecl *OldInstFrom, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
Defines the clang::SourceLocation class and associated facilities.
Defines utilities for dealing with stack allocation and stack space.
static const TemplateArgument & getArgument(const TemplateArgument &A)
StateNode * Previous
__DEVICE__ int max(int __a, int __b)
__device__ int
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
const LValueBase getLValueBase() const
Definition: APValue.cpp:974
APFloat & getFloat()
Definition: APValue.h:437
ValueKind getKind() const
Definition: APValue.h:395
APFixedPoint & getFixedPoint()
Definition: APValue.h:445
APSInt & getComplexIntReal()
Definition: APValue.h:453
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1057
unsigned getVectorLength() const
Definition: APValue.h:505
APSInt & getComplexIntImag()
Definition: APValue.h:461
bool isLValue() const
Definition: APValue.h:406
APFloat & getComplexFloatImag()
Definition: APValue.h:477
bool isMemberPointer() const
Definition: APValue.h:411
APSInt & getInt()
Definition: APValue.h:423
APFloat & getComplexFloatReal()
Definition: APValue.h:469
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
APValue & getVectorElt(unsigned I)
Definition: APValue.h:497
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition: APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition: APValue.h:129
bool isNullPointer() const
Definition: APValue.cpp:1010
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
unsigned getIntWidth(QualType T) const
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgumentLoc > Args) const
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:664
TemplateName getCanonicalTemplateName(const TemplateName &Name) const
Retrieves the "canonical" template name that refers to a given template.
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2633
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2649
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType NullPtrTy
Definition: ASTContext.h:1146
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1642
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:797
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1147
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
TypeSourceInfo * getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &Args, QualType Canon=QualType()) const
CanQualType IntTy
Definition: ASTContext.h:1128
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2215
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType OverloadTy
Definition: ASTContext.h:1147
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2680
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2399
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply.
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1620
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
void setPrimaryMergedDecl(Decl *D, Decl *Primary)
Definition: ASTContext.h:1061
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1101
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: Type.h:3746
A structure for storing the information associated with a name that has been assumed to be a template...
DeclarationName getDeclName() const
Get the name of the template.
Attr - This represents one attribute.
Definition: Attr.h:46
ConceptDecl * getNamedConcept() const
Definition: TypeLoc.h:2231
AutoTypeKeyword getAutoKeyword() const
Definition: TypeLoc.h:2189
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition: TypeLoc.h:2207
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:2257
NamedDecl * getFoundDecl() const
Definition: TypeLoc.h:2225
SourceLocation getLAngleLoc() const
Definition: TypeLoc.h:2250
DeclarationNameInfo getConceptNameInfo() const
Definition: TypeLoc.h:2237
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6385
bool isDecltypeAuto() const
Definition: Type.h:6408
A fixed int type of a specified bitwidth.
Definition: Type.h:7643
Pointer to a block type.
Definition: Type.h:3407
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
BuiltinTemplateKind getBuiltinTemplateKind() const
This class is used for builtin types like 'int'.
Definition: Type.h:3029
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition: Expr.cpp:2160
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition: ExprCXX.h:732
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition: ExprCXX.h:3682
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:1534
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXRecordDecl * getMostRecentDecl()
Definition: DeclCXX.h:541
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1915
base_class_range bases()
Definition: DeclCXX.h:620
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1944
CXXRecordDecl * getPreviousDecl()
Definition: DeclCXX.h:532
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1940
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1922
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1955
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:236
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1066
Declaration of a class template.
void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D, void *InsertPos)
Insert the specified partial specialization knowing that it is not already in.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
ClassTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, TemplateParameterList *TPL, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos)
Insert the specified specialization knowing that it is not already in.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
QualType getInjectedClassNameSpecialization()
Retrieve the template specialization type of the injected-class-name for this class template.
ClassTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, QualType CanonInjectedType, ClassTemplatePartialSpecializationDecl *PrevDecl)
void setMemberSpecialization()
Note that this member template is a specialization.
Represents a class template specialization, which refers to a class template with a given set of temp...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, ClassTemplateSpecializationDecl *PrevDecl)
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3144
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool isTypeConcept() const
Expr * getConstraintExpr() const
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr=nullptr)
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:88
static ConceptSpecializationExpr * Create(const ASTContext &C, ConceptReference *ConceptRef, ImplicitConceptSpecializationDecl *SpecDecl, const ConstraintSatisfaction *Satisfaction)
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3614
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4229
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2219
bool isFileContext() const
Definition: DeclBase.h:2161
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2043
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Definition: DeclBase.cpp:1367
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1333
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
Definition: DeclBase.cpp:2025
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
bool isNamespace() const
Definition: DeclBase.h:2179
bool isTranslationUnit() const
Definition: DeclBase.h:2166
bool isRecord() const
Definition: DeclBase.h:2170
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1988
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2006
bool isFunctionOrMethod() const
Definition: DeclBase.h:2142
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1284
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1384
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1388
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1403
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
ValueDecl * getDecl()
Definition: Expr.h:1333
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1360
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool isVirtualSpecified() const
Definition: DeclSpec.h:648
bool isNoreturnSpecified() const
Definition: DeclSpec.h:661
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:510
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:662
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:654
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:502
bool isInlineSpecified() const
Definition: DeclSpec.h:637
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:511
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:649
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:836
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:640
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:651
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:837
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
void addAttr(Attr *A)
Definition: DeclBase.cpp:1013
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:242
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1207
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:284
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:249
void dropAttrs()
Definition: DeclBase.cpp:1006
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:1054
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition: DeclBase.h:1170
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2767
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1051
bool isInvalidDecl() const
Definition: DeclBase.h:595
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:509
SourceLocation getLocation() const
Definition: DeclBase.h:446
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:232
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
AccessSpecifier getAccess() const
Definition: DeclBase.h:514
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:438
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:836
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:806
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
bool hasAttr() const
Definition: DeclBase.h:584
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:362
Kind getKind() const
Definition: DeclBase.h:449
T * getAttr() const
Definition: DeclBase.h:580
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:434
DeclContext * getDeclContext()
Definition: DeclBase.h:455
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:767
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:761
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
Represents the type decltype(expr) (C++11).
Definition: Type.h:5784
Represents a C++17 deduced template specialization type.
Definition: Type.h:6433
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6351
bool isDeduced() const
Definition: Type.h:6373
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3917
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2423
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2403
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2412
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:6853
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:3322
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:532
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3859
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3957
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4288
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:491
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:550
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:553
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:547
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2472
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2492
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2460
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2516
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2508
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2524
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2500
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:6905
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4083
bool isEmpty() const
Definition: TypeLoc.h:2365
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2361
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3845
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4104
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4941
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6001
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3127
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3122
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:822
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3102
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3998
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
ExtVectorType - Extended vector type.
Definition: Type.h:4123
Represents a member of a struct/union/class.
Definition: Decl.h:3031
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:135
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:124
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:98
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:1054
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1133
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists=std::nullopt)
Definition: DeclFriend.cpp:35
Represents a function declaration or definition.
Definition: Decl.h:1933
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2402
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4044
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:4350
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4152
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4011
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3607
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2466
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3983
void setDependentTemplateSpecialization(ASTContext &Context, const UnresolvedSetImpl &Templates, const TemplateArgumentListInfo *TemplateArgs)
Specifies that this function declaration is actually a dependent function template specialization.
Definition: Decl.cpp:4216
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition: Decl.h:2295
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4256
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3118
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4004
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4678
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5012
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5272
ArrayRef< QualType > param_types() const
Definition: Type.h:5421
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5276
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:467
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:542
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this function template specialization.
Definition: DeclTemplate.h:553
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:525
QualType getReturnType() const
Definition: Type.h:4640
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3727
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition: Type.h:3761
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:5070
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:7522
Describes an entity that is being initialized.
static InitializedEntity InitializeTemplateParameter(QualType T, NonTypeTemplateParmDecl *Param)
Create the initialization entity for a template parameter.
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:705
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6622
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:1032
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3482
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
Represents a linkage specification.
Definition: DeclCXX.h:2938
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:675
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:721
NamedDecl * next()
Definition: Lookup.h:710
bool hasNext() const
Definition: Lookup.h:706
Represents the results of name lookup.
Definition: Lookup.h:46
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:575
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition: Lookup.h:495
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
void setTemplateNameLookup(bool TemplateName)
Sets whether this is a template-name lookup.
Definition: Lookup.h:318
DeclClass * getAsSingle() const
Definition: Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition: Lookup.h:452
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:749
bool isAmbiguous() const
Definition: Lookup.h:324
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
A global _GUID constant.
Definition: DeclCXX.h:4293
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3518
QualType getPointeeType() const
Definition: Type.h:3534
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:615
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:637
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:655
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:244
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:265
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition: Template.h:210
void addOuterRetainedLevels(unsigned Num)
Definition: Template.h:260
This represents a decl that may have a name.
Definition: Decl.h:249
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:463
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:700
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1916
NamedDecl * getMostRecentDecl()
Definition: Decl.h:477
Represent a C++ namespace.
Definition: Decl.h:548
A C++ nested-name-specifier augmented with source location information.
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7353
Represents a pointer to an Objective C object.
Definition: Type.h:7409
Represents a class type in Objective C.
Definition: Type.h:7155
PtrTy get() const
Definition: Ownership.h:80
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:108
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4179
Represents a pack expansion of types.
Definition: Type.h:6970
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:254
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2187
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
Represents the parsed form of a C++ template argument.
Expr * getAsExpr() const
Retrieve the non-type template argument's expression.
KindType getKind() const
Determine what kind of template argument we have.
SourceLocation getLocation() const
Retrieve the location of the template argument.
ParsedTemplateTy getAsTemplate() const
Retrieve the template template argument's template name.
ParsedTemplateArgument getTemplatePackExpansion(SourceLocation EllipsisLoc) const
Retrieve a pack expansion of the given template template argument.
ParsedType getAsType() const
Retrieve the template type argument's type.
@ Type
A template type parameter, stored as a type.
@ Template
A template template argument, stored as a template name.
@ NonType
A non-type template parameter, stored as an expression.
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis that makes a template template argument into a pack expansion.
const CXXScopeSpec & getScopeSpec() const
Retrieve the nested-name-specifier that precedes the template name in a template template argument.
PipeType - OpenCL20.
Definition: Type.h:7609
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3197
QualType getPointeeType() const
Definition: Type.h:3207
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:137
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
A (possibly-)qualified type.
Definition: Type.h:941
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7849
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3482
void * getAsOpaquePtr() const
Definition: Type.h:988
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7760
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1444
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7961
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7854
bool isCanonical() const
Definition: Type.h:7817
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7806
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1339
The collection of all-type qualifiers we support.
Definition: Type.h:319
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:348
void addConst()
Definition: Type.h:447
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:535
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3500
Represents a struct/union/class.
Definition: Decl.h:4146
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4337
Wrapper for source info for record types.
Definition: TypeLoc.h:741
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5975
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:865
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4979
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:205
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3438
QualType getPointeeType() const
Definition: Type.h:3456
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:262
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:270
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:81
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:175
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:64
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:13250
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8094
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3037
Whether and why a template name is required in this lookup.
Definition: Sema.h:11153
SourceLocation getTemplateKeywordLoc() const
Definition: Sema.h:11161
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7270
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:493
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
ConceptDecl * ActOnStartConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, const IdentifierInfo *Name, SourceLocation NameLoc)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:9032
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9036
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack)
TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
ActOnTemplateParameterList - Builds a TemplateParameterList, optionally constrained by RequiresClause...
TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e....
bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is visible.
Definition: Sema.h:9346
void NoteAllFoundTemplates(TemplateName Name)
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, const IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
void referenceDLLExportedClassMethods()
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
bool RequireStructuralType(QualType T, SourceLocation Loc)
Require the given type to be a structural type, and diagnose if it is not.
ConceptDecl * ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C, Expr *ConstraintExpr, const ParsedAttributesView &Attrs)
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1715
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
bool hasVisibleExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is an explicit specialization declaration for a...
bool IsInsideALocalClassWithinATemplateFunction()
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
bool CheckConceptUseInDefinition(ConceptDecl *Concept, SourceLocation Loc)
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition: Sema.h:11697
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType)
Convert a parsed type into a parsed template argument.
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
ASTContext & Context
Definition: Sema.h:962
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:729
bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg, bool IsDeduced)
Check a template argument against its corresponding template template parameter.
TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
Returns the template parameter list with all default template argument information.
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:868
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition: Sema.h:11839
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition: Sema.h:11857
@ TPL_TemplateTemplateArgumentMatch
We are matching the template parameter lists of a template template argument against the template par...
Definition: Sema.h:11868
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:11847
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition: Sema.h:11878
NamedDecl * ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg, bool HasTypeConstraint)
ActOnTypeParameter - Called when a C++ template type parameter (e.g., "typename T") has been parsed.
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
AssumedTemplateKind
Definition: Sema.h:11174
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:84
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition: Sema.h:13974
@ UPPC_TypeConstraint
A type constraint.
Definition: Sema.h:13998
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, std::optional< unsigned > NumExpansions)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool hasVisibleMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is a member specialization declaration (as oppo...
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
const LangOptions & getLangOpts() const
Definition: Sema.h:553
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr, bool PartialOrderingTTP=false)
Check that the given template arguments can be provided to the given template, converting the argumen...
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:19879
AcceptableKind
Definition: Sema.h:9024
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
DeclResult 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=nullptr)
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef< const Expr * > AC1, NamedDecl *D2, ArrayRef< const Expr * > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
bool hasReachableDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a reachable default argument.
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1102
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1289
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a template name from a name that is syntactically required to name a template,...
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3867
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs)
Get the specialization of the given variable template corresponding to the specified argument list,...
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II)
Try to resolve an undeclared template name as a type template.
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14983
bool hasReachableMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is a member specialization declaration (as op...
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
ASTContext & getASTContext() const
Definition: Sema.h:560
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand)
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr)
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
bool hasReachableExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is an explicit specialization declaration for...
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, CXXScopeSpec &SS, ParsedTemplateTy *Template=nullptr)
Determine whether a particular identifier might be the name in a C++1z deduction-guide declaration.
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:584
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition: Sema.h:11339
@ TPC_ClassTemplate
Definition: Sema.h:11340
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11345
@ TPC_ClassTemplateMember
Definition: Sema.h:11343
@ TPC_FunctionTemplate
Definition: Sema.h:11342
@ TPC_FriendClassTemplate
Definition: Sema.h:11344
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11346
@ TPC_TypeAliasTemplate
Definition: Sema.h:11347
@ TPC_VarTemplate
Definition: Sema.h:11341
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, SourceLocation NameLoc, bool Diagnose=true)
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs)
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:5840
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2746
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:557
void NoteTemplateParameterLocation(const NamedDecl &Decl)
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition: Sema.h:9355
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4483
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:6293
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:6223
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3562
StringRef getKindName() const
Definition: Decl.h:3753
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4740
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4823
TagKind getTagKind() const
Definition: Decl.h:3757
bool isBeingDefined() const
Determines whether this type is in the process of being defined.
Definition: Type.cpp:4086
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1294
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:648
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:647
A template argument list.
Definition: DeclTemplate.h:244
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
Definition: DeclTemplate.h:283
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
SourceLocation getLocation() const
Definition: TemplateBase.h:563
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:578
SourceLocation getTemplateEllipsisLoc() const
Definition: TemplateBase.h:623
SourceLocation getTemplateNameLoc() const
Definition: TemplateBase.h:616
SourceRange getSourceRange() const LLVM_READONLY
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Definition: TemplateBase.h:609
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
Expr * getSourceExpression() const
Definition: TemplateBase.h:584
Represents a template argument.
Definition: TemplateBase.h:61
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
bool isInstantiationDependent() const
Whether this template argument is dependent on a template parameter.
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:418
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:363
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
Definition: TemplateBase.h:298
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
void print(const PrintingPolicy &Policy, raw_ostream &Out, bool IncludeType) const
Print this template argument to the given output stream.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:377
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:350
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
Definition: DeclTemplate.h:426
bool hasAssociatedConstraints() const
void getAssociatedConstraints(llvm::SmallVectorImpl< const Expr * > &AC) const
Get the total constraint-expression associated with this template, including constraint-expressions d...
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
bool isNull() const
Determine whether this template name is NULL.
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
bool hasAssociatedConstraints() const
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Definition: DeclTemplate.h:129
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:200
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
void getAssociatedConstraints(llvm::SmallVectorImpl< const Expr * > &AC) const
All associated constraints derived from this template parameter list, including the requires clause a...
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1687
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1663
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1695
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1704
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1671
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1679
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6490
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6556
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, ArrayRef< TemplateArgument > Converted)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:4275
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, bool Typename, TemplateParameterList *Params)
void removeDefaultArgument()
Removes the default argument of this template parameter.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isParameterPack() const
Returns whether this is a parameter pack.
unsigned getDepth() const
Retrieve the depth of the template parameter.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint)
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter.
Wrapper for template type parameters.
Definition: TypeLoc.h:758
TemplateTypeParmDecl * getDecl() const
Definition: TypeLoc.h:760
unsigned getIndex() const
Definition: Type.h:6183
unsigned getDepth() const
Definition: Type.h:6182
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3533
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:227
Represents a declaration of a type.
Definition: Decl.h:3368
const Type * getTypeForDecl() const
Definition: Decl.h:3392
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3395
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:133
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition: TypeLoc.cpp:749
bool isNull() const
Definition: TypeLoc.h:121
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5707
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5757
A container of type source information.
Definition: Type.h:7731
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7742
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier.
Definition: TypeLoc.h:528
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
An operation on a type.
Definition: TypeVisitor.h:64
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:3151
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3133
The base class of the type hierarchy.
Definition: Type.h:1829
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2434
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isBooleanType() const
Definition: Type.h:8475
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2167
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2217
bool isRValueReferenceType() const
Definition: Type.h:8039
bool isVoidPointerType() const
Definition: Type.cpp:665
bool isArrayType() const
Definition: Type.h:8085
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2806
bool isPointerType() const
Definition: Type.h:8013
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8635
bool isReferenceType() const
Definition: Type.h:8031
bool isEnumeralType() const
Definition: Type.h:8117
bool isScalarType() const
Definition: Type.h:8446
bool isChar8Type() const
Definition: Type.cpp:2105
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2058
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition: Type.cpp:427
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8462
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2125
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:8163
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2709
bool isLValueReferenceType() const
Definition: Type.h:8035
bool isBitIntType() const
Definition: Type.h:8269
bool isStructuralType() const
Determine if this type is a structural type, per C++20 [temp.param]p7.
Definition: Type.cpp:2957
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2701
bool isChar16Type() const
Definition: Type.cpp:2111
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2011
QualType getCanonicalTypeInternal() const
Definition: Type.h:2984
bool isMemberPointerType() const
Definition: Type.h:8067
bool isChar32Type() const
Definition: Type.cpp:2117
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2719
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4981
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8481
bool hasUnnamedOrLocalType() const
Whether this type is or contains a local or unnamed type.
Definition: Type.cpp:4593
bool isPointerOrReferenceType() const
Definition: Type.h:8017
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
bool isFunctionType() const
Definition: Type.h:8009
bool isVectorType() const
Definition: Type.h:8125
bool isWideCharType() const
Definition: Type.cpp:2098
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8568
bool isNullPtrType() const
Definition: Type.h:8380
bool isRecordType() const
Definition: Type.h:8113
QualType getUnderlyingType() const
Definition: Decl.h:3465
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
DeclClass * getCorrectionDeclAs() const
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2240
A unary type transform, which is a type constructed from another.
Definition: Type.h:5892
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3202
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition: ExprCXX.cpp:420
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:92
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:5577
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3866
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3324
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3388
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:668
void setType(QualType newType)
Definition: Decl.h:680
QualType getType() const
Definition: Decl.h:679
Represents a variable declaration or definition.
Definition: Decl.h:880
TLSKind getTLSKind() const
Definition: Decl.cpp:2154
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1232
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2741
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition: Decl.cpp:2868
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2769
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2748
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2859
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
void AddPartialSpecialization(VarTemplatePartialSpecializationDecl *D, void *InsertPos)
Insert the specified partial specialization knowing that it is not already in.
VarTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, TemplateParameterList *TPL, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos)
Insert the specified specialization knowing that it is not already in.
llvm::FoldingSetVector< VarTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
VarTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
void setMemberSpecialization()
Note that this member template is a specialization.
VarTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member variable template partial specialization from which this particular variable temp...
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3805
Represents a GCC generic vector type.
Definition: Type.h:4031
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
Defines the clang::TargetInfo interface.
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
std::string toString(const til::SExpr *E)
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
The JSON file list parser is used to communicate input to InstallAPI.
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
ImplicitTypenameContext
Definition: DeclSpec.h:1886
bool isa(CodeGen::Address addr)
Definition: Address.h:328
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus11
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:59
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
StorageClass
Storage classes.
Definition: Specifiers.h:248
@ SC_Extern
Definition: Specifiers.h:251
@ TSCS_unspecified
Definition: Specifiers.h:236
@ CRK_None
Candidate is not a rewritten candidate.
Definition: Overload.h:91
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:50
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
TagUseKind
Definition: Sema.h:427
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:6700
@ Enum
The "enum" keyword.
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
@ BTK__type_pack_element
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:312
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:309
ExprResult ExprError()
Definition: Ownership.h:264
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
CastKind
CastKind - The kind of operation required for a conversion.
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
std::optional< unsigned > getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
bool isSubstitutedDefaultArgument(ASTContext &Ctx, TemplateArgument Arg, const NamedDecl *Param, ArrayRef< TemplateArgument > Args, unsigned Depth)
Make a best-effort determination of whether the type T can be produced by substituting Args into the ...
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
Definition: TemplateKinds.h:20
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
@ TNK_Dependent_template_name
The name refers to a dependent template name:
Definition: TemplateKinds.h:46
@ TNK_Function_template
The name refers to a function template or a set of overloaded functions that includes at least one fu...
Definition: TemplateKinds.h:26
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
@ TNK_Non_template
The name does not refer to a template.
Definition: TemplateKinds.h:22
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
Definition: TemplateKinds.h:50
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:345
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ CUDATargetMismatch
CUDA Target attributes do not match.
@ Success
Template argument deduction was successful.
@ AlreadyDiagnosed
Some error which was already diagnosed.
ActionResult< Decl * > DeclResult
Definition: Ownership.h:254
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6675
@ None
No keyword precedes the qualified type name.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
@ Parens
New-expression has a C++98 paren-delimited initializer.
CharacterLiteralKind
Definition: Expr.h:1589
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:123
@ AS_public
Definition: Specifiers.h:124
@ AS_none
Definition: Specifiers.h:127
long int64_t
#define false
Definition: stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:630
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:609
Extra information about a function prototype.
Definition: Type.h:5097
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
unsigned PrintCanonicalTypes
Whether to print types as written or canonically.
unsigned TerseOutput
Provide a 'terse' output.
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12718
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12825
A stack object to be created when performing template instantiation.
Definition: Sema.h:12903
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:13057
NamedDecl * Previous
Definition: Sema.h:332
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
Information about a template-id annotation token.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
Contains all information for a given match.